editor_tests.rs

    1use super::*;
    2use crate::{
    3    JoinLines,
    4    scroll::scroll_amount::ScrollAmount,
    5    test::{
    6        assert_text_with_selections, build_editor,
    7        editor_lsp_test_context::{EditorLspTestContext, git_commit_lang},
    8        editor_test_context::EditorTestContext,
    9        select_ranges,
   10    },
   11};
   12use buffer_diff::{BufferDiff, DiffHunkSecondaryStatus, DiffHunkStatus, DiffHunkStatusKind};
   13use futures::StreamExt;
   14use gpui::{
   15    BackgroundExecutor, DismissEvent, SemanticVersion, TestAppContext, UpdateGlobal,
   16    VisualTestContext, WindowBounds, WindowOptions, div,
   17};
   18use indoc::indoc;
   19use language::{
   20    BracketPairConfig,
   21    Capability::ReadWrite,
   22    FakeLspAdapter, LanguageConfig, LanguageConfigOverride, LanguageMatcher, LanguageName,
   23    Override, Point,
   24    language_settings::{
   25        AllLanguageSettings, AllLanguageSettingsContent, CompletionSettings,
   26        LanguageSettingsContent, LspInsertMode, PrettierSettings,
   27    },
   28};
   29use language_settings::{Formatter, FormatterList, IndentGuideSettings};
   30use lsp::CompletionParams;
   31use multi_buffer::{IndentGuide, PathKey};
   32use parking_lot::Mutex;
   33use pretty_assertions::{assert_eq, assert_ne};
   34use project::{
   35    FakeFs,
   36    debugger::breakpoint_store::{BreakpointState, SourceBreakpoint},
   37    project_settings::{LspSettings, ProjectSettings},
   38};
   39use serde_json::{self, json};
   40use std::{cell::RefCell, future::Future, rc::Rc, sync::atomic::AtomicBool, time::Instant};
   41use std::{
   42    iter,
   43    sync::atomic::{self, AtomicUsize},
   44};
   45use test::{build_editor_with_project, editor_lsp_test_context::rust_lang};
   46use text::ToPoint as _;
   47use unindent::Unindent;
   48use util::{
   49    assert_set_eq, path,
   50    test::{TextRangeMarker, marked_text_ranges, marked_text_ranges_by, sample_text},
   51    uri,
   52};
   53use workspace::{
   54    CloseAllItems, CloseInactiveItems, NavigationEntry, ViewId,
   55    item::{FollowEvent, FollowableItem, Item, ItemHandle},
   56};
   57
   58#[gpui::test]
   59fn test_edit_events(cx: &mut TestAppContext) {
   60    init_test(cx, |_| {});
   61
   62    let buffer = cx.new(|cx| {
   63        let mut buffer = language::Buffer::local("123456", cx);
   64        buffer.set_group_interval(Duration::from_secs(1));
   65        buffer
   66    });
   67
   68    let events = Rc::new(RefCell::new(Vec::new()));
   69    let editor1 = cx.add_window({
   70        let events = events.clone();
   71        |window, cx| {
   72            let entity = cx.entity().clone();
   73            cx.subscribe_in(
   74                &entity,
   75                window,
   76                move |_, _, event: &EditorEvent, _, _| match event {
   77                    EditorEvent::Edited { .. } => events.borrow_mut().push(("editor1", "edited")),
   78                    EditorEvent::BufferEdited => {
   79                        events.borrow_mut().push(("editor1", "buffer edited"))
   80                    }
   81                    _ => {}
   82                },
   83            )
   84            .detach();
   85            Editor::for_buffer(buffer.clone(), None, window, cx)
   86        }
   87    });
   88
   89    let editor2 = cx.add_window({
   90        let events = events.clone();
   91        |window, cx| {
   92            cx.subscribe_in(
   93                &cx.entity().clone(),
   94                window,
   95                move |_, _, event: &EditorEvent, _, _| match event {
   96                    EditorEvent::Edited { .. } => events.borrow_mut().push(("editor2", "edited")),
   97                    EditorEvent::BufferEdited => {
   98                        events.borrow_mut().push(("editor2", "buffer edited"))
   99                    }
  100                    _ => {}
  101                },
  102            )
  103            .detach();
  104            Editor::for_buffer(buffer.clone(), None, window, cx)
  105        }
  106    });
  107
  108    assert_eq!(mem::take(&mut *events.borrow_mut()), []);
  109
  110    // Mutating editor 1 will emit an `Edited` event only for that editor.
  111    _ = editor1.update(cx, |editor, window, cx| editor.insert("X", window, cx));
  112    assert_eq!(
  113        mem::take(&mut *events.borrow_mut()),
  114        [
  115            ("editor1", "edited"),
  116            ("editor1", "buffer edited"),
  117            ("editor2", "buffer edited"),
  118        ]
  119    );
  120
  121    // Mutating editor 2 will emit an `Edited` event only for that editor.
  122    _ = editor2.update(cx, |editor, window, cx| editor.delete(&Delete, window, cx));
  123    assert_eq!(
  124        mem::take(&mut *events.borrow_mut()),
  125        [
  126            ("editor2", "edited"),
  127            ("editor1", "buffer edited"),
  128            ("editor2", "buffer edited"),
  129        ]
  130    );
  131
  132    // Undoing on editor 1 will emit an `Edited` event only for that editor.
  133    _ = editor1.update(cx, |editor, window, cx| editor.undo(&Undo, window, cx));
  134    assert_eq!(
  135        mem::take(&mut *events.borrow_mut()),
  136        [
  137            ("editor1", "edited"),
  138            ("editor1", "buffer edited"),
  139            ("editor2", "buffer edited"),
  140        ]
  141    );
  142
  143    // Redoing on editor 1 will emit an `Edited` event only for that editor.
  144    _ = editor1.update(cx, |editor, window, cx| editor.redo(&Redo, window, cx));
  145    assert_eq!(
  146        mem::take(&mut *events.borrow_mut()),
  147        [
  148            ("editor1", "edited"),
  149            ("editor1", "buffer edited"),
  150            ("editor2", "buffer edited"),
  151        ]
  152    );
  153
  154    // Undoing on editor 2 will emit an `Edited` event only for that editor.
  155    _ = editor2.update(cx, |editor, window, cx| editor.undo(&Undo, window, cx));
  156    assert_eq!(
  157        mem::take(&mut *events.borrow_mut()),
  158        [
  159            ("editor2", "edited"),
  160            ("editor1", "buffer edited"),
  161            ("editor2", "buffer edited"),
  162        ]
  163    );
  164
  165    // Redoing on editor 2 will emit an `Edited` event only for that editor.
  166    _ = editor2.update(cx, |editor, window, cx| editor.redo(&Redo, window, cx));
  167    assert_eq!(
  168        mem::take(&mut *events.borrow_mut()),
  169        [
  170            ("editor2", "edited"),
  171            ("editor1", "buffer edited"),
  172            ("editor2", "buffer edited"),
  173        ]
  174    );
  175
  176    // No event is emitted when the mutation is a no-op.
  177    _ = editor2.update(cx, |editor, window, cx| {
  178        editor.change_selections(None, window, cx, |s| s.select_ranges([0..0]));
  179
  180        editor.backspace(&Backspace, window, cx);
  181    });
  182    assert_eq!(mem::take(&mut *events.borrow_mut()), []);
  183}
  184
  185#[gpui::test]
  186fn test_undo_redo_with_selection_restoration(cx: &mut TestAppContext) {
  187    init_test(cx, |_| {});
  188
  189    let mut now = Instant::now();
  190    let group_interval = Duration::from_millis(1);
  191    let buffer = cx.new(|cx| {
  192        let mut buf = language::Buffer::local("123456", cx);
  193        buf.set_group_interval(group_interval);
  194        buf
  195    });
  196    let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
  197    let editor = cx.add_window(|window, cx| build_editor(buffer.clone(), window, cx));
  198
  199    _ = editor.update(cx, |editor, window, cx| {
  200        editor.start_transaction_at(now, window, cx);
  201        editor.change_selections(None, window, cx, |s| s.select_ranges([2..4]));
  202
  203        editor.insert("cd", window, cx);
  204        editor.end_transaction_at(now, cx);
  205        assert_eq!(editor.text(cx), "12cd56");
  206        assert_eq!(editor.selections.ranges(cx), vec![4..4]);
  207
  208        editor.start_transaction_at(now, window, cx);
  209        editor.change_selections(None, window, cx, |s| s.select_ranges([4..5]));
  210        editor.insert("e", window, cx);
  211        editor.end_transaction_at(now, cx);
  212        assert_eq!(editor.text(cx), "12cde6");
  213        assert_eq!(editor.selections.ranges(cx), vec![5..5]);
  214
  215        now += group_interval + Duration::from_millis(1);
  216        editor.change_selections(None, window, cx, |s| s.select_ranges([2..2]));
  217
  218        // Simulate an edit in another editor
  219        buffer.update(cx, |buffer, cx| {
  220            buffer.start_transaction_at(now, cx);
  221            buffer.edit([(0..1, "a")], None, cx);
  222            buffer.edit([(1..1, "b")], None, cx);
  223            buffer.end_transaction_at(now, cx);
  224        });
  225
  226        assert_eq!(editor.text(cx), "ab2cde6");
  227        assert_eq!(editor.selections.ranges(cx), vec![3..3]);
  228
  229        // Last transaction happened past the group interval in a different editor.
  230        // Undo it individually and don't restore selections.
  231        editor.undo(&Undo, window, cx);
  232        assert_eq!(editor.text(cx), "12cde6");
  233        assert_eq!(editor.selections.ranges(cx), vec![2..2]);
  234
  235        // First two transactions happened within the group interval in this editor.
  236        // Undo them together and restore selections.
  237        editor.undo(&Undo, window, cx);
  238        editor.undo(&Undo, window, cx); // Undo stack is empty here, so this is a no-op.
  239        assert_eq!(editor.text(cx), "123456");
  240        assert_eq!(editor.selections.ranges(cx), vec![0..0]);
  241
  242        // Redo the first two transactions together.
  243        editor.redo(&Redo, window, cx);
  244        assert_eq!(editor.text(cx), "12cde6");
  245        assert_eq!(editor.selections.ranges(cx), vec![5..5]);
  246
  247        // Redo the last transaction on its own.
  248        editor.redo(&Redo, window, cx);
  249        assert_eq!(editor.text(cx), "ab2cde6");
  250        assert_eq!(editor.selections.ranges(cx), vec![6..6]);
  251
  252        // Test empty transactions.
  253        editor.start_transaction_at(now, window, cx);
  254        editor.end_transaction_at(now, cx);
  255        editor.undo(&Undo, window, cx);
  256        assert_eq!(editor.text(cx), "12cde6");
  257    });
  258}
  259
  260#[gpui::test]
  261fn test_ime_composition(cx: &mut TestAppContext) {
  262    init_test(cx, |_| {});
  263
  264    let buffer = cx.new(|cx| {
  265        let mut buffer = language::Buffer::local("abcde", cx);
  266        // Ensure automatic grouping doesn't occur.
  267        buffer.set_group_interval(Duration::ZERO);
  268        buffer
  269    });
  270
  271    let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
  272    cx.add_window(|window, cx| {
  273        let mut editor = build_editor(buffer.clone(), window, cx);
  274
  275        // Start a new IME composition.
  276        editor.replace_and_mark_text_in_range(Some(0..1), "à", None, window, cx);
  277        editor.replace_and_mark_text_in_range(Some(0..1), "á", None, window, cx);
  278        editor.replace_and_mark_text_in_range(Some(0..1), "ä", None, window, cx);
  279        assert_eq!(editor.text(cx), "äbcde");
  280        assert_eq!(
  281            editor.marked_text_ranges(cx),
  282            Some(vec![OffsetUtf16(0)..OffsetUtf16(1)])
  283        );
  284
  285        // Finalize IME composition.
  286        editor.replace_text_in_range(None, "ā", window, cx);
  287        assert_eq!(editor.text(cx), "ābcde");
  288        assert_eq!(editor.marked_text_ranges(cx), None);
  289
  290        // IME composition edits are grouped and are undone/redone at once.
  291        editor.undo(&Default::default(), window, cx);
  292        assert_eq!(editor.text(cx), "abcde");
  293        assert_eq!(editor.marked_text_ranges(cx), None);
  294        editor.redo(&Default::default(), window, cx);
  295        assert_eq!(editor.text(cx), "ābcde");
  296        assert_eq!(editor.marked_text_ranges(cx), None);
  297
  298        // Start a new IME composition.
  299        editor.replace_and_mark_text_in_range(Some(0..1), "à", None, window, cx);
  300        assert_eq!(
  301            editor.marked_text_ranges(cx),
  302            Some(vec![OffsetUtf16(0)..OffsetUtf16(1)])
  303        );
  304
  305        // Undoing during an IME composition cancels it.
  306        editor.undo(&Default::default(), window, cx);
  307        assert_eq!(editor.text(cx), "ābcde");
  308        assert_eq!(editor.marked_text_ranges(cx), None);
  309
  310        // Start a new IME composition with an invalid marked range, ensuring it gets clipped.
  311        editor.replace_and_mark_text_in_range(Some(4..999), "è", None, window, cx);
  312        assert_eq!(editor.text(cx), "ābcdè");
  313        assert_eq!(
  314            editor.marked_text_ranges(cx),
  315            Some(vec![OffsetUtf16(4)..OffsetUtf16(5)])
  316        );
  317
  318        // Finalize IME composition with an invalid replacement range, ensuring it gets clipped.
  319        editor.replace_text_in_range(Some(4..999), "ę", window, cx);
  320        assert_eq!(editor.text(cx), "ābcdę");
  321        assert_eq!(editor.marked_text_ranges(cx), None);
  322
  323        // Start a new IME composition with multiple cursors.
  324        editor.change_selections(None, window, cx, |s| {
  325            s.select_ranges([
  326                OffsetUtf16(1)..OffsetUtf16(1),
  327                OffsetUtf16(3)..OffsetUtf16(3),
  328                OffsetUtf16(5)..OffsetUtf16(5),
  329            ])
  330        });
  331        editor.replace_and_mark_text_in_range(Some(4..5), "XYZ", None, window, cx);
  332        assert_eq!(editor.text(cx), "XYZbXYZdXYZ");
  333        assert_eq!(
  334            editor.marked_text_ranges(cx),
  335            Some(vec![
  336                OffsetUtf16(0)..OffsetUtf16(3),
  337                OffsetUtf16(4)..OffsetUtf16(7),
  338                OffsetUtf16(8)..OffsetUtf16(11)
  339            ])
  340        );
  341
  342        // Ensure the newly-marked range gets treated as relative to the previously-marked ranges.
  343        editor.replace_and_mark_text_in_range(Some(1..2), "1", None, window, cx);
  344        assert_eq!(editor.text(cx), "X1ZbX1ZdX1Z");
  345        assert_eq!(
  346            editor.marked_text_ranges(cx),
  347            Some(vec![
  348                OffsetUtf16(1)..OffsetUtf16(2),
  349                OffsetUtf16(5)..OffsetUtf16(6),
  350                OffsetUtf16(9)..OffsetUtf16(10)
  351            ])
  352        );
  353
  354        // Finalize IME composition with multiple cursors.
  355        editor.replace_text_in_range(Some(9..10), "2", window, cx);
  356        assert_eq!(editor.text(cx), "X2ZbX2ZdX2Z");
  357        assert_eq!(editor.marked_text_ranges(cx), None);
  358
  359        editor
  360    });
  361}
  362
  363#[gpui::test]
  364fn test_selection_with_mouse(cx: &mut TestAppContext) {
  365    init_test(cx, |_| {});
  366
  367    let editor = cx.add_window(|window, cx| {
  368        let buffer = MultiBuffer::build_simple("aaaaaa\nbbbbbb\ncccccc\nddddddd\n", cx);
  369        build_editor(buffer, window, cx)
  370    });
  371
  372    _ = editor.update(cx, |editor, window, cx| {
  373        editor.begin_selection(DisplayPoint::new(DisplayRow(2), 2), false, 1, window, cx);
  374    });
  375    assert_eq!(
  376        editor
  377            .update(cx, |editor, _, cx| editor.selections.display_ranges(cx))
  378            .unwrap(),
  379        [DisplayPoint::new(DisplayRow(2), 2)..DisplayPoint::new(DisplayRow(2), 2)]
  380    );
  381
  382    _ = editor.update(cx, |editor, window, cx| {
  383        editor.update_selection(
  384            DisplayPoint::new(DisplayRow(3), 3),
  385            0,
  386            gpui::Point::<f32>::default(),
  387            window,
  388            cx,
  389        );
  390    });
  391
  392    assert_eq!(
  393        editor
  394            .update(cx, |editor, _, cx| editor.selections.display_ranges(cx))
  395            .unwrap(),
  396        [DisplayPoint::new(DisplayRow(2), 2)..DisplayPoint::new(DisplayRow(3), 3)]
  397    );
  398
  399    _ = editor.update(cx, |editor, window, cx| {
  400        editor.update_selection(
  401            DisplayPoint::new(DisplayRow(1), 1),
  402            0,
  403            gpui::Point::<f32>::default(),
  404            window,
  405            cx,
  406        );
  407    });
  408
  409    assert_eq!(
  410        editor
  411            .update(cx, |editor, _, cx| editor.selections.display_ranges(cx))
  412            .unwrap(),
  413        [DisplayPoint::new(DisplayRow(2), 2)..DisplayPoint::new(DisplayRow(1), 1)]
  414    );
  415
  416    _ = editor.update(cx, |editor, window, cx| {
  417        editor.end_selection(window, cx);
  418        editor.update_selection(
  419            DisplayPoint::new(DisplayRow(3), 3),
  420            0,
  421            gpui::Point::<f32>::default(),
  422            window,
  423            cx,
  424        );
  425    });
  426
  427    assert_eq!(
  428        editor
  429            .update(cx, |editor, _, cx| editor.selections.display_ranges(cx))
  430            .unwrap(),
  431        [DisplayPoint::new(DisplayRow(2), 2)..DisplayPoint::new(DisplayRow(1), 1)]
  432    );
  433
  434    _ = editor.update(cx, |editor, window, cx| {
  435        editor.begin_selection(DisplayPoint::new(DisplayRow(3), 3), true, 1, window, cx);
  436        editor.update_selection(
  437            DisplayPoint::new(DisplayRow(0), 0),
  438            0,
  439            gpui::Point::<f32>::default(),
  440            window,
  441            cx,
  442        );
  443    });
  444
  445    assert_eq!(
  446        editor
  447            .update(cx, |editor, _, cx| editor.selections.display_ranges(cx))
  448            .unwrap(),
  449        [
  450            DisplayPoint::new(DisplayRow(2), 2)..DisplayPoint::new(DisplayRow(1), 1),
  451            DisplayPoint::new(DisplayRow(3), 3)..DisplayPoint::new(DisplayRow(0), 0)
  452        ]
  453    );
  454
  455    _ = editor.update(cx, |editor, window, cx| {
  456        editor.end_selection(window, cx);
  457    });
  458
  459    assert_eq!(
  460        editor
  461            .update(cx, |editor, _, cx| editor.selections.display_ranges(cx))
  462            .unwrap(),
  463        [DisplayPoint::new(DisplayRow(3), 3)..DisplayPoint::new(DisplayRow(0), 0)]
  464    );
  465}
  466
  467#[gpui::test]
  468fn test_multiple_cursor_removal(cx: &mut TestAppContext) {
  469    init_test(cx, |_| {});
  470
  471    let editor = cx.add_window(|window, cx| {
  472        let buffer = MultiBuffer::build_simple("aaaaaa\nbbbbbb\ncccccc\nddddddd\n", cx);
  473        build_editor(buffer, window, cx)
  474    });
  475
  476    _ = editor.update(cx, |editor, window, cx| {
  477        editor.begin_selection(DisplayPoint::new(DisplayRow(2), 1), false, 1, window, cx);
  478    });
  479
  480    _ = editor.update(cx, |editor, window, cx| {
  481        editor.end_selection(window, cx);
  482    });
  483
  484    _ = editor.update(cx, |editor, window, cx| {
  485        editor.begin_selection(DisplayPoint::new(DisplayRow(3), 2), true, 1, window, cx);
  486    });
  487
  488    _ = editor.update(cx, |editor, window, cx| {
  489        editor.end_selection(window, cx);
  490    });
  491
  492    assert_eq!(
  493        editor
  494            .update(cx, |editor, _, cx| editor.selections.display_ranges(cx))
  495            .unwrap(),
  496        [
  497            DisplayPoint::new(DisplayRow(2), 1)..DisplayPoint::new(DisplayRow(2), 1),
  498            DisplayPoint::new(DisplayRow(3), 2)..DisplayPoint::new(DisplayRow(3), 2)
  499        ]
  500    );
  501
  502    _ = editor.update(cx, |editor, window, cx| {
  503        editor.begin_selection(DisplayPoint::new(DisplayRow(2), 1), true, 1, window, cx);
  504    });
  505
  506    _ = editor.update(cx, |editor, window, cx| {
  507        editor.end_selection(window, cx);
  508    });
  509
  510    assert_eq!(
  511        editor
  512            .update(cx, |editor, _, cx| editor.selections.display_ranges(cx))
  513            .unwrap(),
  514        [DisplayPoint::new(DisplayRow(3), 2)..DisplayPoint::new(DisplayRow(3), 2)]
  515    );
  516}
  517
  518#[gpui::test]
  519fn test_canceling_pending_selection(cx: &mut TestAppContext) {
  520    init_test(cx, |_| {});
  521
  522    let editor = cx.add_window(|window, cx| {
  523        let buffer = MultiBuffer::build_simple("aaaaaa\nbbbbbb\ncccccc\ndddddd\n", cx);
  524        build_editor(buffer, window, cx)
  525    });
  526
  527    _ = editor.update(cx, |editor, window, cx| {
  528        editor.begin_selection(DisplayPoint::new(DisplayRow(2), 2), false, 1, window, cx);
  529        assert_eq!(
  530            editor.selections.display_ranges(cx),
  531            [DisplayPoint::new(DisplayRow(2), 2)..DisplayPoint::new(DisplayRow(2), 2)]
  532        );
  533    });
  534
  535    _ = editor.update(cx, |editor, window, cx| {
  536        editor.update_selection(
  537            DisplayPoint::new(DisplayRow(3), 3),
  538            0,
  539            gpui::Point::<f32>::default(),
  540            window,
  541            cx,
  542        );
  543        assert_eq!(
  544            editor.selections.display_ranges(cx),
  545            [DisplayPoint::new(DisplayRow(2), 2)..DisplayPoint::new(DisplayRow(3), 3)]
  546        );
  547    });
  548
  549    _ = editor.update(cx, |editor, window, cx| {
  550        editor.cancel(&Cancel, window, cx);
  551        editor.update_selection(
  552            DisplayPoint::new(DisplayRow(1), 1),
  553            0,
  554            gpui::Point::<f32>::default(),
  555            window,
  556            cx,
  557        );
  558        assert_eq!(
  559            editor.selections.display_ranges(cx),
  560            [DisplayPoint::new(DisplayRow(2), 2)..DisplayPoint::new(DisplayRow(3), 3)]
  561        );
  562    });
  563}
  564
  565#[gpui::test]
  566fn test_movement_actions_with_pending_selection(cx: &mut TestAppContext) {
  567    init_test(cx, |_| {});
  568
  569    let editor = cx.add_window(|window, cx| {
  570        let buffer = MultiBuffer::build_simple("aaaaaa\nbbbbbb\ncccccc\ndddddd\n", cx);
  571        build_editor(buffer, window, cx)
  572    });
  573
  574    _ = editor.update(cx, |editor, window, cx| {
  575        editor.begin_selection(DisplayPoint::new(DisplayRow(2), 2), false, 1, window, cx);
  576        assert_eq!(
  577            editor.selections.display_ranges(cx),
  578            [DisplayPoint::new(DisplayRow(2), 2)..DisplayPoint::new(DisplayRow(2), 2)]
  579        );
  580
  581        editor.move_down(&Default::default(), window, cx);
  582        assert_eq!(
  583            editor.selections.display_ranges(cx),
  584            [DisplayPoint::new(DisplayRow(3), 2)..DisplayPoint::new(DisplayRow(3), 2)]
  585        );
  586
  587        editor.begin_selection(DisplayPoint::new(DisplayRow(2), 2), false, 1, window, cx);
  588        assert_eq!(
  589            editor.selections.display_ranges(cx),
  590            [DisplayPoint::new(DisplayRow(2), 2)..DisplayPoint::new(DisplayRow(2), 2)]
  591        );
  592
  593        editor.move_up(&Default::default(), window, cx);
  594        assert_eq!(
  595            editor.selections.display_ranges(cx),
  596            [DisplayPoint::new(DisplayRow(1), 2)..DisplayPoint::new(DisplayRow(1), 2)]
  597        );
  598    });
  599}
  600
  601#[gpui::test]
  602fn test_clone(cx: &mut TestAppContext) {
  603    init_test(cx, |_| {});
  604
  605    let (text, selection_ranges) = marked_text_ranges(
  606        indoc! {"
  607            one
  608            two
  609            threeˇ
  610            four
  611            fiveˇ
  612        "},
  613        true,
  614    );
  615
  616    let editor = cx.add_window(|window, cx| {
  617        let buffer = MultiBuffer::build_simple(&text, cx);
  618        build_editor(buffer, window, cx)
  619    });
  620
  621    _ = editor.update(cx, |editor, window, cx| {
  622        editor.change_selections(None, window, cx, |s| {
  623            s.select_ranges(selection_ranges.clone())
  624        });
  625        editor.fold_creases(
  626            vec![
  627                Crease::simple(Point::new(1, 0)..Point::new(2, 0), FoldPlaceholder::test()),
  628                Crease::simple(Point::new(3, 0)..Point::new(4, 0), FoldPlaceholder::test()),
  629            ],
  630            true,
  631            window,
  632            cx,
  633        );
  634    });
  635
  636    let cloned_editor = editor
  637        .update(cx, |editor, _, cx| {
  638            cx.open_window(Default::default(), |window, cx| {
  639                cx.new(|cx| editor.clone(window, cx))
  640            })
  641        })
  642        .unwrap()
  643        .unwrap();
  644
  645    let snapshot = editor
  646        .update(cx, |e, window, cx| e.snapshot(window, cx))
  647        .unwrap();
  648    let cloned_snapshot = cloned_editor
  649        .update(cx, |e, window, cx| e.snapshot(window, cx))
  650        .unwrap();
  651
  652    assert_eq!(
  653        cloned_editor
  654            .update(cx, |e, _, cx| e.display_text(cx))
  655            .unwrap(),
  656        editor.update(cx, |e, _, cx| e.display_text(cx)).unwrap()
  657    );
  658    assert_eq!(
  659        cloned_snapshot
  660            .folds_in_range(0..text.len())
  661            .collect::<Vec<_>>(),
  662        snapshot.folds_in_range(0..text.len()).collect::<Vec<_>>(),
  663    );
  664    assert_set_eq!(
  665        cloned_editor
  666            .update(cx, |editor, _, cx| editor.selections.ranges::<Point>(cx))
  667            .unwrap(),
  668        editor
  669            .update(cx, |editor, _, cx| editor.selections.ranges(cx))
  670            .unwrap()
  671    );
  672    assert_set_eq!(
  673        cloned_editor
  674            .update(cx, |e, _window, cx| e.selections.display_ranges(cx))
  675            .unwrap(),
  676        editor
  677            .update(cx, |e, _, cx| e.selections.display_ranges(cx))
  678            .unwrap()
  679    );
  680}
  681
  682#[gpui::test]
  683async fn test_navigation_history(cx: &mut TestAppContext) {
  684    init_test(cx, |_| {});
  685
  686    use workspace::item::Item;
  687
  688    let fs = FakeFs::new(cx.executor());
  689    let project = Project::test(fs, [], cx).await;
  690    let workspace = cx.add_window(|window, cx| Workspace::test_new(project, window, cx));
  691    let pane = workspace
  692        .update(cx, |workspace, _, _| workspace.active_pane().clone())
  693        .unwrap();
  694
  695    _ = workspace.update(cx, |_v, window, cx| {
  696        cx.new(|cx| {
  697            let buffer = MultiBuffer::build_simple(&sample_text(300, 5, 'a'), cx);
  698            let mut editor = build_editor(buffer.clone(), window, cx);
  699            let handle = cx.entity();
  700            editor.set_nav_history(Some(pane.read(cx).nav_history_for_item(&handle)));
  701
  702            fn pop_history(editor: &mut Editor, cx: &mut App) -> Option<NavigationEntry> {
  703                editor.nav_history.as_mut().unwrap().pop_backward(cx)
  704            }
  705
  706            // Move the cursor a small distance.
  707            // Nothing is added to the navigation history.
  708            editor.change_selections(None, window, cx, |s| {
  709                s.select_display_ranges([
  710                    DisplayPoint::new(DisplayRow(1), 0)..DisplayPoint::new(DisplayRow(1), 0)
  711                ])
  712            });
  713            editor.change_selections(None, window, cx, |s| {
  714                s.select_display_ranges([
  715                    DisplayPoint::new(DisplayRow(3), 0)..DisplayPoint::new(DisplayRow(3), 0)
  716                ])
  717            });
  718            assert!(pop_history(&mut editor, cx).is_none());
  719
  720            // Move the cursor a large distance.
  721            // The history can jump back to the previous position.
  722            editor.change_selections(None, window, cx, |s| {
  723                s.select_display_ranges([
  724                    DisplayPoint::new(DisplayRow(13), 0)..DisplayPoint::new(DisplayRow(13), 3)
  725                ])
  726            });
  727            let nav_entry = pop_history(&mut editor, cx).unwrap();
  728            editor.navigate(nav_entry.data.unwrap(), window, cx);
  729            assert_eq!(nav_entry.item.id(), cx.entity_id());
  730            assert_eq!(
  731                editor.selections.display_ranges(cx),
  732                &[DisplayPoint::new(DisplayRow(3), 0)..DisplayPoint::new(DisplayRow(3), 0)]
  733            );
  734            assert!(pop_history(&mut editor, cx).is_none());
  735
  736            // Move the cursor a small distance via the mouse.
  737            // Nothing is added to the navigation history.
  738            editor.begin_selection(DisplayPoint::new(DisplayRow(5), 0), false, 1, window, cx);
  739            editor.end_selection(window, cx);
  740            assert_eq!(
  741                editor.selections.display_ranges(cx),
  742                &[DisplayPoint::new(DisplayRow(5), 0)..DisplayPoint::new(DisplayRow(5), 0)]
  743            );
  744            assert!(pop_history(&mut editor, cx).is_none());
  745
  746            // Move the cursor a large distance via the mouse.
  747            // The history can jump back to the previous position.
  748            editor.begin_selection(DisplayPoint::new(DisplayRow(15), 0), false, 1, window, cx);
  749            editor.end_selection(window, cx);
  750            assert_eq!(
  751                editor.selections.display_ranges(cx),
  752                &[DisplayPoint::new(DisplayRow(15), 0)..DisplayPoint::new(DisplayRow(15), 0)]
  753            );
  754            let nav_entry = pop_history(&mut editor, cx).unwrap();
  755            editor.navigate(nav_entry.data.unwrap(), window, cx);
  756            assert_eq!(nav_entry.item.id(), cx.entity_id());
  757            assert_eq!(
  758                editor.selections.display_ranges(cx),
  759                &[DisplayPoint::new(DisplayRow(5), 0)..DisplayPoint::new(DisplayRow(5), 0)]
  760            );
  761            assert!(pop_history(&mut editor, cx).is_none());
  762
  763            // Set scroll position to check later
  764            editor.set_scroll_position(gpui::Point::<f32>::new(5.5, 5.5), window, cx);
  765            let original_scroll_position = editor.scroll_manager.anchor();
  766
  767            // Jump to the end of the document and adjust scroll
  768            editor.move_to_end(&MoveToEnd, window, cx);
  769            editor.set_scroll_position(gpui::Point::<f32>::new(-2.5, -0.5), window, cx);
  770            assert_ne!(editor.scroll_manager.anchor(), original_scroll_position);
  771
  772            let nav_entry = pop_history(&mut editor, cx).unwrap();
  773            editor.navigate(nav_entry.data.unwrap(), window, cx);
  774            assert_eq!(editor.scroll_manager.anchor(), original_scroll_position);
  775
  776            // Ensure we don't panic when navigation data contains invalid anchors *and* points.
  777            let mut invalid_anchor = editor.scroll_manager.anchor().anchor;
  778            invalid_anchor.text_anchor.buffer_id = BufferId::new(999).ok();
  779            let invalid_point = Point::new(9999, 0);
  780            editor.navigate(
  781                Box::new(NavigationData {
  782                    cursor_anchor: invalid_anchor,
  783                    cursor_position: invalid_point,
  784                    scroll_anchor: ScrollAnchor {
  785                        anchor: invalid_anchor,
  786                        offset: Default::default(),
  787                    },
  788                    scroll_top_row: invalid_point.row,
  789                }),
  790                window,
  791                cx,
  792            );
  793            assert_eq!(
  794                editor.selections.display_ranges(cx),
  795                &[editor.max_point(cx)..editor.max_point(cx)]
  796            );
  797            assert_eq!(
  798                editor.scroll_position(cx),
  799                gpui::Point::new(0., editor.max_point(cx).row().as_f32())
  800            );
  801
  802            editor
  803        })
  804    });
  805}
  806
  807#[gpui::test]
  808fn test_cancel(cx: &mut TestAppContext) {
  809    init_test(cx, |_| {});
  810
  811    let editor = cx.add_window(|window, cx| {
  812        let buffer = MultiBuffer::build_simple("aaaaaa\nbbbbbb\ncccccc\ndddddd\n", cx);
  813        build_editor(buffer, window, cx)
  814    });
  815
  816    _ = editor.update(cx, |editor, window, cx| {
  817        editor.begin_selection(DisplayPoint::new(DisplayRow(3), 4), false, 1, window, cx);
  818        editor.update_selection(
  819            DisplayPoint::new(DisplayRow(1), 1),
  820            0,
  821            gpui::Point::<f32>::default(),
  822            window,
  823            cx,
  824        );
  825        editor.end_selection(window, cx);
  826
  827        editor.begin_selection(DisplayPoint::new(DisplayRow(0), 1), true, 1, window, cx);
  828        editor.update_selection(
  829            DisplayPoint::new(DisplayRow(0), 3),
  830            0,
  831            gpui::Point::<f32>::default(),
  832            window,
  833            cx,
  834        );
  835        editor.end_selection(window, cx);
  836        assert_eq!(
  837            editor.selections.display_ranges(cx),
  838            [
  839                DisplayPoint::new(DisplayRow(0), 1)..DisplayPoint::new(DisplayRow(0), 3),
  840                DisplayPoint::new(DisplayRow(3), 4)..DisplayPoint::new(DisplayRow(1), 1),
  841            ]
  842        );
  843    });
  844
  845    _ = editor.update(cx, |editor, window, cx| {
  846        editor.cancel(&Cancel, window, cx);
  847        assert_eq!(
  848            editor.selections.display_ranges(cx),
  849            [DisplayPoint::new(DisplayRow(3), 4)..DisplayPoint::new(DisplayRow(1), 1)]
  850        );
  851    });
  852
  853    _ = editor.update(cx, |editor, window, cx| {
  854        editor.cancel(&Cancel, window, cx);
  855        assert_eq!(
  856            editor.selections.display_ranges(cx),
  857            [DisplayPoint::new(DisplayRow(1), 1)..DisplayPoint::new(DisplayRow(1), 1)]
  858        );
  859    });
  860}
  861
  862#[gpui::test]
  863fn test_fold_action(cx: &mut TestAppContext) {
  864    init_test(cx, |_| {});
  865
  866    let editor = cx.add_window(|window, cx| {
  867        let buffer = MultiBuffer::build_simple(
  868            &"
  869                impl Foo {
  870                    // Hello!
  871
  872                    fn a() {
  873                        1
  874                    }
  875
  876                    fn b() {
  877                        2
  878                    }
  879
  880                    fn c() {
  881                        3
  882                    }
  883                }
  884            "
  885            .unindent(),
  886            cx,
  887        );
  888        build_editor(buffer.clone(), window, cx)
  889    });
  890
  891    _ = editor.update(cx, |editor, window, cx| {
  892        editor.change_selections(None, window, cx, |s| {
  893            s.select_display_ranges([
  894                DisplayPoint::new(DisplayRow(7), 0)..DisplayPoint::new(DisplayRow(12), 0)
  895            ]);
  896        });
  897        editor.fold(&Fold, window, cx);
  898        assert_eq!(
  899            editor.display_text(cx),
  900            "
  901                impl Foo {
  902                    // Hello!
  903
  904                    fn a() {
  905                        1
  906                    }
  907
  908                    fn b() {⋯
  909                    }
  910
  911                    fn c() {⋯
  912                    }
  913                }
  914            "
  915            .unindent(),
  916        );
  917
  918        editor.fold(&Fold, window, cx);
  919        assert_eq!(
  920            editor.display_text(cx),
  921            "
  922                impl Foo {⋯
  923                }
  924            "
  925            .unindent(),
  926        );
  927
  928        editor.unfold_lines(&UnfoldLines, window, cx);
  929        assert_eq!(
  930            editor.display_text(cx),
  931            "
  932                impl Foo {
  933                    // Hello!
  934
  935                    fn a() {
  936                        1
  937                    }
  938
  939                    fn b() {⋯
  940                    }
  941
  942                    fn c() {⋯
  943                    }
  944                }
  945            "
  946            .unindent(),
  947        );
  948
  949        editor.unfold_lines(&UnfoldLines, window, cx);
  950        assert_eq!(
  951            editor.display_text(cx),
  952            editor.buffer.read(cx).read(cx).text()
  953        );
  954    });
  955}
  956
  957#[gpui::test]
  958fn test_fold_action_whitespace_sensitive_language(cx: &mut TestAppContext) {
  959    init_test(cx, |_| {});
  960
  961    let editor = cx.add_window(|window, cx| {
  962        let buffer = MultiBuffer::build_simple(
  963            &"
  964                class Foo:
  965                    # Hello!
  966
  967                    def a():
  968                        print(1)
  969
  970                    def b():
  971                        print(2)
  972
  973                    def c():
  974                        print(3)
  975            "
  976            .unindent(),
  977            cx,
  978        );
  979        build_editor(buffer.clone(), window, cx)
  980    });
  981
  982    _ = editor.update(cx, |editor, window, cx| {
  983        editor.change_selections(None, window, cx, |s| {
  984            s.select_display_ranges([
  985                DisplayPoint::new(DisplayRow(6), 0)..DisplayPoint::new(DisplayRow(10), 0)
  986            ]);
  987        });
  988        editor.fold(&Fold, window, cx);
  989        assert_eq!(
  990            editor.display_text(cx),
  991            "
  992                class Foo:
  993                    # Hello!
  994
  995                    def a():
  996                        print(1)
  997
  998                    def b():⋯
  999
 1000                    def c():⋯
 1001            "
 1002            .unindent(),
 1003        );
 1004
 1005        editor.fold(&Fold, window, cx);
 1006        assert_eq!(
 1007            editor.display_text(cx),
 1008            "
 1009                class Foo:⋯
 1010            "
 1011            .unindent(),
 1012        );
 1013
 1014        editor.unfold_lines(&UnfoldLines, window, cx);
 1015        assert_eq!(
 1016            editor.display_text(cx),
 1017            "
 1018                class Foo:
 1019                    # Hello!
 1020
 1021                    def a():
 1022                        print(1)
 1023
 1024                    def b():⋯
 1025
 1026                    def c():⋯
 1027            "
 1028            .unindent(),
 1029        );
 1030
 1031        editor.unfold_lines(&UnfoldLines, window, cx);
 1032        assert_eq!(
 1033            editor.display_text(cx),
 1034            editor.buffer.read(cx).read(cx).text()
 1035        );
 1036    });
 1037}
 1038
 1039#[gpui::test]
 1040fn test_fold_action_multiple_line_breaks(cx: &mut TestAppContext) {
 1041    init_test(cx, |_| {});
 1042
 1043    let editor = cx.add_window(|window, cx| {
 1044        let buffer = MultiBuffer::build_simple(
 1045            &"
 1046                class Foo:
 1047                    # Hello!
 1048
 1049                    def a():
 1050                        print(1)
 1051
 1052                    def b():
 1053                        print(2)
 1054
 1055
 1056                    def c():
 1057                        print(3)
 1058
 1059
 1060            "
 1061            .unindent(),
 1062            cx,
 1063        );
 1064        build_editor(buffer.clone(), window, cx)
 1065    });
 1066
 1067    _ = editor.update(cx, |editor, window, cx| {
 1068        editor.change_selections(None, window, cx, |s| {
 1069            s.select_display_ranges([
 1070                DisplayPoint::new(DisplayRow(6), 0)..DisplayPoint::new(DisplayRow(11), 0)
 1071            ]);
 1072        });
 1073        editor.fold(&Fold, window, cx);
 1074        assert_eq!(
 1075            editor.display_text(cx),
 1076            "
 1077                class Foo:
 1078                    # Hello!
 1079
 1080                    def a():
 1081                        print(1)
 1082
 1083                    def b():⋯
 1084
 1085
 1086                    def c():⋯
 1087
 1088
 1089            "
 1090            .unindent(),
 1091        );
 1092
 1093        editor.fold(&Fold, window, cx);
 1094        assert_eq!(
 1095            editor.display_text(cx),
 1096            "
 1097                class Foo:⋯
 1098
 1099
 1100            "
 1101            .unindent(),
 1102        );
 1103
 1104        editor.unfold_lines(&UnfoldLines, window, cx);
 1105        assert_eq!(
 1106            editor.display_text(cx),
 1107            "
 1108                class Foo:
 1109                    # Hello!
 1110
 1111                    def a():
 1112                        print(1)
 1113
 1114                    def b():⋯
 1115
 1116
 1117                    def c():⋯
 1118
 1119
 1120            "
 1121            .unindent(),
 1122        );
 1123
 1124        editor.unfold_lines(&UnfoldLines, window, cx);
 1125        assert_eq!(
 1126            editor.display_text(cx),
 1127            editor.buffer.read(cx).read(cx).text()
 1128        );
 1129    });
 1130}
 1131
 1132#[gpui::test]
 1133fn test_fold_at_level(cx: &mut TestAppContext) {
 1134    init_test(cx, |_| {});
 1135
 1136    let editor = cx.add_window(|window, cx| {
 1137        let buffer = MultiBuffer::build_simple(
 1138            &"
 1139                class Foo:
 1140                    # Hello!
 1141
 1142                    def a():
 1143                        print(1)
 1144
 1145                    def b():
 1146                        print(2)
 1147
 1148
 1149                class Bar:
 1150                    # World!
 1151
 1152                    def a():
 1153                        print(1)
 1154
 1155                    def b():
 1156                        print(2)
 1157
 1158
 1159            "
 1160            .unindent(),
 1161            cx,
 1162        );
 1163        build_editor(buffer.clone(), window, cx)
 1164    });
 1165
 1166    _ = editor.update(cx, |editor, window, cx| {
 1167        editor.fold_at_level(&FoldAtLevel(2), window, cx);
 1168        assert_eq!(
 1169            editor.display_text(cx),
 1170            "
 1171                class Foo:
 1172                    # Hello!
 1173
 1174                    def a():⋯
 1175
 1176                    def b():⋯
 1177
 1178
 1179                class Bar:
 1180                    # World!
 1181
 1182                    def a():⋯
 1183
 1184                    def b():⋯
 1185
 1186
 1187            "
 1188            .unindent(),
 1189        );
 1190
 1191        editor.fold_at_level(&FoldAtLevel(1), window, cx);
 1192        assert_eq!(
 1193            editor.display_text(cx),
 1194            "
 1195                class Foo:⋯
 1196
 1197
 1198                class Bar:⋯
 1199
 1200
 1201            "
 1202            .unindent(),
 1203        );
 1204
 1205        editor.unfold_all(&UnfoldAll, window, cx);
 1206        editor.fold_at_level(&FoldAtLevel(0), window, cx);
 1207        assert_eq!(
 1208            editor.display_text(cx),
 1209            "
 1210                class Foo:
 1211                    # Hello!
 1212
 1213                    def a():
 1214                        print(1)
 1215
 1216                    def b():
 1217                        print(2)
 1218
 1219
 1220                class Bar:
 1221                    # World!
 1222
 1223                    def a():
 1224                        print(1)
 1225
 1226                    def b():
 1227                        print(2)
 1228
 1229
 1230            "
 1231            .unindent(),
 1232        );
 1233
 1234        assert_eq!(
 1235            editor.display_text(cx),
 1236            editor.buffer.read(cx).read(cx).text()
 1237        );
 1238    });
 1239}
 1240
 1241#[gpui::test]
 1242fn test_move_cursor(cx: &mut TestAppContext) {
 1243    init_test(cx, |_| {});
 1244
 1245    let buffer = cx.update(|cx| MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx));
 1246    let editor = cx.add_window(|window, cx| build_editor(buffer.clone(), window, cx));
 1247
 1248    buffer.update(cx, |buffer, cx| {
 1249        buffer.edit(
 1250            vec![
 1251                (Point::new(1, 0)..Point::new(1, 0), "\t"),
 1252                (Point::new(1, 1)..Point::new(1, 1), "\t"),
 1253            ],
 1254            None,
 1255            cx,
 1256        );
 1257    });
 1258    _ = editor.update(cx, |editor, window, cx| {
 1259        assert_eq!(
 1260            editor.selections.display_ranges(cx),
 1261            &[DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(0), 0)]
 1262        );
 1263
 1264        editor.move_down(&MoveDown, window, cx);
 1265        assert_eq!(
 1266            editor.selections.display_ranges(cx),
 1267            &[DisplayPoint::new(DisplayRow(1), 0)..DisplayPoint::new(DisplayRow(1), 0)]
 1268        );
 1269
 1270        editor.move_right(&MoveRight, window, cx);
 1271        assert_eq!(
 1272            editor.selections.display_ranges(cx),
 1273            &[DisplayPoint::new(DisplayRow(1), 4)..DisplayPoint::new(DisplayRow(1), 4)]
 1274        );
 1275
 1276        editor.move_left(&MoveLeft, window, cx);
 1277        assert_eq!(
 1278            editor.selections.display_ranges(cx),
 1279            &[DisplayPoint::new(DisplayRow(1), 0)..DisplayPoint::new(DisplayRow(1), 0)]
 1280        );
 1281
 1282        editor.move_up(&MoveUp, window, cx);
 1283        assert_eq!(
 1284            editor.selections.display_ranges(cx),
 1285            &[DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(0), 0)]
 1286        );
 1287
 1288        editor.move_to_end(&MoveToEnd, window, cx);
 1289        assert_eq!(
 1290            editor.selections.display_ranges(cx),
 1291            &[DisplayPoint::new(DisplayRow(5), 6)..DisplayPoint::new(DisplayRow(5), 6)]
 1292        );
 1293
 1294        editor.move_to_beginning(&MoveToBeginning, window, cx);
 1295        assert_eq!(
 1296            editor.selections.display_ranges(cx),
 1297            &[DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(0), 0)]
 1298        );
 1299
 1300        editor.change_selections(None, window, cx, |s| {
 1301            s.select_display_ranges([
 1302                DisplayPoint::new(DisplayRow(0), 1)..DisplayPoint::new(DisplayRow(0), 2)
 1303            ]);
 1304        });
 1305        editor.select_to_beginning(&SelectToBeginning, window, cx);
 1306        assert_eq!(
 1307            editor.selections.display_ranges(cx),
 1308            &[DisplayPoint::new(DisplayRow(0), 1)..DisplayPoint::new(DisplayRow(0), 0)]
 1309        );
 1310
 1311        editor.select_to_end(&SelectToEnd, window, cx);
 1312        assert_eq!(
 1313            editor.selections.display_ranges(cx),
 1314            &[DisplayPoint::new(DisplayRow(0), 1)..DisplayPoint::new(DisplayRow(5), 6)]
 1315        );
 1316    });
 1317}
 1318
 1319#[gpui::test]
 1320fn test_move_cursor_multibyte(cx: &mut TestAppContext) {
 1321    init_test(cx, |_| {});
 1322
 1323    let editor = cx.add_window(|window, cx| {
 1324        let buffer = MultiBuffer::build_simple("🟥🟧🟨🟩🟦🟪\nabcde\nαβγδε", cx);
 1325        build_editor(buffer.clone(), window, cx)
 1326    });
 1327
 1328    assert_eq!('🟥'.len_utf8(), 4);
 1329    assert_eq!('α'.len_utf8(), 2);
 1330
 1331    _ = editor.update(cx, |editor, window, cx| {
 1332        editor.fold_creases(
 1333            vec![
 1334                Crease::simple(Point::new(0, 8)..Point::new(0, 16), FoldPlaceholder::test()),
 1335                Crease::simple(Point::new(1, 2)..Point::new(1, 4), FoldPlaceholder::test()),
 1336                Crease::simple(Point::new(2, 4)..Point::new(2, 8), FoldPlaceholder::test()),
 1337            ],
 1338            true,
 1339            window,
 1340            cx,
 1341        );
 1342        assert_eq!(editor.display_text(cx), "🟥🟧⋯🟦🟪\nab⋯e\nαβ⋯ε");
 1343
 1344        editor.move_right(&MoveRight, window, cx);
 1345        assert_eq!(
 1346            editor.selections.display_ranges(cx),
 1347            &[empty_range(0, "🟥".len())]
 1348        );
 1349        editor.move_right(&MoveRight, window, cx);
 1350        assert_eq!(
 1351            editor.selections.display_ranges(cx),
 1352            &[empty_range(0, "🟥🟧".len())]
 1353        );
 1354        editor.move_right(&MoveRight, window, cx);
 1355        assert_eq!(
 1356            editor.selections.display_ranges(cx),
 1357            &[empty_range(0, "🟥🟧⋯".len())]
 1358        );
 1359
 1360        editor.move_down(&MoveDown, window, cx);
 1361        assert_eq!(
 1362            editor.selections.display_ranges(cx),
 1363            &[empty_range(1, "ab⋯e".len())]
 1364        );
 1365        editor.move_left(&MoveLeft, window, cx);
 1366        assert_eq!(
 1367            editor.selections.display_ranges(cx),
 1368            &[empty_range(1, "ab⋯".len())]
 1369        );
 1370        editor.move_left(&MoveLeft, window, cx);
 1371        assert_eq!(
 1372            editor.selections.display_ranges(cx),
 1373            &[empty_range(1, "ab".len())]
 1374        );
 1375        editor.move_left(&MoveLeft, window, cx);
 1376        assert_eq!(
 1377            editor.selections.display_ranges(cx),
 1378            &[empty_range(1, "a".len())]
 1379        );
 1380
 1381        editor.move_down(&MoveDown, window, cx);
 1382        assert_eq!(
 1383            editor.selections.display_ranges(cx),
 1384            &[empty_range(2, "α".len())]
 1385        );
 1386        editor.move_right(&MoveRight, window, cx);
 1387        assert_eq!(
 1388            editor.selections.display_ranges(cx),
 1389            &[empty_range(2, "αβ".len())]
 1390        );
 1391        editor.move_right(&MoveRight, window, cx);
 1392        assert_eq!(
 1393            editor.selections.display_ranges(cx),
 1394            &[empty_range(2, "αβ⋯".len())]
 1395        );
 1396        editor.move_right(&MoveRight, window, cx);
 1397        assert_eq!(
 1398            editor.selections.display_ranges(cx),
 1399            &[empty_range(2, "αβ⋯ε".len())]
 1400        );
 1401
 1402        editor.move_up(&MoveUp, window, cx);
 1403        assert_eq!(
 1404            editor.selections.display_ranges(cx),
 1405            &[empty_range(1, "ab⋯e".len())]
 1406        );
 1407        editor.move_down(&MoveDown, window, cx);
 1408        assert_eq!(
 1409            editor.selections.display_ranges(cx),
 1410            &[empty_range(2, "αβ⋯ε".len())]
 1411        );
 1412        editor.move_up(&MoveUp, window, cx);
 1413        assert_eq!(
 1414            editor.selections.display_ranges(cx),
 1415            &[empty_range(1, "ab⋯e".len())]
 1416        );
 1417
 1418        editor.move_up(&MoveUp, window, cx);
 1419        assert_eq!(
 1420            editor.selections.display_ranges(cx),
 1421            &[empty_range(0, "🟥🟧".len())]
 1422        );
 1423        editor.move_left(&MoveLeft, window, cx);
 1424        assert_eq!(
 1425            editor.selections.display_ranges(cx),
 1426            &[empty_range(0, "🟥".len())]
 1427        );
 1428        editor.move_left(&MoveLeft, window, cx);
 1429        assert_eq!(
 1430            editor.selections.display_ranges(cx),
 1431            &[empty_range(0, "".len())]
 1432        );
 1433    });
 1434}
 1435
 1436#[gpui::test]
 1437fn test_move_cursor_different_line_lengths(cx: &mut TestAppContext) {
 1438    init_test(cx, |_| {});
 1439
 1440    let editor = cx.add_window(|window, cx| {
 1441        let buffer = MultiBuffer::build_simple("ⓐⓑⓒⓓⓔ\nabcd\nαβγ\nabcd\nⓐⓑⓒⓓⓔ\n", cx);
 1442        build_editor(buffer.clone(), window, cx)
 1443    });
 1444    _ = editor.update(cx, |editor, window, cx| {
 1445        editor.change_selections(None, window, cx, |s| {
 1446            s.select_display_ranges([empty_range(0, "ⓐⓑⓒⓓⓔ".len())]);
 1447        });
 1448
 1449        // moving above start of document should move selection to start of document,
 1450        // but the next move down should still be at the original goal_x
 1451        editor.move_up(&MoveUp, window, cx);
 1452        assert_eq!(
 1453            editor.selections.display_ranges(cx),
 1454            &[empty_range(0, "".len())]
 1455        );
 1456
 1457        editor.move_down(&MoveDown, window, cx);
 1458        assert_eq!(
 1459            editor.selections.display_ranges(cx),
 1460            &[empty_range(1, "abcd".len())]
 1461        );
 1462
 1463        editor.move_down(&MoveDown, window, cx);
 1464        assert_eq!(
 1465            editor.selections.display_ranges(cx),
 1466            &[empty_range(2, "αβγ".len())]
 1467        );
 1468
 1469        editor.move_down(&MoveDown, window, cx);
 1470        assert_eq!(
 1471            editor.selections.display_ranges(cx),
 1472            &[empty_range(3, "abcd".len())]
 1473        );
 1474
 1475        editor.move_down(&MoveDown, window, cx);
 1476        assert_eq!(
 1477            editor.selections.display_ranges(cx),
 1478            &[empty_range(4, "ⓐⓑⓒⓓⓔ".len())]
 1479        );
 1480
 1481        // moving past end of document should not change goal_x
 1482        editor.move_down(&MoveDown, window, cx);
 1483        assert_eq!(
 1484            editor.selections.display_ranges(cx),
 1485            &[empty_range(5, "".len())]
 1486        );
 1487
 1488        editor.move_down(&MoveDown, window, cx);
 1489        assert_eq!(
 1490            editor.selections.display_ranges(cx),
 1491            &[empty_range(5, "".len())]
 1492        );
 1493
 1494        editor.move_up(&MoveUp, window, cx);
 1495        assert_eq!(
 1496            editor.selections.display_ranges(cx),
 1497            &[empty_range(4, "ⓐⓑⓒⓓⓔ".len())]
 1498        );
 1499
 1500        editor.move_up(&MoveUp, window, cx);
 1501        assert_eq!(
 1502            editor.selections.display_ranges(cx),
 1503            &[empty_range(3, "abcd".len())]
 1504        );
 1505
 1506        editor.move_up(&MoveUp, window, cx);
 1507        assert_eq!(
 1508            editor.selections.display_ranges(cx),
 1509            &[empty_range(2, "αβγ".len())]
 1510        );
 1511    });
 1512}
 1513
 1514#[gpui::test]
 1515fn test_beginning_end_of_line(cx: &mut TestAppContext) {
 1516    init_test(cx, |_| {});
 1517    let move_to_beg = MoveToBeginningOfLine {
 1518        stop_at_soft_wraps: true,
 1519        stop_at_indent: true,
 1520    };
 1521
 1522    let delete_to_beg = DeleteToBeginningOfLine {
 1523        stop_at_indent: false,
 1524    };
 1525
 1526    let move_to_end = MoveToEndOfLine {
 1527        stop_at_soft_wraps: true,
 1528    };
 1529
 1530    let editor = cx.add_window(|window, cx| {
 1531        let buffer = MultiBuffer::build_simple("abc\n  def", cx);
 1532        build_editor(buffer, window, cx)
 1533    });
 1534    _ = editor.update(cx, |editor, window, cx| {
 1535        editor.change_selections(None, window, cx, |s| {
 1536            s.select_display_ranges([
 1537                DisplayPoint::new(DisplayRow(0), 1)..DisplayPoint::new(DisplayRow(0), 1),
 1538                DisplayPoint::new(DisplayRow(1), 4)..DisplayPoint::new(DisplayRow(1), 4),
 1539            ]);
 1540        });
 1541    });
 1542
 1543    _ = editor.update(cx, |editor, window, cx| {
 1544        editor.move_to_beginning_of_line(&move_to_beg, window, cx);
 1545        assert_eq!(
 1546            editor.selections.display_ranges(cx),
 1547            &[
 1548                DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(0), 0),
 1549                DisplayPoint::new(DisplayRow(1), 2)..DisplayPoint::new(DisplayRow(1), 2),
 1550            ]
 1551        );
 1552    });
 1553
 1554    _ = editor.update(cx, |editor, window, cx| {
 1555        editor.move_to_beginning_of_line(&move_to_beg, window, cx);
 1556        assert_eq!(
 1557            editor.selections.display_ranges(cx),
 1558            &[
 1559                DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(0), 0),
 1560                DisplayPoint::new(DisplayRow(1), 0)..DisplayPoint::new(DisplayRow(1), 0),
 1561            ]
 1562        );
 1563    });
 1564
 1565    _ = editor.update(cx, |editor, window, cx| {
 1566        editor.move_to_beginning_of_line(&move_to_beg, window, cx);
 1567        assert_eq!(
 1568            editor.selections.display_ranges(cx),
 1569            &[
 1570                DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(0), 0),
 1571                DisplayPoint::new(DisplayRow(1), 2)..DisplayPoint::new(DisplayRow(1), 2),
 1572            ]
 1573        );
 1574    });
 1575
 1576    _ = editor.update(cx, |editor, window, cx| {
 1577        editor.move_to_end_of_line(&move_to_end, window, cx);
 1578        assert_eq!(
 1579            editor.selections.display_ranges(cx),
 1580            &[
 1581                DisplayPoint::new(DisplayRow(0), 3)..DisplayPoint::new(DisplayRow(0), 3),
 1582                DisplayPoint::new(DisplayRow(1), 5)..DisplayPoint::new(DisplayRow(1), 5),
 1583            ]
 1584        );
 1585    });
 1586
 1587    // Moving to the end of line again is a no-op.
 1588    _ = editor.update(cx, |editor, window, cx| {
 1589        editor.move_to_end_of_line(&move_to_end, window, cx);
 1590        assert_eq!(
 1591            editor.selections.display_ranges(cx),
 1592            &[
 1593                DisplayPoint::new(DisplayRow(0), 3)..DisplayPoint::new(DisplayRow(0), 3),
 1594                DisplayPoint::new(DisplayRow(1), 5)..DisplayPoint::new(DisplayRow(1), 5),
 1595            ]
 1596        );
 1597    });
 1598
 1599    _ = editor.update(cx, |editor, window, cx| {
 1600        editor.move_left(&MoveLeft, window, cx);
 1601        editor.select_to_beginning_of_line(
 1602            &SelectToBeginningOfLine {
 1603                stop_at_soft_wraps: true,
 1604                stop_at_indent: true,
 1605            },
 1606            window,
 1607            cx,
 1608        );
 1609        assert_eq!(
 1610            editor.selections.display_ranges(cx),
 1611            &[
 1612                DisplayPoint::new(DisplayRow(0), 2)..DisplayPoint::new(DisplayRow(0), 0),
 1613                DisplayPoint::new(DisplayRow(1), 4)..DisplayPoint::new(DisplayRow(1), 2),
 1614            ]
 1615        );
 1616    });
 1617
 1618    _ = editor.update(cx, |editor, window, cx| {
 1619        editor.select_to_beginning_of_line(
 1620            &SelectToBeginningOfLine {
 1621                stop_at_soft_wraps: true,
 1622                stop_at_indent: true,
 1623            },
 1624            window,
 1625            cx,
 1626        );
 1627        assert_eq!(
 1628            editor.selections.display_ranges(cx),
 1629            &[
 1630                DisplayPoint::new(DisplayRow(0), 2)..DisplayPoint::new(DisplayRow(0), 0),
 1631                DisplayPoint::new(DisplayRow(1), 4)..DisplayPoint::new(DisplayRow(1), 0),
 1632            ]
 1633        );
 1634    });
 1635
 1636    _ = editor.update(cx, |editor, window, cx| {
 1637        editor.select_to_beginning_of_line(
 1638            &SelectToBeginningOfLine {
 1639                stop_at_soft_wraps: true,
 1640                stop_at_indent: true,
 1641            },
 1642            window,
 1643            cx,
 1644        );
 1645        assert_eq!(
 1646            editor.selections.display_ranges(cx),
 1647            &[
 1648                DisplayPoint::new(DisplayRow(0), 2)..DisplayPoint::new(DisplayRow(0), 0),
 1649                DisplayPoint::new(DisplayRow(1), 4)..DisplayPoint::new(DisplayRow(1), 2),
 1650            ]
 1651        );
 1652    });
 1653
 1654    _ = editor.update(cx, |editor, window, cx| {
 1655        editor.select_to_end_of_line(
 1656            &SelectToEndOfLine {
 1657                stop_at_soft_wraps: true,
 1658            },
 1659            window,
 1660            cx,
 1661        );
 1662        assert_eq!(
 1663            editor.selections.display_ranges(cx),
 1664            &[
 1665                DisplayPoint::new(DisplayRow(0), 2)..DisplayPoint::new(DisplayRow(0), 3),
 1666                DisplayPoint::new(DisplayRow(1), 4)..DisplayPoint::new(DisplayRow(1), 5),
 1667            ]
 1668        );
 1669    });
 1670
 1671    _ = editor.update(cx, |editor, window, cx| {
 1672        editor.delete_to_end_of_line(&DeleteToEndOfLine, window, cx);
 1673        assert_eq!(editor.display_text(cx), "ab\n  de");
 1674        assert_eq!(
 1675            editor.selections.display_ranges(cx),
 1676            &[
 1677                DisplayPoint::new(DisplayRow(0), 2)..DisplayPoint::new(DisplayRow(0), 2),
 1678                DisplayPoint::new(DisplayRow(1), 4)..DisplayPoint::new(DisplayRow(1), 4),
 1679            ]
 1680        );
 1681    });
 1682
 1683    _ = editor.update(cx, |editor, window, cx| {
 1684        editor.delete_to_beginning_of_line(&delete_to_beg, window, cx);
 1685        assert_eq!(editor.display_text(cx), "\n");
 1686        assert_eq!(
 1687            editor.selections.display_ranges(cx),
 1688            &[
 1689                DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(0), 0),
 1690                DisplayPoint::new(DisplayRow(1), 0)..DisplayPoint::new(DisplayRow(1), 0),
 1691            ]
 1692        );
 1693    });
 1694}
 1695
 1696#[gpui::test]
 1697fn test_beginning_end_of_line_ignore_soft_wrap(cx: &mut TestAppContext) {
 1698    init_test(cx, |_| {});
 1699    let move_to_beg = MoveToBeginningOfLine {
 1700        stop_at_soft_wraps: false,
 1701        stop_at_indent: false,
 1702    };
 1703
 1704    let move_to_end = MoveToEndOfLine {
 1705        stop_at_soft_wraps: false,
 1706    };
 1707
 1708    let editor = cx.add_window(|window, cx| {
 1709        let buffer = MultiBuffer::build_simple("thequickbrownfox\njumpedoverthelazydogs", cx);
 1710        build_editor(buffer, window, cx)
 1711    });
 1712
 1713    _ = editor.update(cx, |editor, window, cx| {
 1714        editor.set_wrap_width(Some(140.0.into()), cx);
 1715
 1716        // We expect the following lines after wrapping
 1717        // ```
 1718        // thequickbrownfox
 1719        // jumpedoverthelazydo
 1720        // gs
 1721        // ```
 1722        // The final `gs` was soft-wrapped onto a new line.
 1723        assert_eq!(
 1724            "thequickbrownfox\njumpedoverthelaz\nydogs",
 1725            editor.display_text(cx),
 1726        );
 1727
 1728        // First, let's assert behavior on the first line, that was not soft-wrapped.
 1729        // Start the cursor at the `k` on the first line
 1730        editor.change_selections(None, window, cx, |s| {
 1731            s.select_display_ranges([
 1732                DisplayPoint::new(DisplayRow(0), 7)..DisplayPoint::new(DisplayRow(0), 7)
 1733            ]);
 1734        });
 1735
 1736        // Moving to the beginning of the line should put us at the beginning of the line.
 1737        editor.move_to_beginning_of_line(&move_to_beg, window, cx);
 1738        assert_eq!(
 1739            vec![DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(0), 0),],
 1740            editor.selections.display_ranges(cx)
 1741        );
 1742
 1743        // Moving to the end of the line should put us at the end of the line.
 1744        editor.move_to_end_of_line(&move_to_end, window, cx);
 1745        assert_eq!(
 1746            vec![DisplayPoint::new(DisplayRow(0), 16)..DisplayPoint::new(DisplayRow(0), 16),],
 1747            editor.selections.display_ranges(cx)
 1748        );
 1749
 1750        // Now, let's assert behavior on the second line, that ended up being soft-wrapped.
 1751        // Start the cursor at the last line (`y` that was wrapped to a new line)
 1752        editor.change_selections(None, window, cx, |s| {
 1753            s.select_display_ranges([
 1754                DisplayPoint::new(DisplayRow(2), 0)..DisplayPoint::new(DisplayRow(2), 0)
 1755            ]);
 1756        });
 1757
 1758        // Moving to the beginning of the line should put us at the start of the second line of
 1759        // display text, i.e., the `j`.
 1760        editor.move_to_beginning_of_line(&move_to_beg, window, cx);
 1761        assert_eq!(
 1762            vec![DisplayPoint::new(DisplayRow(1), 0)..DisplayPoint::new(DisplayRow(1), 0),],
 1763            editor.selections.display_ranges(cx)
 1764        );
 1765
 1766        // Moving to the beginning of the line again should be a no-op.
 1767        editor.move_to_beginning_of_line(&move_to_beg, window, cx);
 1768        assert_eq!(
 1769            vec![DisplayPoint::new(DisplayRow(1), 0)..DisplayPoint::new(DisplayRow(1), 0),],
 1770            editor.selections.display_ranges(cx)
 1771        );
 1772
 1773        // Moving to the end of the line should put us right after the `s` that was soft-wrapped to the
 1774        // next display line.
 1775        editor.move_to_end_of_line(&move_to_end, window, cx);
 1776        assert_eq!(
 1777            vec![DisplayPoint::new(DisplayRow(2), 5)..DisplayPoint::new(DisplayRow(2), 5),],
 1778            editor.selections.display_ranges(cx)
 1779        );
 1780
 1781        // Moving to the end of the line again should be a no-op.
 1782        editor.move_to_end_of_line(&move_to_end, window, cx);
 1783        assert_eq!(
 1784            vec![DisplayPoint::new(DisplayRow(2), 5)..DisplayPoint::new(DisplayRow(2), 5),],
 1785            editor.selections.display_ranges(cx)
 1786        );
 1787    });
 1788}
 1789
 1790#[gpui::test]
 1791fn test_beginning_of_line_stop_at_indent(cx: &mut TestAppContext) {
 1792    init_test(cx, |_| {});
 1793
 1794    let move_to_beg = MoveToBeginningOfLine {
 1795        stop_at_soft_wraps: true,
 1796        stop_at_indent: true,
 1797    };
 1798
 1799    let select_to_beg = SelectToBeginningOfLine {
 1800        stop_at_soft_wraps: true,
 1801        stop_at_indent: true,
 1802    };
 1803
 1804    let delete_to_beg = DeleteToBeginningOfLine {
 1805        stop_at_indent: true,
 1806    };
 1807
 1808    let move_to_end = MoveToEndOfLine {
 1809        stop_at_soft_wraps: false,
 1810    };
 1811
 1812    let editor = cx.add_window(|window, cx| {
 1813        let buffer = MultiBuffer::build_simple("abc\n  def", cx);
 1814        build_editor(buffer, window, cx)
 1815    });
 1816
 1817    _ = editor.update(cx, |editor, window, cx| {
 1818        editor.change_selections(None, window, cx, |s| {
 1819            s.select_display_ranges([
 1820                DisplayPoint::new(DisplayRow(0), 1)..DisplayPoint::new(DisplayRow(0), 1),
 1821                DisplayPoint::new(DisplayRow(1), 4)..DisplayPoint::new(DisplayRow(1), 4),
 1822            ]);
 1823        });
 1824
 1825        // Moving to the beginning of the line should put the first cursor at the beginning of the line,
 1826        // and the second cursor at the first non-whitespace character in the line.
 1827        editor.move_to_beginning_of_line(&move_to_beg, window, cx);
 1828        assert_eq!(
 1829            editor.selections.display_ranges(cx),
 1830            &[
 1831                DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(0), 0),
 1832                DisplayPoint::new(DisplayRow(1), 2)..DisplayPoint::new(DisplayRow(1), 2),
 1833            ]
 1834        );
 1835
 1836        // Moving to the beginning of the line again should be a no-op for the first cursor,
 1837        // and should move the second cursor to the beginning of the line.
 1838        editor.move_to_beginning_of_line(&move_to_beg, window, cx);
 1839        assert_eq!(
 1840            editor.selections.display_ranges(cx),
 1841            &[
 1842                DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(0), 0),
 1843                DisplayPoint::new(DisplayRow(1), 0)..DisplayPoint::new(DisplayRow(1), 0),
 1844            ]
 1845        );
 1846
 1847        // Moving to the beginning of the line again should still be a no-op for the first cursor,
 1848        // and should move the second cursor back to the first non-whitespace character in the line.
 1849        editor.move_to_beginning_of_line(&move_to_beg, window, cx);
 1850        assert_eq!(
 1851            editor.selections.display_ranges(cx),
 1852            &[
 1853                DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(0), 0),
 1854                DisplayPoint::new(DisplayRow(1), 2)..DisplayPoint::new(DisplayRow(1), 2),
 1855            ]
 1856        );
 1857
 1858        // Selecting to the beginning of the line should select to the beginning of the line for the first cursor,
 1859        // and to the first non-whitespace character in the line for the second cursor.
 1860        editor.move_to_end_of_line(&move_to_end, window, cx);
 1861        editor.move_left(&MoveLeft, window, cx);
 1862        editor.select_to_beginning_of_line(&select_to_beg, window, cx);
 1863        assert_eq!(
 1864            editor.selections.display_ranges(cx),
 1865            &[
 1866                DisplayPoint::new(DisplayRow(0), 2)..DisplayPoint::new(DisplayRow(0), 0),
 1867                DisplayPoint::new(DisplayRow(1), 4)..DisplayPoint::new(DisplayRow(1), 2),
 1868            ]
 1869        );
 1870
 1871        // Selecting to the beginning of the line again should be a no-op for the first cursor,
 1872        // and should select to the beginning of the line for the second cursor.
 1873        editor.select_to_beginning_of_line(&select_to_beg, window, cx);
 1874        assert_eq!(
 1875            editor.selections.display_ranges(cx),
 1876            &[
 1877                DisplayPoint::new(DisplayRow(0), 2)..DisplayPoint::new(DisplayRow(0), 0),
 1878                DisplayPoint::new(DisplayRow(1), 4)..DisplayPoint::new(DisplayRow(1), 0),
 1879            ]
 1880        );
 1881
 1882        // Deleting to the beginning of the line should delete to the beginning of the line for the first cursor,
 1883        // and should delete to the first non-whitespace character in the line for the second cursor.
 1884        editor.move_to_end_of_line(&move_to_end, window, cx);
 1885        editor.move_left(&MoveLeft, window, cx);
 1886        editor.delete_to_beginning_of_line(&delete_to_beg, window, cx);
 1887        assert_eq!(editor.text(cx), "c\n  f");
 1888    });
 1889}
 1890
 1891#[gpui::test]
 1892fn test_prev_next_word_boundary(cx: &mut TestAppContext) {
 1893    init_test(cx, |_| {});
 1894
 1895    let editor = cx.add_window(|window, cx| {
 1896        let buffer = MultiBuffer::build_simple("use std::str::{foo, bar}\n\n  {baz.qux()}", cx);
 1897        build_editor(buffer, window, cx)
 1898    });
 1899    _ = editor.update(cx, |editor, window, cx| {
 1900        editor.change_selections(None, window, cx, |s| {
 1901            s.select_display_ranges([
 1902                DisplayPoint::new(DisplayRow(0), 11)..DisplayPoint::new(DisplayRow(0), 11),
 1903                DisplayPoint::new(DisplayRow(2), 4)..DisplayPoint::new(DisplayRow(2), 4),
 1904            ])
 1905        });
 1906
 1907        editor.move_to_previous_word_start(&MoveToPreviousWordStart, window, cx);
 1908        assert_selection_ranges("use std::ˇstr::{foo, bar}\n\n  {ˇbaz.qux()}", editor, cx);
 1909
 1910        editor.move_to_previous_word_start(&MoveToPreviousWordStart, window, cx);
 1911        assert_selection_ranges("use stdˇ::str::{foo, bar}\n\n  ˇ{baz.qux()}", editor, cx);
 1912
 1913        editor.move_to_previous_word_start(&MoveToPreviousWordStart, window, cx);
 1914        assert_selection_ranges("use ˇstd::str::{foo, bar}\n\nˇ  {baz.qux()}", editor, cx);
 1915
 1916        editor.move_to_previous_word_start(&MoveToPreviousWordStart, window, cx);
 1917        assert_selection_ranges("ˇuse std::str::{foo, bar}\nˇ\n  {baz.qux()}", editor, cx);
 1918
 1919        editor.move_to_previous_word_start(&MoveToPreviousWordStart, window, cx);
 1920        assert_selection_ranges("ˇuse std::str::{foo, barˇ}\n\n  {baz.qux()}", editor, cx);
 1921
 1922        editor.move_to_next_word_end(&MoveToNextWordEnd, window, cx);
 1923        assert_selection_ranges("useˇ std::str::{foo, bar}ˇ\n\n  {baz.qux()}", editor, cx);
 1924
 1925        editor.move_to_next_word_end(&MoveToNextWordEnd, window, cx);
 1926        assert_selection_ranges("use stdˇ::str::{foo, bar}\nˇ\n  {baz.qux()}", editor, cx);
 1927
 1928        editor.move_to_next_word_end(&MoveToNextWordEnd, window, cx);
 1929        assert_selection_ranges("use std::ˇstr::{foo, bar}\n\n  {ˇbaz.qux()}", editor, cx);
 1930
 1931        editor.move_right(&MoveRight, window, cx);
 1932        editor.select_to_previous_word_start(&SelectToPreviousWordStart, window, cx);
 1933        assert_selection_ranges(
 1934            "use std::«ˇs»tr::{foo, bar}\n\n  {«ˇb»az.qux()}",
 1935            editor,
 1936            cx,
 1937        );
 1938
 1939        editor.select_to_previous_word_start(&SelectToPreviousWordStart, window, cx);
 1940        assert_selection_ranges(
 1941            "use std«ˇ::s»tr::{foo, bar}\n\n  «ˇ{b»az.qux()}",
 1942            editor,
 1943            cx,
 1944        );
 1945
 1946        editor.select_to_next_word_end(&SelectToNextWordEnd, window, cx);
 1947        assert_selection_ranges(
 1948            "use std::«ˇs»tr::{foo, bar}\n\n  {«ˇb»az.qux()}",
 1949            editor,
 1950            cx,
 1951        );
 1952    });
 1953}
 1954
 1955#[gpui::test]
 1956fn test_prev_next_word_bounds_with_soft_wrap(cx: &mut TestAppContext) {
 1957    init_test(cx, |_| {});
 1958
 1959    let editor = cx.add_window(|window, cx| {
 1960        let buffer = MultiBuffer::build_simple("use one::{\n    two::three::four::five\n};", cx);
 1961        build_editor(buffer, window, cx)
 1962    });
 1963
 1964    _ = editor.update(cx, |editor, window, cx| {
 1965        editor.set_wrap_width(Some(140.0.into()), cx);
 1966        assert_eq!(
 1967            editor.display_text(cx),
 1968            "use one::{\n    two::three::\n    four::five\n};"
 1969        );
 1970
 1971        editor.change_selections(None, window, cx, |s| {
 1972            s.select_display_ranges([
 1973                DisplayPoint::new(DisplayRow(1), 7)..DisplayPoint::new(DisplayRow(1), 7)
 1974            ]);
 1975        });
 1976
 1977        editor.move_to_next_word_end(&MoveToNextWordEnd, window, cx);
 1978        assert_eq!(
 1979            editor.selections.display_ranges(cx),
 1980            &[DisplayPoint::new(DisplayRow(1), 9)..DisplayPoint::new(DisplayRow(1), 9)]
 1981        );
 1982
 1983        editor.move_to_next_word_end(&MoveToNextWordEnd, window, cx);
 1984        assert_eq!(
 1985            editor.selections.display_ranges(cx),
 1986            &[DisplayPoint::new(DisplayRow(1), 14)..DisplayPoint::new(DisplayRow(1), 14)]
 1987        );
 1988
 1989        editor.move_to_next_word_end(&MoveToNextWordEnd, window, cx);
 1990        assert_eq!(
 1991            editor.selections.display_ranges(cx),
 1992            &[DisplayPoint::new(DisplayRow(2), 4)..DisplayPoint::new(DisplayRow(2), 4)]
 1993        );
 1994
 1995        editor.move_to_next_word_end(&MoveToNextWordEnd, window, cx);
 1996        assert_eq!(
 1997            editor.selections.display_ranges(cx),
 1998            &[DisplayPoint::new(DisplayRow(2), 8)..DisplayPoint::new(DisplayRow(2), 8)]
 1999        );
 2000
 2001        editor.move_to_previous_word_start(&MoveToPreviousWordStart, window, cx);
 2002        assert_eq!(
 2003            editor.selections.display_ranges(cx),
 2004            &[DisplayPoint::new(DisplayRow(2), 4)..DisplayPoint::new(DisplayRow(2), 4)]
 2005        );
 2006
 2007        editor.move_to_previous_word_start(&MoveToPreviousWordStart, window, cx);
 2008        assert_eq!(
 2009            editor.selections.display_ranges(cx),
 2010            &[DisplayPoint::new(DisplayRow(1), 14)..DisplayPoint::new(DisplayRow(1), 14)]
 2011        );
 2012    });
 2013}
 2014
 2015#[gpui::test]
 2016async fn test_move_start_of_paragraph_end_of_paragraph(cx: &mut TestAppContext) {
 2017    init_test(cx, |_| {});
 2018    let mut cx = EditorTestContext::new(cx).await;
 2019
 2020    let line_height = cx.editor(|editor, window, _| {
 2021        editor
 2022            .style()
 2023            .unwrap()
 2024            .text
 2025            .line_height_in_pixels(window.rem_size())
 2026    });
 2027    cx.simulate_window_resize(cx.window, size(px(100.), 4. * line_height));
 2028
 2029    cx.set_state(
 2030        &r#"ˇone
 2031        two
 2032
 2033        three
 2034        fourˇ
 2035        five
 2036
 2037        six"#
 2038            .unindent(),
 2039    );
 2040
 2041    cx.update_editor(|editor, window, cx| {
 2042        editor.move_to_end_of_paragraph(&MoveToEndOfParagraph, window, cx)
 2043    });
 2044    cx.assert_editor_state(
 2045        &r#"one
 2046        two
 2047        ˇ
 2048        three
 2049        four
 2050        five
 2051        ˇ
 2052        six"#
 2053            .unindent(),
 2054    );
 2055
 2056    cx.update_editor(|editor, window, cx| {
 2057        editor.move_to_end_of_paragraph(&MoveToEndOfParagraph, window, cx)
 2058    });
 2059    cx.assert_editor_state(
 2060        &r#"one
 2061        two
 2062
 2063        three
 2064        four
 2065        five
 2066        ˇ
 2067        sixˇ"#
 2068            .unindent(),
 2069    );
 2070
 2071    cx.update_editor(|editor, window, cx| {
 2072        editor.move_to_end_of_paragraph(&MoveToEndOfParagraph, window, cx)
 2073    });
 2074    cx.assert_editor_state(
 2075        &r#"one
 2076        two
 2077
 2078        three
 2079        four
 2080        five
 2081
 2082        sixˇ"#
 2083            .unindent(),
 2084    );
 2085
 2086    cx.update_editor(|editor, window, cx| {
 2087        editor.move_to_start_of_paragraph(&MoveToStartOfParagraph, window, cx)
 2088    });
 2089    cx.assert_editor_state(
 2090        &r#"one
 2091        two
 2092
 2093        three
 2094        four
 2095        five
 2096        ˇ
 2097        six"#
 2098            .unindent(),
 2099    );
 2100
 2101    cx.update_editor(|editor, window, cx| {
 2102        editor.move_to_start_of_paragraph(&MoveToStartOfParagraph, window, cx)
 2103    });
 2104    cx.assert_editor_state(
 2105        &r#"one
 2106        two
 2107        ˇ
 2108        three
 2109        four
 2110        five
 2111
 2112        six"#
 2113            .unindent(),
 2114    );
 2115
 2116    cx.update_editor(|editor, window, cx| {
 2117        editor.move_to_start_of_paragraph(&MoveToStartOfParagraph, window, cx)
 2118    });
 2119    cx.assert_editor_state(
 2120        &r#"ˇone
 2121        two
 2122
 2123        three
 2124        four
 2125        five
 2126
 2127        six"#
 2128            .unindent(),
 2129    );
 2130}
 2131
 2132#[gpui::test]
 2133async fn test_scroll_page_up_page_down(cx: &mut TestAppContext) {
 2134    init_test(cx, |_| {});
 2135    let mut cx = EditorTestContext::new(cx).await;
 2136    let line_height = cx.editor(|editor, window, _| {
 2137        editor
 2138            .style()
 2139            .unwrap()
 2140            .text
 2141            .line_height_in_pixels(window.rem_size())
 2142    });
 2143    let window = cx.window;
 2144    cx.simulate_window_resize(window, size(px(1000.), 4. * line_height + px(0.5)));
 2145
 2146    cx.set_state(
 2147        r#"ˇone
 2148        two
 2149        three
 2150        four
 2151        five
 2152        six
 2153        seven
 2154        eight
 2155        nine
 2156        ten
 2157        "#,
 2158    );
 2159
 2160    cx.update_editor(|editor, window, cx| {
 2161        assert_eq!(
 2162            editor.snapshot(window, cx).scroll_position(),
 2163            gpui::Point::new(0., 0.)
 2164        );
 2165        editor.scroll_screen(&ScrollAmount::Page(1.), window, cx);
 2166        assert_eq!(
 2167            editor.snapshot(window, cx).scroll_position(),
 2168            gpui::Point::new(0., 3.)
 2169        );
 2170        editor.scroll_screen(&ScrollAmount::Page(1.), window, cx);
 2171        assert_eq!(
 2172            editor.snapshot(window, cx).scroll_position(),
 2173            gpui::Point::new(0., 6.)
 2174        );
 2175        editor.scroll_screen(&ScrollAmount::Page(-1.), window, cx);
 2176        assert_eq!(
 2177            editor.snapshot(window, cx).scroll_position(),
 2178            gpui::Point::new(0., 3.)
 2179        );
 2180
 2181        editor.scroll_screen(&ScrollAmount::Page(-0.5), window, cx);
 2182        assert_eq!(
 2183            editor.snapshot(window, cx).scroll_position(),
 2184            gpui::Point::new(0., 1.)
 2185        );
 2186        editor.scroll_screen(&ScrollAmount::Page(0.5), window, cx);
 2187        assert_eq!(
 2188            editor.snapshot(window, cx).scroll_position(),
 2189            gpui::Point::new(0., 3.)
 2190        );
 2191    });
 2192}
 2193
 2194#[gpui::test]
 2195async fn test_autoscroll(cx: &mut TestAppContext) {
 2196    init_test(cx, |_| {});
 2197    let mut cx = EditorTestContext::new(cx).await;
 2198
 2199    let line_height = cx.update_editor(|editor, window, cx| {
 2200        editor.set_vertical_scroll_margin(2, cx);
 2201        editor
 2202            .style()
 2203            .unwrap()
 2204            .text
 2205            .line_height_in_pixels(window.rem_size())
 2206    });
 2207    let window = cx.window;
 2208    cx.simulate_window_resize(window, size(px(1000.), 6. * line_height));
 2209
 2210    cx.set_state(
 2211        r#"ˇone
 2212            two
 2213            three
 2214            four
 2215            five
 2216            six
 2217            seven
 2218            eight
 2219            nine
 2220            ten
 2221        "#,
 2222    );
 2223    cx.update_editor(|editor, window, cx| {
 2224        assert_eq!(
 2225            editor.snapshot(window, cx).scroll_position(),
 2226            gpui::Point::new(0., 0.0)
 2227        );
 2228    });
 2229
 2230    // Add a cursor below the visible area. Since both cursors cannot fit
 2231    // on screen, the editor autoscrolls to reveal the newest cursor, and
 2232    // allows the vertical scroll margin below that cursor.
 2233    cx.update_editor(|editor, window, cx| {
 2234        editor.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
 2235            selections.select_ranges([
 2236                Point::new(0, 0)..Point::new(0, 0),
 2237                Point::new(6, 0)..Point::new(6, 0),
 2238            ]);
 2239        })
 2240    });
 2241    cx.update_editor(|editor, window, cx| {
 2242        assert_eq!(
 2243            editor.snapshot(window, cx).scroll_position(),
 2244            gpui::Point::new(0., 3.0)
 2245        );
 2246    });
 2247
 2248    // Move down. The editor cursor scrolls down to track the newest cursor.
 2249    cx.update_editor(|editor, window, cx| {
 2250        editor.move_down(&Default::default(), window, cx);
 2251    });
 2252    cx.update_editor(|editor, window, cx| {
 2253        assert_eq!(
 2254            editor.snapshot(window, cx).scroll_position(),
 2255            gpui::Point::new(0., 4.0)
 2256        );
 2257    });
 2258
 2259    // Add a cursor above the visible area. Since both cursors fit on screen,
 2260    // the editor scrolls to show both.
 2261    cx.update_editor(|editor, window, cx| {
 2262        editor.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
 2263            selections.select_ranges([
 2264                Point::new(1, 0)..Point::new(1, 0),
 2265                Point::new(6, 0)..Point::new(6, 0),
 2266            ]);
 2267        })
 2268    });
 2269    cx.update_editor(|editor, window, cx| {
 2270        assert_eq!(
 2271            editor.snapshot(window, cx).scroll_position(),
 2272            gpui::Point::new(0., 1.0)
 2273        );
 2274    });
 2275}
 2276
 2277#[gpui::test]
 2278async fn test_move_page_up_page_down(cx: &mut TestAppContext) {
 2279    init_test(cx, |_| {});
 2280    let mut cx = EditorTestContext::new(cx).await;
 2281
 2282    let line_height = cx.editor(|editor, window, _cx| {
 2283        editor
 2284            .style()
 2285            .unwrap()
 2286            .text
 2287            .line_height_in_pixels(window.rem_size())
 2288    });
 2289    let window = cx.window;
 2290    cx.simulate_window_resize(window, size(px(100.), 4. * line_height));
 2291    cx.set_state(
 2292        &r#"
 2293        ˇone
 2294        two
 2295        threeˇ
 2296        four
 2297        five
 2298        six
 2299        seven
 2300        eight
 2301        nine
 2302        ten
 2303        "#
 2304        .unindent(),
 2305    );
 2306
 2307    cx.update_editor(|editor, window, cx| {
 2308        editor.move_page_down(&MovePageDown::default(), window, cx)
 2309    });
 2310    cx.assert_editor_state(
 2311        &r#"
 2312        one
 2313        two
 2314        three
 2315        ˇfour
 2316        five
 2317        sixˇ
 2318        seven
 2319        eight
 2320        nine
 2321        ten
 2322        "#
 2323        .unindent(),
 2324    );
 2325
 2326    cx.update_editor(|editor, window, cx| {
 2327        editor.move_page_down(&MovePageDown::default(), window, cx)
 2328    });
 2329    cx.assert_editor_state(
 2330        &r#"
 2331        one
 2332        two
 2333        three
 2334        four
 2335        five
 2336        six
 2337        ˇseven
 2338        eight
 2339        nineˇ
 2340        ten
 2341        "#
 2342        .unindent(),
 2343    );
 2344
 2345    cx.update_editor(|editor, window, cx| editor.move_page_up(&MovePageUp::default(), window, cx));
 2346    cx.assert_editor_state(
 2347        &r#"
 2348        one
 2349        two
 2350        three
 2351        ˇfour
 2352        five
 2353        sixˇ
 2354        seven
 2355        eight
 2356        nine
 2357        ten
 2358        "#
 2359        .unindent(),
 2360    );
 2361
 2362    cx.update_editor(|editor, window, cx| editor.move_page_up(&MovePageUp::default(), window, cx));
 2363    cx.assert_editor_state(
 2364        &r#"
 2365        ˇone
 2366        two
 2367        threeˇ
 2368        four
 2369        five
 2370        six
 2371        seven
 2372        eight
 2373        nine
 2374        ten
 2375        "#
 2376        .unindent(),
 2377    );
 2378
 2379    // Test select collapsing
 2380    cx.update_editor(|editor, window, cx| {
 2381        editor.move_page_down(&MovePageDown::default(), window, cx);
 2382        editor.move_page_down(&MovePageDown::default(), window, cx);
 2383        editor.move_page_down(&MovePageDown::default(), window, cx);
 2384    });
 2385    cx.assert_editor_state(
 2386        &r#"
 2387        one
 2388        two
 2389        three
 2390        four
 2391        five
 2392        six
 2393        seven
 2394        eight
 2395        nine
 2396        ˇten
 2397        ˇ"#
 2398        .unindent(),
 2399    );
 2400}
 2401
 2402#[gpui::test]
 2403async fn test_delete_to_beginning_of_line(cx: &mut TestAppContext) {
 2404    init_test(cx, |_| {});
 2405    let mut cx = EditorTestContext::new(cx).await;
 2406    cx.set_state("one «two threeˇ» four");
 2407    cx.update_editor(|editor, window, cx| {
 2408        editor.delete_to_beginning_of_line(
 2409            &DeleteToBeginningOfLine {
 2410                stop_at_indent: false,
 2411            },
 2412            window,
 2413            cx,
 2414        );
 2415        assert_eq!(editor.text(cx), " four");
 2416    });
 2417}
 2418
 2419#[gpui::test]
 2420fn test_delete_to_word_boundary(cx: &mut TestAppContext) {
 2421    init_test(cx, |_| {});
 2422
 2423    let editor = cx.add_window(|window, cx| {
 2424        let buffer = MultiBuffer::build_simple("one two three four", cx);
 2425        build_editor(buffer.clone(), window, cx)
 2426    });
 2427
 2428    _ = editor.update(cx, |editor, window, cx| {
 2429        editor.change_selections(None, window, cx, |s| {
 2430            s.select_display_ranges([
 2431                // an empty selection - the preceding word fragment is deleted
 2432                DisplayPoint::new(DisplayRow(0), 2)..DisplayPoint::new(DisplayRow(0), 2),
 2433                // characters selected - they are deleted
 2434                DisplayPoint::new(DisplayRow(0), 9)..DisplayPoint::new(DisplayRow(0), 12),
 2435            ])
 2436        });
 2437        editor.delete_to_previous_word_start(
 2438            &DeleteToPreviousWordStart {
 2439                ignore_newlines: false,
 2440            },
 2441            window,
 2442            cx,
 2443        );
 2444        assert_eq!(editor.buffer.read(cx).read(cx).text(), "e two te four");
 2445    });
 2446
 2447    _ = editor.update(cx, |editor, window, cx| {
 2448        editor.change_selections(None, window, cx, |s| {
 2449            s.select_display_ranges([
 2450                // an empty selection - the following word fragment is deleted
 2451                DisplayPoint::new(DisplayRow(0), 3)..DisplayPoint::new(DisplayRow(0), 3),
 2452                // characters selected - they are deleted
 2453                DisplayPoint::new(DisplayRow(0), 9)..DisplayPoint::new(DisplayRow(0), 10),
 2454            ])
 2455        });
 2456        editor.delete_to_next_word_end(
 2457            &DeleteToNextWordEnd {
 2458                ignore_newlines: false,
 2459            },
 2460            window,
 2461            cx,
 2462        );
 2463        assert_eq!(editor.buffer.read(cx).read(cx).text(), "e t te our");
 2464    });
 2465}
 2466
 2467#[gpui::test]
 2468fn test_delete_to_previous_word_start_or_newline(cx: &mut TestAppContext) {
 2469    init_test(cx, |_| {});
 2470
 2471    let editor = cx.add_window(|window, cx| {
 2472        let buffer = MultiBuffer::build_simple("one\n2\nthree\n4", cx);
 2473        build_editor(buffer.clone(), window, cx)
 2474    });
 2475    let del_to_prev_word_start = DeleteToPreviousWordStart {
 2476        ignore_newlines: false,
 2477    };
 2478    let del_to_prev_word_start_ignore_newlines = DeleteToPreviousWordStart {
 2479        ignore_newlines: true,
 2480    };
 2481
 2482    _ = editor.update(cx, |editor, window, cx| {
 2483        editor.change_selections(None, window, cx, |s| {
 2484            s.select_display_ranges([
 2485                DisplayPoint::new(DisplayRow(3), 1)..DisplayPoint::new(DisplayRow(3), 1)
 2486            ])
 2487        });
 2488        editor.delete_to_previous_word_start(&del_to_prev_word_start, window, cx);
 2489        assert_eq!(editor.buffer.read(cx).read(cx).text(), "one\n2\nthree\n");
 2490        editor.delete_to_previous_word_start(&del_to_prev_word_start, window, cx);
 2491        assert_eq!(editor.buffer.read(cx).read(cx).text(), "one\n2\nthree");
 2492        editor.delete_to_previous_word_start(&del_to_prev_word_start, window, cx);
 2493        assert_eq!(editor.buffer.read(cx).read(cx).text(), "one\n2\n");
 2494        editor.delete_to_previous_word_start(&del_to_prev_word_start, window, cx);
 2495        assert_eq!(editor.buffer.read(cx).read(cx).text(), "one\n2");
 2496        editor.delete_to_previous_word_start(&del_to_prev_word_start_ignore_newlines, window, cx);
 2497        assert_eq!(editor.buffer.read(cx).read(cx).text(), "one\n");
 2498        editor.delete_to_previous_word_start(&del_to_prev_word_start_ignore_newlines, window, cx);
 2499        assert_eq!(editor.buffer.read(cx).read(cx).text(), "");
 2500    });
 2501}
 2502
 2503#[gpui::test]
 2504fn test_delete_to_next_word_end_or_newline(cx: &mut TestAppContext) {
 2505    init_test(cx, |_| {});
 2506
 2507    let editor = cx.add_window(|window, cx| {
 2508        let buffer = MultiBuffer::build_simple("\none\n   two\nthree\n   four", cx);
 2509        build_editor(buffer.clone(), window, cx)
 2510    });
 2511    let del_to_next_word_end = DeleteToNextWordEnd {
 2512        ignore_newlines: false,
 2513    };
 2514    let del_to_next_word_end_ignore_newlines = DeleteToNextWordEnd {
 2515        ignore_newlines: true,
 2516    };
 2517
 2518    _ = editor.update(cx, |editor, window, cx| {
 2519        editor.change_selections(None, window, cx, |s| {
 2520            s.select_display_ranges([
 2521                DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(0), 0)
 2522            ])
 2523        });
 2524        editor.delete_to_next_word_end(&del_to_next_word_end, window, cx);
 2525        assert_eq!(
 2526            editor.buffer.read(cx).read(cx).text(),
 2527            "one\n   two\nthree\n   four"
 2528        );
 2529        editor.delete_to_next_word_end(&del_to_next_word_end, window, cx);
 2530        assert_eq!(
 2531            editor.buffer.read(cx).read(cx).text(),
 2532            "\n   two\nthree\n   four"
 2533        );
 2534        editor.delete_to_next_word_end(&del_to_next_word_end, window, cx);
 2535        assert_eq!(
 2536            editor.buffer.read(cx).read(cx).text(),
 2537            "two\nthree\n   four"
 2538        );
 2539        editor.delete_to_next_word_end(&del_to_next_word_end, window, cx);
 2540        assert_eq!(editor.buffer.read(cx).read(cx).text(), "\nthree\n   four");
 2541        editor.delete_to_next_word_end(&del_to_next_word_end_ignore_newlines, window, cx);
 2542        assert_eq!(editor.buffer.read(cx).read(cx).text(), "\n   four");
 2543        editor.delete_to_next_word_end(&del_to_next_word_end_ignore_newlines, window, cx);
 2544        assert_eq!(editor.buffer.read(cx).read(cx).text(), "");
 2545    });
 2546}
 2547
 2548#[gpui::test]
 2549fn test_newline(cx: &mut TestAppContext) {
 2550    init_test(cx, |_| {});
 2551
 2552    let editor = cx.add_window(|window, cx| {
 2553        let buffer = MultiBuffer::build_simple("aaaa\n    bbbb\n", cx);
 2554        build_editor(buffer.clone(), window, cx)
 2555    });
 2556
 2557    _ = editor.update(cx, |editor, window, cx| {
 2558        editor.change_selections(None, window, cx, |s| {
 2559            s.select_display_ranges([
 2560                DisplayPoint::new(DisplayRow(0), 2)..DisplayPoint::new(DisplayRow(0), 2),
 2561                DisplayPoint::new(DisplayRow(1), 2)..DisplayPoint::new(DisplayRow(1), 2),
 2562                DisplayPoint::new(DisplayRow(1), 6)..DisplayPoint::new(DisplayRow(1), 6),
 2563            ])
 2564        });
 2565
 2566        editor.newline(&Newline, window, cx);
 2567        assert_eq!(editor.text(cx), "aa\naa\n  \n    bb\n    bb\n");
 2568    });
 2569}
 2570
 2571#[gpui::test]
 2572fn test_newline_with_old_selections(cx: &mut TestAppContext) {
 2573    init_test(cx, |_| {});
 2574
 2575    let editor = cx.add_window(|window, cx| {
 2576        let buffer = MultiBuffer::build_simple(
 2577            "
 2578                a
 2579                b(
 2580                    X
 2581                )
 2582                c(
 2583                    X
 2584                )
 2585            "
 2586            .unindent()
 2587            .as_str(),
 2588            cx,
 2589        );
 2590        let mut editor = build_editor(buffer.clone(), window, cx);
 2591        editor.change_selections(None, window, cx, |s| {
 2592            s.select_ranges([
 2593                Point::new(2, 4)..Point::new(2, 5),
 2594                Point::new(5, 4)..Point::new(5, 5),
 2595            ])
 2596        });
 2597        editor
 2598    });
 2599
 2600    _ = editor.update(cx, |editor, window, cx| {
 2601        // Edit the buffer directly, deleting ranges surrounding the editor's selections
 2602        editor.buffer.update(cx, |buffer, cx| {
 2603            buffer.edit(
 2604                [
 2605                    (Point::new(1, 2)..Point::new(3, 0), ""),
 2606                    (Point::new(4, 2)..Point::new(6, 0), ""),
 2607                ],
 2608                None,
 2609                cx,
 2610            );
 2611            assert_eq!(
 2612                buffer.read(cx).text(),
 2613                "
 2614                    a
 2615                    b()
 2616                    c()
 2617                "
 2618                .unindent()
 2619            );
 2620        });
 2621        assert_eq!(
 2622            editor.selections.ranges(cx),
 2623            &[
 2624                Point::new(1, 2)..Point::new(1, 2),
 2625                Point::new(2, 2)..Point::new(2, 2),
 2626            ],
 2627        );
 2628
 2629        editor.newline(&Newline, window, cx);
 2630        assert_eq!(
 2631            editor.text(cx),
 2632            "
 2633                a
 2634                b(
 2635                )
 2636                c(
 2637                )
 2638            "
 2639            .unindent()
 2640        );
 2641
 2642        // The selections are moved after the inserted newlines
 2643        assert_eq!(
 2644            editor.selections.ranges(cx),
 2645            &[
 2646                Point::new(2, 0)..Point::new(2, 0),
 2647                Point::new(4, 0)..Point::new(4, 0),
 2648            ],
 2649        );
 2650    });
 2651}
 2652
 2653#[gpui::test]
 2654async fn test_newline_above(cx: &mut TestAppContext) {
 2655    init_test(cx, |settings| {
 2656        settings.defaults.tab_size = NonZeroU32::new(4)
 2657    });
 2658
 2659    let language = Arc::new(
 2660        Language::new(
 2661            LanguageConfig::default(),
 2662            Some(tree_sitter_rust::LANGUAGE.into()),
 2663        )
 2664        .with_indents_query(r#"(_ "(" ")" @end) @indent"#)
 2665        .unwrap(),
 2666    );
 2667
 2668    let mut cx = EditorTestContext::new(cx).await;
 2669    cx.update_buffer(|buffer, cx| buffer.set_language(Some(language), cx));
 2670    cx.set_state(indoc! {"
 2671        const a: ˇA = (
 2672 2673                «const_functionˇ»(ˇ),
 2674                so«mˇ»et«hˇ»ing_ˇelse,ˇ
 2675 2676        ˇ);ˇ
 2677    "});
 2678
 2679    cx.update_editor(|e, window, cx| e.newline_above(&NewlineAbove, window, cx));
 2680    cx.assert_editor_state(indoc! {"
 2681        ˇ
 2682        const a: A = (
 2683            ˇ
 2684            (
 2685                ˇ
 2686                ˇ
 2687                const_function(),
 2688                ˇ
 2689                ˇ
 2690                ˇ
 2691                ˇ
 2692                something_else,
 2693                ˇ
 2694            )
 2695            ˇ
 2696            ˇ
 2697        );
 2698    "});
 2699}
 2700
 2701#[gpui::test]
 2702async fn test_newline_below(cx: &mut TestAppContext) {
 2703    init_test(cx, |settings| {
 2704        settings.defaults.tab_size = NonZeroU32::new(4)
 2705    });
 2706
 2707    let language = Arc::new(
 2708        Language::new(
 2709            LanguageConfig::default(),
 2710            Some(tree_sitter_rust::LANGUAGE.into()),
 2711        )
 2712        .with_indents_query(r#"(_ "(" ")" @end) @indent"#)
 2713        .unwrap(),
 2714    );
 2715
 2716    let mut cx = EditorTestContext::new(cx).await;
 2717    cx.update_buffer(|buffer, cx| buffer.set_language(Some(language), cx));
 2718    cx.set_state(indoc! {"
 2719        const a: ˇA = (
 2720 2721                «const_functionˇ»(ˇ),
 2722                so«mˇ»et«hˇ»ing_ˇelse,ˇ
 2723 2724        ˇ);ˇ
 2725    "});
 2726
 2727    cx.update_editor(|e, window, cx| e.newline_below(&NewlineBelow, window, cx));
 2728    cx.assert_editor_state(indoc! {"
 2729        const a: A = (
 2730            ˇ
 2731            (
 2732                ˇ
 2733                const_function(),
 2734                ˇ
 2735                ˇ
 2736                something_else,
 2737                ˇ
 2738                ˇ
 2739                ˇ
 2740                ˇ
 2741            )
 2742            ˇ
 2743        );
 2744        ˇ
 2745        ˇ
 2746    "});
 2747}
 2748
 2749#[gpui::test]
 2750async fn test_newline_comments(cx: &mut TestAppContext) {
 2751    init_test(cx, |settings| {
 2752        settings.defaults.tab_size = NonZeroU32::new(4)
 2753    });
 2754
 2755    let language = Arc::new(Language::new(
 2756        LanguageConfig {
 2757            line_comments: vec!["//".into()],
 2758            ..LanguageConfig::default()
 2759        },
 2760        None,
 2761    ));
 2762    {
 2763        let mut cx = EditorTestContext::new(cx).await;
 2764        cx.update_buffer(|buffer, cx| buffer.set_language(Some(language), cx));
 2765        cx.set_state(indoc! {"
 2766        // Fooˇ
 2767    "});
 2768
 2769        cx.update_editor(|e, window, cx| e.newline(&Newline, window, cx));
 2770        cx.assert_editor_state(indoc! {"
 2771        // Foo
 2772        //ˇ
 2773    "});
 2774        // Ensure that if cursor is before the comment start, we do not actually insert a comment prefix.
 2775        cx.set_state(indoc! {"
 2776        ˇ// Foo
 2777    "});
 2778        cx.update_editor(|e, window, cx| e.newline(&Newline, window, cx));
 2779        cx.assert_editor_state(indoc! {"
 2780
 2781        ˇ// Foo
 2782    "});
 2783    }
 2784    // Ensure that comment continuations can be disabled.
 2785    update_test_language_settings(cx, |settings| {
 2786        settings.defaults.extend_comment_on_newline = Some(false);
 2787    });
 2788    let mut cx = EditorTestContext::new(cx).await;
 2789    cx.set_state(indoc! {"
 2790        // Fooˇ
 2791    "});
 2792    cx.update_editor(|e, window, cx| e.newline(&Newline, window, cx));
 2793    cx.assert_editor_state(indoc! {"
 2794        // Foo
 2795        ˇ
 2796    "});
 2797}
 2798
 2799#[gpui::test]
 2800fn test_insert_with_old_selections(cx: &mut TestAppContext) {
 2801    init_test(cx, |_| {});
 2802
 2803    let editor = cx.add_window(|window, cx| {
 2804        let buffer = MultiBuffer::build_simple("a( X ), b( Y ), c( Z )", cx);
 2805        let mut editor = build_editor(buffer.clone(), window, cx);
 2806        editor.change_selections(None, window, cx, |s| {
 2807            s.select_ranges([3..4, 11..12, 19..20])
 2808        });
 2809        editor
 2810    });
 2811
 2812    _ = editor.update(cx, |editor, window, cx| {
 2813        // Edit the buffer directly, deleting ranges surrounding the editor's selections
 2814        editor.buffer.update(cx, |buffer, cx| {
 2815            buffer.edit([(2..5, ""), (10..13, ""), (18..21, "")], None, cx);
 2816            assert_eq!(buffer.read(cx).text(), "a(), b(), c()".unindent());
 2817        });
 2818        assert_eq!(editor.selections.ranges(cx), &[2..2, 7..7, 12..12],);
 2819
 2820        editor.insert("Z", window, cx);
 2821        assert_eq!(editor.text(cx), "a(Z), b(Z), c(Z)");
 2822
 2823        // The selections are moved after the inserted characters
 2824        assert_eq!(editor.selections.ranges(cx), &[3..3, 9..9, 15..15],);
 2825    });
 2826}
 2827
 2828#[gpui::test]
 2829async fn test_tab(cx: &mut TestAppContext) {
 2830    init_test(cx, |settings| {
 2831        settings.defaults.tab_size = NonZeroU32::new(3)
 2832    });
 2833
 2834    let mut cx = EditorTestContext::new(cx).await;
 2835    cx.set_state(indoc! {"
 2836        ˇabˇc
 2837        ˇ🏀ˇ🏀ˇefg
 2838 2839    "});
 2840    cx.update_editor(|e, window, cx| e.tab(&Tab, window, cx));
 2841    cx.assert_editor_state(indoc! {"
 2842           ˇab ˇc
 2843           ˇ🏀  ˇ🏀  ˇefg
 2844        d  ˇ
 2845    "});
 2846
 2847    cx.set_state(indoc! {"
 2848        a
 2849        «🏀ˇ»🏀«🏀ˇ»🏀«🏀ˇ»
 2850    "});
 2851    cx.update_editor(|e, window, cx| e.tab(&Tab, window, cx));
 2852    cx.assert_editor_state(indoc! {"
 2853        a
 2854           «🏀ˇ»🏀«🏀ˇ»🏀«🏀ˇ»
 2855    "});
 2856}
 2857
 2858#[gpui::test]
 2859async fn test_tab_in_leading_whitespace_auto_indents_lines(cx: &mut TestAppContext) {
 2860    init_test(cx, |_| {});
 2861
 2862    let mut cx = EditorTestContext::new(cx).await;
 2863    let language = Arc::new(
 2864        Language::new(
 2865            LanguageConfig::default(),
 2866            Some(tree_sitter_rust::LANGUAGE.into()),
 2867        )
 2868        .with_indents_query(r#"(_ "(" ")" @end) @indent"#)
 2869        .unwrap(),
 2870    );
 2871    cx.update_buffer(|buffer, cx| buffer.set_language(Some(language), cx));
 2872
 2873    // cursors that are already at the suggested indent level insert
 2874    // a soft tab. cursors that are to the left of the suggested indent
 2875    // auto-indent their line.
 2876    cx.set_state(indoc! {"
 2877        ˇ
 2878        const a: B = (
 2879            c(
 2880                d(
 2881        ˇ
 2882                )
 2883        ˇ
 2884        ˇ    )
 2885        );
 2886    "});
 2887    cx.update_editor(|e, window, cx| e.tab(&Tab, window, cx));
 2888    cx.assert_editor_state(indoc! {"
 2889            ˇ
 2890        const a: B = (
 2891            c(
 2892                d(
 2893                    ˇ
 2894                )
 2895                ˇ
 2896            ˇ)
 2897        );
 2898    "});
 2899
 2900    // handle auto-indent when there are multiple cursors on the same line
 2901    cx.set_state(indoc! {"
 2902        const a: B = (
 2903            c(
 2904        ˇ    ˇ
 2905        ˇ    )
 2906        );
 2907    "});
 2908    cx.update_editor(|e, window, cx| e.tab(&Tab, window, cx));
 2909    cx.assert_editor_state(indoc! {"
 2910        const a: B = (
 2911            c(
 2912                ˇ
 2913            ˇ)
 2914        );
 2915    "});
 2916}
 2917
 2918#[gpui::test]
 2919async fn test_tab_with_mixed_whitespace_txt(cx: &mut TestAppContext) {
 2920    init_test(cx, |settings| {
 2921        settings.defaults.tab_size = NonZeroU32::new(3)
 2922    });
 2923
 2924    let mut cx = EditorTestContext::new(cx).await;
 2925    cx.set_state(indoc! {"
 2926         ˇ
 2927        \t ˇ
 2928        \t  ˇ
 2929        \t   ˇ
 2930         \t  \t\t \t      \t\t   \t\t    \t \t ˇ
 2931    "});
 2932
 2933    cx.update_editor(|e, window, cx| e.tab(&Tab, window, cx));
 2934    cx.assert_editor_state(indoc! {"
 2935           ˇ
 2936        \t   ˇ
 2937        \t   ˇ
 2938        \t      ˇ
 2939         \t  \t\t \t      \t\t   \t\t    \t \t   ˇ
 2940    "});
 2941}
 2942
 2943#[gpui::test]
 2944async fn test_tab_with_mixed_whitespace_rust(cx: &mut TestAppContext) {
 2945    init_test(cx, |settings| {
 2946        settings.defaults.tab_size = NonZeroU32::new(4)
 2947    });
 2948
 2949    let language = Arc::new(
 2950        Language::new(
 2951            LanguageConfig::default(),
 2952            Some(tree_sitter_rust::LANGUAGE.into()),
 2953        )
 2954        .with_indents_query(r#"(_ "{" "}" @end) @indent"#)
 2955        .unwrap(),
 2956    );
 2957
 2958    let mut cx = EditorTestContext::new(cx).await;
 2959    cx.update_buffer(|buffer, cx| buffer.set_language(Some(language), cx));
 2960    cx.set_state(indoc! {"
 2961        fn a() {
 2962            if b {
 2963        \t ˇc
 2964            }
 2965        }
 2966    "});
 2967
 2968    cx.update_editor(|e, window, cx| e.tab(&Tab, window, cx));
 2969    cx.assert_editor_state(indoc! {"
 2970        fn a() {
 2971            if b {
 2972                ˇc
 2973            }
 2974        }
 2975    "});
 2976}
 2977
 2978#[gpui::test]
 2979async fn test_indent_outdent(cx: &mut TestAppContext) {
 2980    init_test(cx, |settings| {
 2981        settings.defaults.tab_size = NonZeroU32::new(4);
 2982    });
 2983
 2984    let mut cx = EditorTestContext::new(cx).await;
 2985
 2986    cx.set_state(indoc! {"
 2987          «oneˇ» «twoˇ»
 2988        three
 2989         four
 2990    "});
 2991    cx.update_editor(|e, window, cx| e.tab(&Tab, window, cx));
 2992    cx.assert_editor_state(indoc! {"
 2993            «oneˇ» «twoˇ»
 2994        three
 2995         four
 2996    "});
 2997
 2998    cx.update_editor(|e, window, cx| e.backtab(&Backtab, window, cx));
 2999    cx.assert_editor_state(indoc! {"
 3000        «oneˇ» «twoˇ»
 3001        three
 3002         four
 3003    "});
 3004
 3005    // select across line ending
 3006    cx.set_state(indoc! {"
 3007        one two
 3008        t«hree
 3009        ˇ» four
 3010    "});
 3011    cx.update_editor(|e, window, cx| e.tab(&Tab, window, cx));
 3012    cx.assert_editor_state(indoc! {"
 3013        one two
 3014            t«hree
 3015        ˇ» four
 3016    "});
 3017
 3018    cx.update_editor(|e, window, cx| e.backtab(&Backtab, window, cx));
 3019    cx.assert_editor_state(indoc! {"
 3020        one two
 3021        t«hree
 3022        ˇ» four
 3023    "});
 3024
 3025    // Ensure that indenting/outdenting works when the cursor is at column 0.
 3026    cx.set_state(indoc! {"
 3027        one two
 3028        ˇthree
 3029            four
 3030    "});
 3031    cx.update_editor(|e, window, cx| e.tab(&Tab, window, cx));
 3032    cx.assert_editor_state(indoc! {"
 3033        one two
 3034            ˇthree
 3035            four
 3036    "});
 3037
 3038    cx.set_state(indoc! {"
 3039        one two
 3040        ˇ    three
 3041            four
 3042    "});
 3043    cx.update_editor(|e, window, cx| e.backtab(&Backtab, window, cx));
 3044    cx.assert_editor_state(indoc! {"
 3045        one two
 3046        ˇthree
 3047            four
 3048    "});
 3049}
 3050
 3051#[gpui::test]
 3052async fn test_indent_outdent_with_hard_tabs(cx: &mut TestAppContext) {
 3053    init_test(cx, |settings| {
 3054        settings.defaults.hard_tabs = Some(true);
 3055    });
 3056
 3057    let mut cx = EditorTestContext::new(cx).await;
 3058
 3059    // select two ranges on one line
 3060    cx.set_state(indoc! {"
 3061        «oneˇ» «twoˇ»
 3062        three
 3063        four
 3064    "});
 3065    cx.update_editor(|e, window, cx| e.tab(&Tab, window, cx));
 3066    cx.assert_editor_state(indoc! {"
 3067        \t«oneˇ» «twoˇ»
 3068        three
 3069        four
 3070    "});
 3071    cx.update_editor(|e, window, cx| e.tab(&Tab, window, cx));
 3072    cx.assert_editor_state(indoc! {"
 3073        \t\t«oneˇ» «twoˇ»
 3074        three
 3075        four
 3076    "});
 3077    cx.update_editor(|e, window, cx| e.backtab(&Backtab, window, cx));
 3078    cx.assert_editor_state(indoc! {"
 3079        \t«oneˇ» «twoˇ»
 3080        three
 3081        four
 3082    "});
 3083    cx.update_editor(|e, window, cx| e.backtab(&Backtab, window, cx));
 3084    cx.assert_editor_state(indoc! {"
 3085        «oneˇ» «twoˇ»
 3086        three
 3087        four
 3088    "});
 3089
 3090    // select across a line ending
 3091    cx.set_state(indoc! {"
 3092        one two
 3093        t«hree
 3094        ˇ»four
 3095    "});
 3096    cx.update_editor(|e, window, cx| e.tab(&Tab, window, cx));
 3097    cx.assert_editor_state(indoc! {"
 3098        one two
 3099        \tt«hree
 3100        ˇ»four
 3101    "});
 3102    cx.update_editor(|e, window, cx| e.tab(&Tab, window, cx));
 3103    cx.assert_editor_state(indoc! {"
 3104        one two
 3105        \t\tt«hree
 3106        ˇ»four
 3107    "});
 3108    cx.update_editor(|e, window, cx| e.backtab(&Backtab, window, cx));
 3109    cx.assert_editor_state(indoc! {"
 3110        one two
 3111        \tt«hree
 3112        ˇ»four
 3113    "});
 3114    cx.update_editor(|e, window, cx| e.backtab(&Backtab, window, cx));
 3115    cx.assert_editor_state(indoc! {"
 3116        one two
 3117        t«hree
 3118        ˇ»four
 3119    "});
 3120
 3121    // Ensure that indenting/outdenting works when the cursor is at column 0.
 3122    cx.set_state(indoc! {"
 3123        one two
 3124        ˇthree
 3125        four
 3126    "});
 3127    cx.update_editor(|e, window, cx| e.backtab(&Backtab, window, cx));
 3128    cx.assert_editor_state(indoc! {"
 3129        one two
 3130        ˇthree
 3131        four
 3132    "});
 3133    cx.update_editor(|e, window, cx| e.tab(&Tab, window, cx));
 3134    cx.assert_editor_state(indoc! {"
 3135        one two
 3136        \tˇthree
 3137        four
 3138    "});
 3139    cx.update_editor(|e, window, cx| e.backtab(&Backtab, window, cx));
 3140    cx.assert_editor_state(indoc! {"
 3141        one two
 3142        ˇthree
 3143        four
 3144    "});
 3145}
 3146
 3147#[gpui::test]
 3148fn test_indent_outdent_with_excerpts(cx: &mut TestAppContext) {
 3149    init_test(cx, |settings| {
 3150        settings.languages.extend([
 3151            (
 3152                "TOML".into(),
 3153                LanguageSettingsContent {
 3154                    tab_size: NonZeroU32::new(2),
 3155                    ..Default::default()
 3156                },
 3157            ),
 3158            (
 3159                "Rust".into(),
 3160                LanguageSettingsContent {
 3161                    tab_size: NonZeroU32::new(4),
 3162                    ..Default::default()
 3163                },
 3164            ),
 3165        ]);
 3166    });
 3167
 3168    let toml_language = Arc::new(Language::new(
 3169        LanguageConfig {
 3170            name: "TOML".into(),
 3171            ..Default::default()
 3172        },
 3173        None,
 3174    ));
 3175    let rust_language = Arc::new(Language::new(
 3176        LanguageConfig {
 3177            name: "Rust".into(),
 3178            ..Default::default()
 3179        },
 3180        None,
 3181    ));
 3182
 3183    let toml_buffer =
 3184        cx.new(|cx| Buffer::local("a = 1\nb = 2\n", cx).with_language(toml_language, cx));
 3185    let rust_buffer =
 3186        cx.new(|cx| Buffer::local("const c: usize = 3;\n", cx).with_language(rust_language, cx));
 3187    let multibuffer = cx.new(|cx| {
 3188        let mut multibuffer = MultiBuffer::new(ReadWrite);
 3189        multibuffer.push_excerpts(
 3190            toml_buffer.clone(),
 3191            [ExcerptRange::new(Point::new(0, 0)..Point::new(2, 0))],
 3192            cx,
 3193        );
 3194        multibuffer.push_excerpts(
 3195            rust_buffer.clone(),
 3196            [ExcerptRange::new(Point::new(0, 0)..Point::new(1, 0))],
 3197            cx,
 3198        );
 3199        multibuffer
 3200    });
 3201
 3202    cx.add_window(|window, cx| {
 3203        let mut editor = build_editor(multibuffer, window, cx);
 3204
 3205        assert_eq!(
 3206            editor.text(cx),
 3207            indoc! {"
 3208                a = 1
 3209                b = 2
 3210
 3211                const c: usize = 3;
 3212            "}
 3213        );
 3214
 3215        select_ranges(
 3216            &mut editor,
 3217            indoc! {"
 3218                «aˇ» = 1
 3219                b = 2
 3220
 3221                «const c:ˇ» usize = 3;
 3222            "},
 3223            window,
 3224            cx,
 3225        );
 3226
 3227        editor.tab(&Tab, window, cx);
 3228        assert_text_with_selections(
 3229            &mut editor,
 3230            indoc! {"
 3231                  «aˇ» = 1
 3232                b = 2
 3233
 3234                    «const c:ˇ» usize = 3;
 3235            "},
 3236            cx,
 3237        );
 3238        editor.backtab(&Backtab, window, cx);
 3239        assert_text_with_selections(
 3240            &mut editor,
 3241            indoc! {"
 3242                «aˇ» = 1
 3243                b = 2
 3244
 3245                «const c:ˇ» usize = 3;
 3246            "},
 3247            cx,
 3248        );
 3249
 3250        editor
 3251    });
 3252}
 3253
 3254#[gpui::test]
 3255async fn test_backspace(cx: &mut TestAppContext) {
 3256    init_test(cx, |_| {});
 3257
 3258    let mut cx = EditorTestContext::new(cx).await;
 3259
 3260    // Basic backspace
 3261    cx.set_state(indoc! {"
 3262        onˇe two three
 3263        fou«rˇ» five six
 3264        seven «ˇeight nine
 3265        »ten
 3266    "});
 3267    cx.update_editor(|e, window, cx| e.backspace(&Backspace, window, cx));
 3268    cx.assert_editor_state(indoc! {"
 3269        oˇe two three
 3270        fouˇ five six
 3271        seven ˇten
 3272    "});
 3273
 3274    // Test backspace inside and around indents
 3275    cx.set_state(indoc! {"
 3276        zero
 3277            ˇone
 3278                ˇtwo
 3279            ˇ ˇ ˇ  three
 3280        ˇ  ˇ  four
 3281    "});
 3282    cx.update_editor(|e, window, cx| e.backspace(&Backspace, window, cx));
 3283    cx.assert_editor_state(indoc! {"
 3284        zero
 3285        ˇone
 3286            ˇtwo
 3287        ˇ  threeˇ  four
 3288    "});
 3289}
 3290
 3291#[gpui::test]
 3292async fn test_delete(cx: &mut TestAppContext) {
 3293    init_test(cx, |_| {});
 3294
 3295    let mut cx = EditorTestContext::new(cx).await;
 3296    cx.set_state(indoc! {"
 3297        onˇe two three
 3298        fou«rˇ» five six
 3299        seven «ˇeight nine
 3300        »ten
 3301    "});
 3302    cx.update_editor(|e, window, cx| e.delete(&Delete, window, cx));
 3303    cx.assert_editor_state(indoc! {"
 3304        onˇ two three
 3305        fouˇ five six
 3306        seven ˇten
 3307    "});
 3308}
 3309
 3310#[gpui::test]
 3311fn test_delete_line(cx: &mut TestAppContext) {
 3312    init_test(cx, |_| {});
 3313
 3314    let editor = cx.add_window(|window, cx| {
 3315        let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
 3316        build_editor(buffer, window, cx)
 3317    });
 3318    _ = editor.update(cx, |editor, window, cx| {
 3319        editor.change_selections(None, window, cx, |s| {
 3320            s.select_display_ranges([
 3321                DisplayPoint::new(DisplayRow(0), 1)..DisplayPoint::new(DisplayRow(0), 1),
 3322                DisplayPoint::new(DisplayRow(1), 0)..DisplayPoint::new(DisplayRow(1), 1),
 3323                DisplayPoint::new(DisplayRow(3), 0)..DisplayPoint::new(DisplayRow(3), 0),
 3324            ])
 3325        });
 3326        editor.delete_line(&DeleteLine, window, cx);
 3327        assert_eq!(editor.display_text(cx), "ghi");
 3328        assert_eq!(
 3329            editor.selections.display_ranges(cx),
 3330            vec![
 3331                DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(0), 0),
 3332                DisplayPoint::new(DisplayRow(0), 1)..DisplayPoint::new(DisplayRow(0), 1)
 3333            ]
 3334        );
 3335    });
 3336
 3337    let editor = cx.add_window(|window, cx| {
 3338        let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
 3339        build_editor(buffer, window, cx)
 3340    });
 3341    _ = editor.update(cx, |editor, window, cx| {
 3342        editor.change_selections(None, window, cx, |s| {
 3343            s.select_display_ranges([
 3344                DisplayPoint::new(DisplayRow(2), 0)..DisplayPoint::new(DisplayRow(0), 1)
 3345            ])
 3346        });
 3347        editor.delete_line(&DeleteLine, window, cx);
 3348        assert_eq!(editor.display_text(cx), "ghi\n");
 3349        assert_eq!(
 3350            editor.selections.display_ranges(cx),
 3351            vec![DisplayPoint::new(DisplayRow(0), 1)..DisplayPoint::new(DisplayRow(0), 1)]
 3352        );
 3353    });
 3354}
 3355
 3356#[gpui::test]
 3357fn test_join_lines_with_single_selection(cx: &mut TestAppContext) {
 3358    init_test(cx, |_| {});
 3359
 3360    cx.add_window(|window, cx| {
 3361        let buffer = MultiBuffer::build_simple("aaa\nbbb\nccc\nddd\n\n", cx);
 3362        let mut editor = build_editor(buffer.clone(), window, cx);
 3363        let buffer = buffer.read(cx).as_singleton().unwrap();
 3364
 3365        assert_eq!(
 3366            editor.selections.ranges::<Point>(cx),
 3367            &[Point::new(0, 0)..Point::new(0, 0)]
 3368        );
 3369
 3370        // When on single line, replace newline at end by space
 3371        editor.join_lines(&JoinLines, window, cx);
 3372        assert_eq!(buffer.read(cx).text(), "aaa bbb\nccc\nddd\n\n");
 3373        assert_eq!(
 3374            editor.selections.ranges::<Point>(cx),
 3375            &[Point::new(0, 3)..Point::new(0, 3)]
 3376        );
 3377
 3378        // When multiple lines are selected, remove newlines that are spanned by the selection
 3379        editor.change_selections(None, window, cx, |s| {
 3380            s.select_ranges([Point::new(0, 5)..Point::new(2, 2)])
 3381        });
 3382        editor.join_lines(&JoinLines, window, cx);
 3383        assert_eq!(buffer.read(cx).text(), "aaa bbb ccc ddd\n\n");
 3384        assert_eq!(
 3385            editor.selections.ranges::<Point>(cx),
 3386            &[Point::new(0, 11)..Point::new(0, 11)]
 3387        );
 3388
 3389        // Undo should be transactional
 3390        editor.undo(&Undo, window, cx);
 3391        assert_eq!(buffer.read(cx).text(), "aaa bbb\nccc\nddd\n\n");
 3392        assert_eq!(
 3393            editor.selections.ranges::<Point>(cx),
 3394            &[Point::new(0, 5)..Point::new(2, 2)]
 3395        );
 3396
 3397        // When joining an empty line don't insert a space
 3398        editor.change_selections(None, window, cx, |s| {
 3399            s.select_ranges([Point::new(2, 1)..Point::new(2, 2)])
 3400        });
 3401        editor.join_lines(&JoinLines, window, cx);
 3402        assert_eq!(buffer.read(cx).text(), "aaa bbb\nccc\nddd\n");
 3403        assert_eq!(
 3404            editor.selections.ranges::<Point>(cx),
 3405            [Point::new(2, 3)..Point::new(2, 3)]
 3406        );
 3407
 3408        // We can remove trailing newlines
 3409        editor.join_lines(&JoinLines, window, cx);
 3410        assert_eq!(buffer.read(cx).text(), "aaa bbb\nccc\nddd");
 3411        assert_eq!(
 3412            editor.selections.ranges::<Point>(cx),
 3413            [Point::new(2, 3)..Point::new(2, 3)]
 3414        );
 3415
 3416        // We don't blow up on the last line
 3417        editor.join_lines(&JoinLines, window, cx);
 3418        assert_eq!(buffer.read(cx).text(), "aaa bbb\nccc\nddd");
 3419        assert_eq!(
 3420            editor.selections.ranges::<Point>(cx),
 3421            [Point::new(2, 3)..Point::new(2, 3)]
 3422        );
 3423
 3424        // reset to test indentation
 3425        editor.buffer.update(cx, |buffer, cx| {
 3426            buffer.edit(
 3427                [
 3428                    (Point::new(1, 0)..Point::new(1, 2), "  "),
 3429                    (Point::new(2, 0)..Point::new(2, 3), "  \n\td"),
 3430                ],
 3431                None,
 3432                cx,
 3433            )
 3434        });
 3435
 3436        // We remove any leading spaces
 3437        assert_eq!(buffer.read(cx).text(), "aaa bbb\n  c\n  \n\td");
 3438        editor.change_selections(None, window, cx, |s| {
 3439            s.select_ranges([Point::new(0, 1)..Point::new(0, 1)])
 3440        });
 3441        editor.join_lines(&JoinLines, window, cx);
 3442        assert_eq!(buffer.read(cx).text(), "aaa bbb c\n  \n\td");
 3443
 3444        // We don't insert a space for a line containing only spaces
 3445        editor.join_lines(&JoinLines, window, cx);
 3446        assert_eq!(buffer.read(cx).text(), "aaa bbb c\n\td");
 3447
 3448        // We ignore any leading tabs
 3449        editor.join_lines(&JoinLines, window, cx);
 3450        assert_eq!(buffer.read(cx).text(), "aaa bbb c d");
 3451
 3452        editor
 3453    });
 3454}
 3455
 3456#[gpui::test]
 3457fn test_join_lines_with_multi_selection(cx: &mut TestAppContext) {
 3458    init_test(cx, |_| {});
 3459
 3460    cx.add_window(|window, cx| {
 3461        let buffer = MultiBuffer::build_simple("aaa\nbbb\nccc\nddd\n\n", cx);
 3462        let mut editor = build_editor(buffer.clone(), window, cx);
 3463        let buffer = buffer.read(cx).as_singleton().unwrap();
 3464
 3465        editor.change_selections(None, window, cx, |s| {
 3466            s.select_ranges([
 3467                Point::new(0, 2)..Point::new(1, 1),
 3468                Point::new(1, 2)..Point::new(1, 2),
 3469                Point::new(3, 1)..Point::new(3, 2),
 3470            ])
 3471        });
 3472
 3473        editor.join_lines(&JoinLines, window, cx);
 3474        assert_eq!(buffer.read(cx).text(), "aaa bbb ccc\nddd\n");
 3475
 3476        assert_eq!(
 3477            editor.selections.ranges::<Point>(cx),
 3478            [
 3479                Point::new(0, 7)..Point::new(0, 7),
 3480                Point::new(1, 3)..Point::new(1, 3)
 3481            ]
 3482        );
 3483        editor
 3484    });
 3485}
 3486
 3487#[gpui::test]
 3488async fn test_join_lines_with_git_diff_base(executor: BackgroundExecutor, cx: &mut TestAppContext) {
 3489    init_test(cx, |_| {});
 3490
 3491    let mut cx = EditorTestContext::new(cx).await;
 3492
 3493    let diff_base = r#"
 3494        Line 0
 3495        Line 1
 3496        Line 2
 3497        Line 3
 3498        "#
 3499    .unindent();
 3500
 3501    cx.set_state(
 3502        &r#"
 3503        ˇLine 0
 3504        Line 1
 3505        Line 2
 3506        Line 3
 3507        "#
 3508        .unindent(),
 3509    );
 3510
 3511    cx.set_head_text(&diff_base);
 3512    executor.run_until_parked();
 3513
 3514    // Join lines
 3515    cx.update_editor(|editor, window, cx| {
 3516        editor.join_lines(&JoinLines, window, cx);
 3517    });
 3518    executor.run_until_parked();
 3519
 3520    cx.assert_editor_state(
 3521        &r#"
 3522        Line 0ˇ Line 1
 3523        Line 2
 3524        Line 3
 3525        "#
 3526        .unindent(),
 3527    );
 3528    // Join again
 3529    cx.update_editor(|editor, window, cx| {
 3530        editor.join_lines(&JoinLines, window, cx);
 3531    });
 3532    executor.run_until_parked();
 3533
 3534    cx.assert_editor_state(
 3535        &r#"
 3536        Line 0 Line 1ˇ Line 2
 3537        Line 3
 3538        "#
 3539        .unindent(),
 3540    );
 3541}
 3542
 3543#[gpui::test]
 3544async fn test_custom_newlines_cause_no_false_positive_diffs(
 3545    executor: BackgroundExecutor,
 3546    cx: &mut TestAppContext,
 3547) {
 3548    init_test(cx, |_| {});
 3549    let mut cx = EditorTestContext::new(cx).await;
 3550    cx.set_state("Line 0\r\nLine 1\rˇ\nLine 2\r\nLine 3");
 3551    cx.set_head_text("Line 0\r\nLine 1\r\nLine 2\r\nLine 3");
 3552    executor.run_until_parked();
 3553
 3554    cx.update_editor(|editor, window, cx| {
 3555        let snapshot = editor.snapshot(window, cx);
 3556        assert_eq!(
 3557            snapshot
 3558                .buffer_snapshot
 3559                .diff_hunks_in_range(0..snapshot.buffer_snapshot.len())
 3560                .collect::<Vec<_>>(),
 3561            Vec::new(),
 3562            "Should not have any diffs for files with custom newlines"
 3563        );
 3564    });
 3565}
 3566
 3567#[gpui::test]
 3568async fn test_manipulate_lines_with_single_selection(cx: &mut TestAppContext) {
 3569    init_test(cx, |_| {});
 3570
 3571    let mut cx = EditorTestContext::new(cx).await;
 3572
 3573    // Test sort_lines_case_insensitive()
 3574    cx.set_state(indoc! {"
 3575        «z
 3576        y
 3577        x
 3578        Z
 3579        Y
 3580        Xˇ»
 3581    "});
 3582    cx.update_editor(|e, window, cx| {
 3583        e.sort_lines_case_insensitive(&SortLinesCaseInsensitive, window, cx)
 3584    });
 3585    cx.assert_editor_state(indoc! {"
 3586        «x
 3587        X
 3588        y
 3589        Y
 3590        z
 3591        Zˇ»
 3592    "});
 3593
 3594    // Test reverse_lines()
 3595    cx.set_state(indoc! {"
 3596        «5
 3597        4
 3598        3
 3599        2
 3600        1ˇ»
 3601    "});
 3602    cx.update_editor(|e, window, cx| e.reverse_lines(&ReverseLines, window, cx));
 3603    cx.assert_editor_state(indoc! {"
 3604        «1
 3605        2
 3606        3
 3607        4
 3608        5ˇ»
 3609    "});
 3610
 3611    // Skip testing shuffle_line()
 3612
 3613    // From here on out, test more complex cases of manipulate_lines() with a single driver method: sort_lines_case_sensitive()
 3614    // Since all methods calling manipulate_lines() are doing the exact same general thing (reordering lines)
 3615
 3616    // Don't manipulate when cursor is on single line, but expand the selection
 3617    cx.set_state(indoc! {"
 3618        ddˇdd
 3619        ccc
 3620        bb
 3621        a
 3622    "});
 3623    cx.update_editor(|e, window, cx| {
 3624        e.sort_lines_case_sensitive(&SortLinesCaseSensitive, window, cx)
 3625    });
 3626    cx.assert_editor_state(indoc! {"
 3627        «ddddˇ»
 3628        ccc
 3629        bb
 3630        a
 3631    "});
 3632
 3633    // Basic manipulate case
 3634    // Start selection moves to column 0
 3635    // End of selection shrinks to fit shorter line
 3636    cx.set_state(indoc! {"
 3637        dd«d
 3638        ccc
 3639        bb
 3640        aaaaaˇ»
 3641    "});
 3642    cx.update_editor(|e, window, cx| {
 3643        e.sort_lines_case_sensitive(&SortLinesCaseSensitive, window, cx)
 3644    });
 3645    cx.assert_editor_state(indoc! {"
 3646        «aaaaa
 3647        bb
 3648        ccc
 3649        dddˇ»
 3650    "});
 3651
 3652    // Manipulate case with newlines
 3653    cx.set_state(indoc! {"
 3654        dd«d
 3655        ccc
 3656
 3657        bb
 3658        aaaaa
 3659
 3660        ˇ»
 3661    "});
 3662    cx.update_editor(|e, window, cx| {
 3663        e.sort_lines_case_sensitive(&SortLinesCaseSensitive, window, cx)
 3664    });
 3665    cx.assert_editor_state(indoc! {"
 3666        «
 3667
 3668        aaaaa
 3669        bb
 3670        ccc
 3671        dddˇ»
 3672
 3673    "});
 3674
 3675    // Adding new line
 3676    cx.set_state(indoc! {"
 3677        aa«a
 3678        bbˇ»b
 3679    "});
 3680    cx.update_editor(|e, window, cx| {
 3681        e.manipulate_lines(window, cx, |lines| lines.push("added_line"))
 3682    });
 3683    cx.assert_editor_state(indoc! {"
 3684        «aaa
 3685        bbb
 3686        added_lineˇ»
 3687    "});
 3688
 3689    // Removing line
 3690    cx.set_state(indoc! {"
 3691        aa«a
 3692        bbbˇ»
 3693    "});
 3694    cx.update_editor(|e, window, cx| {
 3695        e.manipulate_lines(window, cx, |lines| {
 3696            lines.pop();
 3697        })
 3698    });
 3699    cx.assert_editor_state(indoc! {"
 3700        «aaaˇ»
 3701    "});
 3702
 3703    // Removing all lines
 3704    cx.set_state(indoc! {"
 3705        aa«a
 3706        bbbˇ»
 3707    "});
 3708    cx.update_editor(|e, window, cx| {
 3709        e.manipulate_lines(window, cx, |lines| {
 3710            lines.drain(..);
 3711        })
 3712    });
 3713    cx.assert_editor_state(indoc! {"
 3714        ˇ
 3715    "});
 3716}
 3717
 3718#[gpui::test]
 3719async fn test_unique_lines_multi_selection(cx: &mut TestAppContext) {
 3720    init_test(cx, |_| {});
 3721
 3722    let mut cx = EditorTestContext::new(cx).await;
 3723
 3724    // Consider continuous selection as single selection
 3725    cx.set_state(indoc! {"
 3726        Aaa«aa
 3727        cˇ»c«c
 3728        bb
 3729        aaaˇ»aa
 3730    "});
 3731    cx.update_editor(|e, window, cx| {
 3732        e.unique_lines_case_sensitive(&UniqueLinesCaseSensitive, window, cx)
 3733    });
 3734    cx.assert_editor_state(indoc! {"
 3735        «Aaaaa
 3736        ccc
 3737        bb
 3738        aaaaaˇ»
 3739    "});
 3740
 3741    cx.set_state(indoc! {"
 3742        Aaa«aa
 3743        cˇ»c«c
 3744        bb
 3745        aaaˇ»aa
 3746    "});
 3747    cx.update_editor(|e, window, cx| {
 3748        e.unique_lines_case_insensitive(&UniqueLinesCaseInsensitive, window, cx)
 3749    });
 3750    cx.assert_editor_state(indoc! {"
 3751        «Aaaaa
 3752        ccc
 3753        bbˇ»
 3754    "});
 3755
 3756    // Consider non continuous selection as distinct dedup operations
 3757    cx.set_state(indoc! {"
 3758        «aaaaa
 3759        bb
 3760        aaaaa
 3761        aaaaaˇ»
 3762
 3763        aaa«aaˇ»
 3764    "});
 3765    cx.update_editor(|e, window, cx| {
 3766        e.unique_lines_case_sensitive(&UniqueLinesCaseSensitive, window, cx)
 3767    });
 3768    cx.assert_editor_state(indoc! {"
 3769        «aaaaa
 3770        bbˇ»
 3771
 3772        «aaaaaˇ»
 3773    "});
 3774}
 3775
 3776#[gpui::test]
 3777async fn test_unique_lines_single_selection(cx: &mut TestAppContext) {
 3778    init_test(cx, |_| {});
 3779
 3780    let mut cx = EditorTestContext::new(cx).await;
 3781
 3782    cx.set_state(indoc! {"
 3783        «Aaa
 3784        aAa
 3785        Aaaˇ»
 3786    "});
 3787    cx.update_editor(|e, window, cx| {
 3788        e.unique_lines_case_sensitive(&UniqueLinesCaseSensitive, window, cx)
 3789    });
 3790    cx.assert_editor_state(indoc! {"
 3791        «Aaa
 3792        aAaˇ»
 3793    "});
 3794
 3795    cx.set_state(indoc! {"
 3796        «Aaa
 3797        aAa
 3798        aaAˇ»
 3799    "});
 3800    cx.update_editor(|e, window, cx| {
 3801        e.unique_lines_case_insensitive(&UniqueLinesCaseInsensitive, window, cx)
 3802    });
 3803    cx.assert_editor_state(indoc! {"
 3804        «Aaaˇ»
 3805    "});
 3806}
 3807
 3808#[gpui::test]
 3809async fn test_manipulate_lines_with_multi_selection(cx: &mut TestAppContext) {
 3810    init_test(cx, |_| {});
 3811
 3812    let mut cx = EditorTestContext::new(cx).await;
 3813
 3814    // Manipulate with multiple selections on a single line
 3815    cx.set_state(indoc! {"
 3816        dd«dd
 3817        cˇ»c«c
 3818        bb
 3819        aaaˇ»aa
 3820    "});
 3821    cx.update_editor(|e, window, cx| {
 3822        e.sort_lines_case_sensitive(&SortLinesCaseSensitive, window, cx)
 3823    });
 3824    cx.assert_editor_state(indoc! {"
 3825        «aaaaa
 3826        bb
 3827        ccc
 3828        ddddˇ»
 3829    "});
 3830
 3831    // Manipulate with multiple disjoin selections
 3832    cx.set_state(indoc! {"
 3833 3834        4
 3835        3
 3836        2
 3837        1ˇ»
 3838
 3839        dd«dd
 3840        ccc
 3841        bb
 3842        aaaˇ»aa
 3843    "});
 3844    cx.update_editor(|e, window, cx| {
 3845        e.sort_lines_case_sensitive(&SortLinesCaseSensitive, window, cx)
 3846    });
 3847    cx.assert_editor_state(indoc! {"
 3848        «1
 3849        2
 3850        3
 3851        4
 3852        5ˇ»
 3853
 3854        «aaaaa
 3855        bb
 3856        ccc
 3857        ddddˇ»
 3858    "});
 3859
 3860    // Adding lines on each selection
 3861    cx.set_state(indoc! {"
 3862 3863        1ˇ»
 3864
 3865        bb«bb
 3866        aaaˇ»aa
 3867    "});
 3868    cx.update_editor(|e, window, cx| {
 3869        e.manipulate_lines(window, cx, |lines| lines.push("added line"))
 3870    });
 3871    cx.assert_editor_state(indoc! {"
 3872        «2
 3873        1
 3874        added lineˇ»
 3875
 3876        «bbbb
 3877        aaaaa
 3878        added lineˇ»
 3879    "});
 3880
 3881    // Removing lines on each selection
 3882    cx.set_state(indoc! {"
 3883 3884        1ˇ»
 3885
 3886        bb«bb
 3887        aaaˇ»aa
 3888    "});
 3889    cx.update_editor(|e, window, cx| {
 3890        e.manipulate_lines(window, cx, |lines| {
 3891            lines.pop();
 3892        })
 3893    });
 3894    cx.assert_editor_state(indoc! {"
 3895        «2ˇ»
 3896
 3897        «bbbbˇ»
 3898    "});
 3899}
 3900
 3901#[gpui::test]
 3902async fn test_toggle_case(cx: &mut TestAppContext) {
 3903    init_test(cx, |_| {});
 3904
 3905    let mut cx = EditorTestContext::new(cx).await;
 3906
 3907    // If all lower case -> upper case
 3908    cx.set_state(indoc! {"
 3909        «hello worldˇ»
 3910    "});
 3911    cx.update_editor(|e, window, cx| e.toggle_case(&ToggleCase, window, cx));
 3912    cx.assert_editor_state(indoc! {"
 3913        «HELLO WORLDˇ»
 3914    "});
 3915
 3916    // If all upper case -> lower case
 3917    cx.set_state(indoc! {"
 3918        «HELLO WORLDˇ»
 3919    "});
 3920    cx.update_editor(|e, window, cx| e.toggle_case(&ToggleCase, window, cx));
 3921    cx.assert_editor_state(indoc! {"
 3922        «hello worldˇ»
 3923    "});
 3924
 3925    // If any upper case characters are identified -> lower case
 3926    // This matches JetBrains IDEs
 3927    cx.set_state(indoc! {"
 3928        «hEllo worldˇ»
 3929    "});
 3930    cx.update_editor(|e, window, cx| e.toggle_case(&ToggleCase, window, cx));
 3931    cx.assert_editor_state(indoc! {"
 3932        «hello worldˇ»
 3933    "});
 3934}
 3935
 3936#[gpui::test]
 3937async fn test_manipulate_text(cx: &mut TestAppContext) {
 3938    init_test(cx, |_| {});
 3939
 3940    let mut cx = EditorTestContext::new(cx).await;
 3941
 3942    // Test convert_to_upper_case()
 3943    cx.set_state(indoc! {"
 3944        «hello worldˇ»
 3945    "});
 3946    cx.update_editor(|e, window, cx| e.convert_to_upper_case(&ConvertToUpperCase, window, cx));
 3947    cx.assert_editor_state(indoc! {"
 3948        «HELLO WORLDˇ»
 3949    "});
 3950
 3951    // Test convert_to_lower_case()
 3952    cx.set_state(indoc! {"
 3953        «HELLO WORLDˇ»
 3954    "});
 3955    cx.update_editor(|e, window, cx| e.convert_to_lower_case(&ConvertToLowerCase, window, cx));
 3956    cx.assert_editor_state(indoc! {"
 3957        «hello worldˇ»
 3958    "});
 3959
 3960    // Test multiple line, single selection case
 3961    cx.set_state(indoc! {"
 3962        «The quick brown
 3963        fox jumps over
 3964        the lazy dogˇ»
 3965    "});
 3966    cx.update_editor(|e, window, cx| e.convert_to_title_case(&ConvertToTitleCase, window, cx));
 3967    cx.assert_editor_state(indoc! {"
 3968        «The Quick Brown
 3969        Fox Jumps Over
 3970        The Lazy Dogˇ»
 3971    "});
 3972
 3973    // Test multiple line, single selection case
 3974    cx.set_state(indoc! {"
 3975        «The quick brown
 3976        fox jumps over
 3977        the lazy dogˇ»
 3978    "});
 3979    cx.update_editor(|e, window, cx| {
 3980        e.convert_to_upper_camel_case(&ConvertToUpperCamelCase, window, cx)
 3981    });
 3982    cx.assert_editor_state(indoc! {"
 3983        «TheQuickBrown
 3984        FoxJumpsOver
 3985        TheLazyDogˇ»
 3986    "});
 3987
 3988    // From here on out, test more complex cases of manipulate_text()
 3989
 3990    // Test no selection case - should affect words cursors are in
 3991    // Cursor at beginning, middle, and end of word
 3992    cx.set_state(indoc! {"
 3993        ˇhello big beauˇtiful worldˇ
 3994    "});
 3995    cx.update_editor(|e, window, cx| e.convert_to_upper_case(&ConvertToUpperCase, window, cx));
 3996    cx.assert_editor_state(indoc! {"
 3997        «HELLOˇ» big «BEAUTIFULˇ» «WORLDˇ»
 3998    "});
 3999
 4000    // Test multiple selections on a single line and across multiple lines
 4001    cx.set_state(indoc! {"
 4002        «Theˇ» quick «brown
 4003        foxˇ» jumps «overˇ»
 4004        the «lazyˇ» dog
 4005    "});
 4006    cx.update_editor(|e, window, cx| e.convert_to_upper_case(&ConvertToUpperCase, window, cx));
 4007    cx.assert_editor_state(indoc! {"
 4008        «THEˇ» quick «BROWN
 4009        FOXˇ» jumps «OVERˇ»
 4010        the «LAZYˇ» dog
 4011    "});
 4012
 4013    // Test case where text length grows
 4014    cx.set_state(indoc! {"
 4015        «tschüߡ»
 4016    "});
 4017    cx.update_editor(|e, window, cx| e.convert_to_upper_case(&ConvertToUpperCase, window, cx));
 4018    cx.assert_editor_state(indoc! {"
 4019        «TSCHÜSSˇ»
 4020    "});
 4021
 4022    // Test to make sure we don't crash when text shrinks
 4023    cx.set_state(indoc! {"
 4024        aaa_bbbˇ
 4025    "});
 4026    cx.update_editor(|e, window, cx| {
 4027        e.convert_to_lower_camel_case(&ConvertToLowerCamelCase, window, cx)
 4028    });
 4029    cx.assert_editor_state(indoc! {"
 4030        «aaaBbbˇ»
 4031    "});
 4032
 4033    // Test to make sure we all aware of the fact that each word can grow and shrink
 4034    // Final selections should be aware of this fact
 4035    cx.set_state(indoc! {"
 4036        aaa_bˇbb bbˇb_ccc ˇccc_ddd
 4037    "});
 4038    cx.update_editor(|e, window, cx| {
 4039        e.convert_to_lower_camel_case(&ConvertToLowerCamelCase, window, cx)
 4040    });
 4041    cx.assert_editor_state(indoc! {"
 4042        «aaaBbbˇ» «bbbCccˇ» «cccDddˇ»
 4043    "});
 4044
 4045    cx.set_state(indoc! {"
 4046        «hElLo, WoRld!ˇ»
 4047    "});
 4048    cx.update_editor(|e, window, cx| {
 4049        e.convert_to_opposite_case(&ConvertToOppositeCase, window, cx)
 4050    });
 4051    cx.assert_editor_state(indoc! {"
 4052        «HeLlO, wOrLD!ˇ»
 4053    "});
 4054}
 4055
 4056#[gpui::test]
 4057fn test_duplicate_line(cx: &mut TestAppContext) {
 4058    init_test(cx, |_| {});
 4059
 4060    let editor = cx.add_window(|window, cx| {
 4061        let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
 4062        build_editor(buffer, window, cx)
 4063    });
 4064    _ = editor.update(cx, |editor, window, cx| {
 4065        editor.change_selections(None, window, cx, |s| {
 4066            s.select_display_ranges([
 4067                DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(0), 1),
 4068                DisplayPoint::new(DisplayRow(0), 2)..DisplayPoint::new(DisplayRow(0), 2),
 4069                DisplayPoint::new(DisplayRow(1), 0)..DisplayPoint::new(DisplayRow(1), 0),
 4070                DisplayPoint::new(DisplayRow(3), 0)..DisplayPoint::new(DisplayRow(3), 0),
 4071            ])
 4072        });
 4073        editor.duplicate_line_down(&DuplicateLineDown, window, cx);
 4074        assert_eq!(editor.display_text(cx), "abc\nabc\ndef\ndef\nghi\n\n");
 4075        assert_eq!(
 4076            editor.selections.display_ranges(cx),
 4077            vec![
 4078                DisplayPoint::new(DisplayRow(1), 0)..DisplayPoint::new(DisplayRow(1), 1),
 4079                DisplayPoint::new(DisplayRow(1), 2)..DisplayPoint::new(DisplayRow(1), 2),
 4080                DisplayPoint::new(DisplayRow(3), 0)..DisplayPoint::new(DisplayRow(3), 0),
 4081                DisplayPoint::new(DisplayRow(6), 0)..DisplayPoint::new(DisplayRow(6), 0),
 4082            ]
 4083        );
 4084    });
 4085
 4086    let editor = cx.add_window(|window, cx| {
 4087        let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
 4088        build_editor(buffer, window, cx)
 4089    });
 4090    _ = editor.update(cx, |editor, window, cx| {
 4091        editor.change_selections(None, window, cx, |s| {
 4092            s.select_display_ranges([
 4093                DisplayPoint::new(DisplayRow(0), 1)..DisplayPoint::new(DisplayRow(1), 1),
 4094                DisplayPoint::new(DisplayRow(1), 2)..DisplayPoint::new(DisplayRow(2), 1),
 4095            ])
 4096        });
 4097        editor.duplicate_line_down(&DuplicateLineDown, window, cx);
 4098        assert_eq!(editor.display_text(cx), "abc\ndef\nghi\nabc\ndef\nghi\n");
 4099        assert_eq!(
 4100            editor.selections.display_ranges(cx),
 4101            vec![
 4102                DisplayPoint::new(DisplayRow(3), 1)..DisplayPoint::new(DisplayRow(4), 1),
 4103                DisplayPoint::new(DisplayRow(4), 2)..DisplayPoint::new(DisplayRow(5), 1),
 4104            ]
 4105        );
 4106    });
 4107
 4108    // With `move_upwards` the selections stay in place, except for
 4109    // the lines inserted above them
 4110    let editor = cx.add_window(|window, cx| {
 4111        let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
 4112        build_editor(buffer, window, cx)
 4113    });
 4114    _ = editor.update(cx, |editor, window, cx| {
 4115        editor.change_selections(None, window, cx, |s| {
 4116            s.select_display_ranges([
 4117                DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(0), 1),
 4118                DisplayPoint::new(DisplayRow(0), 2)..DisplayPoint::new(DisplayRow(0), 2),
 4119                DisplayPoint::new(DisplayRow(1), 0)..DisplayPoint::new(DisplayRow(1), 0),
 4120                DisplayPoint::new(DisplayRow(3), 0)..DisplayPoint::new(DisplayRow(3), 0),
 4121            ])
 4122        });
 4123        editor.duplicate_line_up(&DuplicateLineUp, window, cx);
 4124        assert_eq!(editor.display_text(cx), "abc\nabc\ndef\ndef\nghi\n\n");
 4125        assert_eq!(
 4126            editor.selections.display_ranges(cx),
 4127            vec![
 4128                DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(0), 1),
 4129                DisplayPoint::new(DisplayRow(0), 2)..DisplayPoint::new(DisplayRow(0), 2),
 4130                DisplayPoint::new(DisplayRow(2), 0)..DisplayPoint::new(DisplayRow(2), 0),
 4131                DisplayPoint::new(DisplayRow(6), 0)..DisplayPoint::new(DisplayRow(6), 0),
 4132            ]
 4133        );
 4134    });
 4135
 4136    let editor = cx.add_window(|window, cx| {
 4137        let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
 4138        build_editor(buffer, window, cx)
 4139    });
 4140    _ = editor.update(cx, |editor, window, cx| {
 4141        editor.change_selections(None, window, cx, |s| {
 4142            s.select_display_ranges([
 4143                DisplayPoint::new(DisplayRow(0), 1)..DisplayPoint::new(DisplayRow(1), 1),
 4144                DisplayPoint::new(DisplayRow(1), 2)..DisplayPoint::new(DisplayRow(2), 1),
 4145            ])
 4146        });
 4147        editor.duplicate_line_up(&DuplicateLineUp, window, cx);
 4148        assert_eq!(editor.display_text(cx), "abc\ndef\nghi\nabc\ndef\nghi\n");
 4149        assert_eq!(
 4150            editor.selections.display_ranges(cx),
 4151            vec![
 4152                DisplayPoint::new(DisplayRow(0), 1)..DisplayPoint::new(DisplayRow(1), 1),
 4153                DisplayPoint::new(DisplayRow(1), 2)..DisplayPoint::new(DisplayRow(2), 1),
 4154            ]
 4155        );
 4156    });
 4157
 4158    let editor = cx.add_window(|window, cx| {
 4159        let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
 4160        build_editor(buffer, window, cx)
 4161    });
 4162    _ = editor.update(cx, |editor, window, cx| {
 4163        editor.change_selections(None, window, cx, |s| {
 4164            s.select_display_ranges([
 4165                DisplayPoint::new(DisplayRow(0), 1)..DisplayPoint::new(DisplayRow(1), 1),
 4166                DisplayPoint::new(DisplayRow(1), 2)..DisplayPoint::new(DisplayRow(2), 1),
 4167            ])
 4168        });
 4169        editor.duplicate_selection(&DuplicateSelection, window, cx);
 4170        assert_eq!(editor.display_text(cx), "abc\ndbc\ndef\ngf\nghi\n");
 4171        assert_eq!(
 4172            editor.selections.display_ranges(cx),
 4173            vec![
 4174                DisplayPoint::new(DisplayRow(0), 1)..DisplayPoint::new(DisplayRow(1), 1),
 4175                DisplayPoint::new(DisplayRow(2), 2)..DisplayPoint::new(DisplayRow(3), 1),
 4176            ]
 4177        );
 4178    });
 4179}
 4180
 4181#[gpui::test]
 4182fn test_move_line_up_down(cx: &mut TestAppContext) {
 4183    init_test(cx, |_| {});
 4184
 4185    let editor = cx.add_window(|window, cx| {
 4186        let buffer = MultiBuffer::build_simple(&sample_text(10, 5, 'a'), cx);
 4187        build_editor(buffer, window, cx)
 4188    });
 4189    _ = editor.update(cx, |editor, window, cx| {
 4190        editor.fold_creases(
 4191            vec![
 4192                Crease::simple(Point::new(0, 2)..Point::new(1, 2), FoldPlaceholder::test()),
 4193                Crease::simple(Point::new(2, 3)..Point::new(4, 1), FoldPlaceholder::test()),
 4194                Crease::simple(Point::new(7, 0)..Point::new(8, 4), FoldPlaceholder::test()),
 4195            ],
 4196            true,
 4197            window,
 4198            cx,
 4199        );
 4200        editor.change_selections(None, window, cx, |s| {
 4201            s.select_display_ranges([
 4202                DisplayPoint::new(DisplayRow(0), 1)..DisplayPoint::new(DisplayRow(0), 1),
 4203                DisplayPoint::new(DisplayRow(3), 1)..DisplayPoint::new(DisplayRow(3), 1),
 4204                DisplayPoint::new(DisplayRow(3), 2)..DisplayPoint::new(DisplayRow(4), 3),
 4205                DisplayPoint::new(DisplayRow(5), 0)..DisplayPoint::new(DisplayRow(5), 2),
 4206            ])
 4207        });
 4208        assert_eq!(
 4209            editor.display_text(cx),
 4210            "aa⋯bbb\nccc⋯eeee\nfffff\nggggg\n⋯i\njjjjj"
 4211        );
 4212
 4213        editor.move_line_up(&MoveLineUp, window, cx);
 4214        assert_eq!(
 4215            editor.display_text(cx),
 4216            "aa⋯bbb\nccc⋯eeee\nggggg\n⋯i\njjjjj\nfffff"
 4217        );
 4218        assert_eq!(
 4219            editor.selections.display_ranges(cx),
 4220            vec![
 4221                DisplayPoint::new(DisplayRow(0), 1)..DisplayPoint::new(DisplayRow(0), 1),
 4222                DisplayPoint::new(DisplayRow(2), 1)..DisplayPoint::new(DisplayRow(2), 1),
 4223                DisplayPoint::new(DisplayRow(2), 2)..DisplayPoint::new(DisplayRow(3), 3),
 4224                DisplayPoint::new(DisplayRow(4), 0)..DisplayPoint::new(DisplayRow(4), 2)
 4225            ]
 4226        );
 4227    });
 4228
 4229    _ = editor.update(cx, |editor, window, cx| {
 4230        editor.move_line_down(&MoveLineDown, window, cx);
 4231        assert_eq!(
 4232            editor.display_text(cx),
 4233            "ccc⋯eeee\naa⋯bbb\nfffff\nggggg\n⋯i\njjjjj"
 4234        );
 4235        assert_eq!(
 4236            editor.selections.display_ranges(cx),
 4237            vec![
 4238                DisplayPoint::new(DisplayRow(1), 1)..DisplayPoint::new(DisplayRow(1), 1),
 4239                DisplayPoint::new(DisplayRow(3), 1)..DisplayPoint::new(DisplayRow(3), 1),
 4240                DisplayPoint::new(DisplayRow(3), 2)..DisplayPoint::new(DisplayRow(4), 3),
 4241                DisplayPoint::new(DisplayRow(5), 0)..DisplayPoint::new(DisplayRow(5), 2)
 4242            ]
 4243        );
 4244    });
 4245
 4246    _ = editor.update(cx, |editor, window, cx| {
 4247        editor.move_line_down(&MoveLineDown, window, cx);
 4248        assert_eq!(
 4249            editor.display_text(cx),
 4250            "ccc⋯eeee\nfffff\naa⋯bbb\nggggg\n⋯i\njjjjj"
 4251        );
 4252        assert_eq!(
 4253            editor.selections.display_ranges(cx),
 4254            vec![
 4255                DisplayPoint::new(DisplayRow(2), 1)..DisplayPoint::new(DisplayRow(2), 1),
 4256                DisplayPoint::new(DisplayRow(3), 1)..DisplayPoint::new(DisplayRow(3), 1),
 4257                DisplayPoint::new(DisplayRow(3), 2)..DisplayPoint::new(DisplayRow(4), 3),
 4258                DisplayPoint::new(DisplayRow(5), 0)..DisplayPoint::new(DisplayRow(5), 2)
 4259            ]
 4260        );
 4261    });
 4262
 4263    _ = editor.update(cx, |editor, window, cx| {
 4264        editor.move_line_up(&MoveLineUp, window, cx);
 4265        assert_eq!(
 4266            editor.display_text(cx),
 4267            "ccc⋯eeee\naa⋯bbb\nggggg\n⋯i\njjjjj\nfffff"
 4268        );
 4269        assert_eq!(
 4270            editor.selections.display_ranges(cx),
 4271            vec![
 4272                DisplayPoint::new(DisplayRow(1), 1)..DisplayPoint::new(DisplayRow(1), 1),
 4273                DisplayPoint::new(DisplayRow(2), 1)..DisplayPoint::new(DisplayRow(2), 1),
 4274                DisplayPoint::new(DisplayRow(2), 2)..DisplayPoint::new(DisplayRow(3), 3),
 4275                DisplayPoint::new(DisplayRow(4), 0)..DisplayPoint::new(DisplayRow(4), 2)
 4276            ]
 4277        );
 4278    });
 4279}
 4280
 4281#[gpui::test]
 4282fn test_move_line_up_down_with_blocks(cx: &mut TestAppContext) {
 4283    init_test(cx, |_| {});
 4284
 4285    let editor = cx.add_window(|window, cx| {
 4286        let buffer = MultiBuffer::build_simple(&sample_text(10, 5, 'a'), cx);
 4287        build_editor(buffer, window, cx)
 4288    });
 4289    _ = editor.update(cx, |editor, window, cx| {
 4290        let snapshot = editor.buffer.read(cx).snapshot(cx);
 4291        editor.insert_blocks(
 4292            [BlockProperties {
 4293                style: BlockStyle::Fixed,
 4294                placement: BlockPlacement::Below(snapshot.anchor_after(Point::new(2, 0))),
 4295                height: Some(1),
 4296                render: Arc::new(|_| div().into_any()),
 4297                priority: 0,
 4298            }],
 4299            Some(Autoscroll::fit()),
 4300            cx,
 4301        );
 4302        editor.change_selections(None, window, cx, |s| {
 4303            s.select_ranges([Point::new(2, 0)..Point::new(2, 0)])
 4304        });
 4305        editor.move_line_down(&MoveLineDown, window, cx);
 4306    });
 4307}
 4308
 4309#[gpui::test]
 4310async fn test_selections_and_replace_blocks(cx: &mut TestAppContext) {
 4311    init_test(cx, |_| {});
 4312
 4313    let mut cx = EditorTestContext::new(cx).await;
 4314    cx.set_state(
 4315        &"
 4316            ˇzero
 4317            one
 4318            two
 4319            three
 4320            four
 4321            five
 4322        "
 4323        .unindent(),
 4324    );
 4325
 4326    // Create a four-line block that replaces three lines of text.
 4327    cx.update_editor(|editor, window, cx| {
 4328        let snapshot = editor.snapshot(window, cx);
 4329        let snapshot = &snapshot.buffer_snapshot;
 4330        let placement = BlockPlacement::Replace(
 4331            snapshot.anchor_after(Point::new(1, 0))..=snapshot.anchor_after(Point::new(3, 0)),
 4332        );
 4333        editor.insert_blocks(
 4334            [BlockProperties {
 4335                placement,
 4336                height: Some(4),
 4337                style: BlockStyle::Sticky,
 4338                render: Arc::new(|_| gpui::div().into_any_element()),
 4339                priority: 0,
 4340            }],
 4341            None,
 4342            cx,
 4343        );
 4344    });
 4345
 4346    // Move down so that the cursor touches the block.
 4347    cx.update_editor(|editor, window, cx| {
 4348        editor.move_down(&Default::default(), window, cx);
 4349    });
 4350    cx.assert_editor_state(
 4351        &"
 4352            zero
 4353            «one
 4354            two
 4355            threeˇ»
 4356            four
 4357            five
 4358        "
 4359        .unindent(),
 4360    );
 4361
 4362    // Move down past the block.
 4363    cx.update_editor(|editor, window, cx| {
 4364        editor.move_down(&Default::default(), window, cx);
 4365    });
 4366    cx.assert_editor_state(
 4367        &"
 4368            zero
 4369            one
 4370            two
 4371            three
 4372            ˇfour
 4373            five
 4374        "
 4375        .unindent(),
 4376    );
 4377}
 4378
 4379#[gpui::test]
 4380fn test_transpose(cx: &mut TestAppContext) {
 4381    init_test(cx, |_| {});
 4382
 4383    _ = cx.add_window(|window, cx| {
 4384        let mut editor = build_editor(MultiBuffer::build_simple("abc", cx), window, cx);
 4385        editor.set_style(EditorStyle::default(), window, cx);
 4386        editor.change_selections(None, window, cx, |s| s.select_ranges([1..1]));
 4387        editor.transpose(&Default::default(), window, cx);
 4388        assert_eq!(editor.text(cx), "bac");
 4389        assert_eq!(editor.selections.ranges(cx), [2..2]);
 4390
 4391        editor.transpose(&Default::default(), window, cx);
 4392        assert_eq!(editor.text(cx), "bca");
 4393        assert_eq!(editor.selections.ranges(cx), [3..3]);
 4394
 4395        editor.transpose(&Default::default(), window, cx);
 4396        assert_eq!(editor.text(cx), "bac");
 4397        assert_eq!(editor.selections.ranges(cx), [3..3]);
 4398
 4399        editor
 4400    });
 4401
 4402    _ = cx.add_window(|window, cx| {
 4403        let mut editor = build_editor(MultiBuffer::build_simple("abc\nde", cx), window, cx);
 4404        editor.set_style(EditorStyle::default(), window, cx);
 4405        editor.change_selections(None, window, cx, |s| s.select_ranges([3..3]));
 4406        editor.transpose(&Default::default(), window, cx);
 4407        assert_eq!(editor.text(cx), "acb\nde");
 4408        assert_eq!(editor.selections.ranges(cx), [3..3]);
 4409
 4410        editor.change_selections(None, window, cx, |s| s.select_ranges([4..4]));
 4411        editor.transpose(&Default::default(), window, cx);
 4412        assert_eq!(editor.text(cx), "acbd\ne");
 4413        assert_eq!(editor.selections.ranges(cx), [5..5]);
 4414
 4415        editor.transpose(&Default::default(), window, cx);
 4416        assert_eq!(editor.text(cx), "acbde\n");
 4417        assert_eq!(editor.selections.ranges(cx), [6..6]);
 4418
 4419        editor.transpose(&Default::default(), window, cx);
 4420        assert_eq!(editor.text(cx), "acbd\ne");
 4421        assert_eq!(editor.selections.ranges(cx), [6..6]);
 4422
 4423        editor
 4424    });
 4425
 4426    _ = cx.add_window(|window, cx| {
 4427        let mut editor = build_editor(MultiBuffer::build_simple("abc\nde", cx), window, cx);
 4428        editor.set_style(EditorStyle::default(), window, cx);
 4429        editor.change_selections(None, window, cx, |s| s.select_ranges([1..1, 2..2, 4..4]));
 4430        editor.transpose(&Default::default(), window, cx);
 4431        assert_eq!(editor.text(cx), "bacd\ne");
 4432        assert_eq!(editor.selections.ranges(cx), [2..2, 3..3, 5..5]);
 4433
 4434        editor.transpose(&Default::default(), window, cx);
 4435        assert_eq!(editor.text(cx), "bcade\n");
 4436        assert_eq!(editor.selections.ranges(cx), [3..3, 4..4, 6..6]);
 4437
 4438        editor.transpose(&Default::default(), window, cx);
 4439        assert_eq!(editor.text(cx), "bcda\ne");
 4440        assert_eq!(editor.selections.ranges(cx), [4..4, 6..6]);
 4441
 4442        editor.transpose(&Default::default(), window, cx);
 4443        assert_eq!(editor.text(cx), "bcade\n");
 4444        assert_eq!(editor.selections.ranges(cx), [4..4, 6..6]);
 4445
 4446        editor.transpose(&Default::default(), window, cx);
 4447        assert_eq!(editor.text(cx), "bcaed\n");
 4448        assert_eq!(editor.selections.ranges(cx), [5..5, 6..6]);
 4449
 4450        editor
 4451    });
 4452
 4453    _ = cx.add_window(|window, cx| {
 4454        let mut editor = build_editor(MultiBuffer::build_simple("🍐🏀✋", cx), window, cx);
 4455        editor.set_style(EditorStyle::default(), window, cx);
 4456        editor.change_selections(None, window, cx, |s| s.select_ranges([4..4]));
 4457        editor.transpose(&Default::default(), window, cx);
 4458        assert_eq!(editor.text(cx), "🏀🍐✋");
 4459        assert_eq!(editor.selections.ranges(cx), [8..8]);
 4460
 4461        editor.transpose(&Default::default(), window, cx);
 4462        assert_eq!(editor.text(cx), "🏀✋🍐");
 4463        assert_eq!(editor.selections.ranges(cx), [11..11]);
 4464
 4465        editor.transpose(&Default::default(), window, cx);
 4466        assert_eq!(editor.text(cx), "🏀🍐✋");
 4467        assert_eq!(editor.selections.ranges(cx), [11..11]);
 4468
 4469        editor
 4470    });
 4471}
 4472
 4473#[gpui::test]
 4474async fn test_rewrap(cx: &mut TestAppContext) {
 4475    init_test(cx, |settings| {
 4476        settings.languages.extend([
 4477            (
 4478                "Markdown".into(),
 4479                LanguageSettingsContent {
 4480                    allow_rewrap: Some(language_settings::RewrapBehavior::Anywhere),
 4481                    ..Default::default()
 4482                },
 4483            ),
 4484            (
 4485                "Plain Text".into(),
 4486                LanguageSettingsContent {
 4487                    allow_rewrap: Some(language_settings::RewrapBehavior::Anywhere),
 4488                    ..Default::default()
 4489                },
 4490            ),
 4491        ])
 4492    });
 4493
 4494    let mut cx = EditorTestContext::new(cx).await;
 4495
 4496    let language_with_c_comments = Arc::new(Language::new(
 4497        LanguageConfig {
 4498            line_comments: vec!["// ".into()],
 4499            ..LanguageConfig::default()
 4500        },
 4501        None,
 4502    ));
 4503    let language_with_pound_comments = Arc::new(Language::new(
 4504        LanguageConfig {
 4505            line_comments: vec!["# ".into()],
 4506            ..LanguageConfig::default()
 4507        },
 4508        None,
 4509    ));
 4510    let markdown_language = Arc::new(Language::new(
 4511        LanguageConfig {
 4512            name: "Markdown".into(),
 4513            ..LanguageConfig::default()
 4514        },
 4515        None,
 4516    ));
 4517    let language_with_doc_comments = Arc::new(Language::new(
 4518        LanguageConfig {
 4519            line_comments: vec!["// ".into(), "/// ".into()],
 4520            ..LanguageConfig::default()
 4521        },
 4522        Some(tree_sitter_rust::LANGUAGE.into()),
 4523    ));
 4524
 4525    let plaintext_language = Arc::new(Language::new(
 4526        LanguageConfig {
 4527            name: "Plain Text".into(),
 4528            ..LanguageConfig::default()
 4529        },
 4530        None,
 4531    ));
 4532
 4533    assert_rewrap(
 4534        indoc! {"
 4535            // ˇLorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus mollis elit purus, a ornare lacus gravida vitae. Proin consectetur felis vel purus auctor, eu lacinia sapien scelerisque. Vivamus sit amet neque et quam tincidunt hendrerit. Praesent semper egestas tellus id dignissim. Pellentesque odio lectus, iaculis ac volutpat et, blandit quis urna. Sed vestibulum nisi sit amet nisl venenatis tempus. Donec molestie blandit quam, et porta nunc laoreet in. Integer sit amet scelerisque nisi. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras egestas porta metus, eu viverra ipsum efficitur quis. Donec luctus eros turpis, id vulputate turpis porttitor id. Aliquam id accumsan eros.
 4536        "},
 4537        indoc! {"
 4538            // ˇLorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus mollis elit
 4539            // purus, a ornare lacus gravida vitae. Proin consectetur felis vel purus
 4540            // auctor, eu lacinia sapien scelerisque. Vivamus sit amet neque et quam
 4541            // tincidunt hendrerit. Praesent semper egestas tellus id dignissim.
 4542            // Pellentesque odio lectus, iaculis ac volutpat et, blandit quis urna. Sed
 4543            // vestibulum nisi sit amet nisl venenatis tempus. Donec molestie blandit quam,
 4544            // et porta nunc laoreet in. Integer sit amet scelerisque nisi. Lorem ipsum
 4545            // dolor sit amet, consectetur adipiscing elit. Cras egestas porta metus, eu
 4546            // viverra ipsum efficitur quis. Donec luctus eros turpis, id vulputate turpis
 4547            // porttitor id. Aliquam id accumsan eros.
 4548        "},
 4549        language_with_c_comments.clone(),
 4550        &mut cx,
 4551    );
 4552
 4553    // Test that rewrapping works inside of a selection
 4554    assert_rewrap(
 4555        indoc! {"
 4556            «// Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus mollis elit purus, a ornare lacus gravida vitae. Proin consectetur felis vel purus auctor, eu lacinia sapien scelerisque. Vivamus sit amet neque et quam tincidunt hendrerit. Praesent semper egestas tellus id dignissim. Pellentesque odio lectus, iaculis ac volutpat et, blandit quis urna. Sed vestibulum nisi sit amet nisl venenatis tempus. Donec molestie blandit quam, et porta nunc laoreet in. Integer sit amet scelerisque nisi. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras egestas porta metus, eu viverra ipsum efficitur quis. Donec luctus eros turpis, id vulputate turpis porttitor id. Aliquam id accumsan eros.ˇ»
 4557        "},
 4558        indoc! {"
 4559            «// Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus mollis elit
 4560            // purus, a ornare lacus gravida vitae. Proin consectetur felis vel purus
 4561            // auctor, eu lacinia sapien scelerisque. Vivamus sit amet neque et quam
 4562            // tincidunt hendrerit. Praesent semper egestas tellus id dignissim.
 4563            // Pellentesque odio lectus, iaculis ac volutpat et, blandit quis urna. Sed
 4564            // vestibulum nisi sit amet nisl venenatis tempus. Donec molestie blandit quam,
 4565            // et porta nunc laoreet in. Integer sit amet scelerisque nisi. Lorem ipsum
 4566            // dolor sit amet, consectetur adipiscing elit. Cras egestas porta metus, eu
 4567            // viverra ipsum efficitur quis. Donec luctus eros turpis, id vulputate turpis
 4568            // porttitor id. Aliquam id accumsan eros.ˇ»
 4569        "},
 4570        language_with_c_comments.clone(),
 4571        &mut cx,
 4572    );
 4573
 4574    // Test that cursors that expand to the same region are collapsed.
 4575    assert_rewrap(
 4576        indoc! {"
 4577            // ˇLorem ipsum dolor sit amet, consectetur adipiscing elit.
 4578            // ˇVivamus mollis elit purus, a ornare lacus gravida vitae. Proin consectetur felis vel purus auctor, eu lacinia sapien scelerisque.
 4579            // ˇVivamus sit amet neque et quam tincidunt hendrerit. Praesent semper egestas tellus id dignissim. Pellentesque odio lectus, iaculis ac volutpat et,
 4580            // ˇblandit quis urna. Sed vestibulum nisi sit amet nisl venenatis tempus. Donec molestie blandit quam, et porta nunc laoreet in. Integer sit amet scelerisque nisi. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras egestas porta metus, eu viverra ipsum efficitur quis. Donec luctus eros turpis, id vulputate turpis porttitor id. Aliquam id accumsan eros.
 4581        "},
 4582        indoc! {"
 4583            // ˇLorem ipsum dolor sit amet, consectetur adipiscing elit. ˇVivamus mollis elit
 4584            // purus, a ornare lacus gravida vitae. Proin consectetur felis vel purus
 4585            // auctor, eu lacinia sapien scelerisque. ˇVivamus sit amet neque et quam
 4586            // tincidunt hendrerit. Praesent semper egestas tellus id dignissim.
 4587            // Pellentesque odio lectus, iaculis ac volutpat et, ˇblandit quis urna. Sed
 4588            // vestibulum nisi sit amet nisl venenatis tempus. Donec molestie blandit quam,
 4589            // et porta nunc laoreet in. Integer sit amet scelerisque nisi. Lorem ipsum
 4590            // dolor sit amet, consectetur adipiscing elit. Cras egestas porta metus, eu
 4591            // viverra ipsum efficitur quis. Donec luctus eros turpis, id vulputate turpis
 4592            // porttitor id. Aliquam id accumsan eros.
 4593        "},
 4594        language_with_c_comments.clone(),
 4595        &mut cx,
 4596    );
 4597
 4598    // Test that non-contiguous selections are treated separately.
 4599    assert_rewrap(
 4600        indoc! {"
 4601            // ˇLorem ipsum dolor sit amet, consectetur adipiscing elit.
 4602            // ˇVivamus mollis elit purus, a ornare lacus gravida vitae. Proin consectetur felis vel purus auctor, eu lacinia sapien scelerisque.
 4603            //
 4604            // ˇVivamus sit amet neque et quam tincidunt hendrerit. Praesent semper egestas tellus id dignissim. Pellentesque odio lectus, iaculis ac volutpat et,
 4605            // ˇblandit quis urna. Sed vestibulum nisi sit amet nisl venenatis tempus. Donec molestie blandit quam, et porta nunc laoreet in. Integer sit amet scelerisque nisi. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras egestas porta metus, eu viverra ipsum efficitur quis. Donec luctus eros turpis, id vulputate turpis porttitor id. Aliquam id accumsan eros.
 4606        "},
 4607        indoc! {"
 4608            // ˇLorem ipsum dolor sit amet, consectetur adipiscing elit. ˇVivamus mollis elit
 4609            // purus, a ornare lacus gravida vitae. Proin consectetur felis vel purus
 4610            // auctor, eu lacinia sapien scelerisque.
 4611            //
 4612            // ˇVivamus sit amet neque et quam tincidunt hendrerit. Praesent semper egestas
 4613            // tellus id dignissim. Pellentesque odio lectus, iaculis ac volutpat et,
 4614            // ˇblandit quis urna. Sed vestibulum nisi sit amet nisl venenatis tempus. Donec
 4615            // molestie blandit quam, et porta nunc laoreet in. Integer sit amet scelerisque
 4616            // nisi. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras egestas
 4617            // porta metus, eu viverra ipsum efficitur quis. Donec luctus eros turpis, id
 4618            // vulputate turpis porttitor id. Aliquam id accumsan eros.
 4619        "},
 4620        language_with_c_comments.clone(),
 4621        &mut cx,
 4622    );
 4623
 4624    // Test that different comment prefixes are supported.
 4625    assert_rewrap(
 4626        indoc! {"
 4627            # ˇLorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus mollis elit purus, a ornare lacus gravida vitae. Proin consectetur felis vel purus auctor, eu lacinia sapien scelerisque. Vivamus sit amet neque et quam tincidunt hendrerit. Praesent semper egestas tellus id dignissim. Pellentesque odio lectus, iaculis ac volutpat et, blandit quis urna. Sed vestibulum nisi sit amet nisl venenatis tempus. Donec molestie blandit quam, et porta nunc laoreet in. Integer sit amet scelerisque nisi. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras egestas porta metus, eu viverra ipsum efficitur quis. Donec luctus eros turpis, id vulputate turpis porttitor id. Aliquam id accumsan eros.
 4628        "},
 4629        indoc! {"
 4630            # ˇLorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus mollis elit
 4631            # purus, a ornare lacus gravida vitae. Proin consectetur felis vel purus auctor,
 4632            # eu lacinia sapien scelerisque. Vivamus sit amet neque et quam tincidunt
 4633            # hendrerit. Praesent semper egestas tellus id dignissim. Pellentesque odio
 4634            # lectus, iaculis ac volutpat et, blandit quis urna. Sed vestibulum nisi sit
 4635            # amet nisl venenatis tempus. Donec molestie blandit quam, et porta nunc laoreet
 4636            # in. Integer sit amet scelerisque nisi. Lorem ipsum dolor sit amet, consectetur
 4637            # adipiscing elit. Cras egestas porta metus, eu viverra ipsum efficitur quis.
 4638            # Donec luctus eros turpis, id vulputate turpis porttitor id. Aliquam id
 4639            # accumsan eros.
 4640        "},
 4641        language_with_pound_comments.clone(),
 4642        &mut cx,
 4643    );
 4644
 4645    // Test that rewrapping is ignored outside of comments in most languages.
 4646    assert_rewrap(
 4647        indoc! {"
 4648            /// Adds two numbers.
 4649            /// Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus mollis elit purus, a ornare lacus gravida vitae.ˇ
 4650            fn add(a: u32, b: u32) -> u32 {
 4651                a + b + a + b + a + b + a + b + a + b + a + b + a + b + a + b + a + b + a + b + a + b + a + b + a + b + a + b + a + b + a + bˇ
 4652            }
 4653        "},
 4654        indoc! {"
 4655            /// Adds two numbers. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
 4656            /// Vivamus mollis elit purus, a ornare lacus gravida vitae.ˇ
 4657            fn add(a: u32, b: u32) -> u32 {
 4658                a + b + a + b + a + b + a + b + a + b + a + b + a + b + a + b + a + b + a + b + a + b + a + b + a + b + a + b + a + b + a + bˇ
 4659            }
 4660        "},
 4661        language_with_doc_comments.clone(),
 4662        &mut cx,
 4663    );
 4664
 4665    // Test that rewrapping works in Markdown and Plain Text languages.
 4666    assert_rewrap(
 4667        indoc! {"
 4668            # Hello
 4669
 4670            Lorem ipsum dolor sit amet, ˇconsectetur adipiscing elit. Vivamus mollis elit purus, a ornare lacus gravida vitae. Proin consectetur felis vel purus auctor, eu lacinia sapien scelerisque. Vivamus sit amet neque et quam tincidunt hendrerit. Praesent semper egestas tellus id dignissim. Pellentesque odio lectus, iaculis ac volutpat et, blandit quis urna. Sed vestibulum nisi sit amet nisl venenatis tempus. Donec molestie blandit quam, et porta nunc laoreet in. Integer sit amet scelerisque nisi.
 4671        "},
 4672        indoc! {"
 4673            # Hello
 4674
 4675            Lorem ipsum dolor sit amet, ˇconsectetur adipiscing elit. Vivamus mollis elit
 4676            purus, a ornare lacus gravida vitae. Proin consectetur felis vel purus auctor,
 4677            eu lacinia sapien scelerisque. Vivamus sit amet neque et quam tincidunt
 4678            hendrerit. Praesent semper egestas tellus id dignissim. Pellentesque odio
 4679            lectus, iaculis ac volutpat et, blandit quis urna. Sed vestibulum nisi sit amet
 4680            nisl venenatis tempus. Donec molestie blandit quam, et porta nunc laoreet in.
 4681            Integer sit amet scelerisque nisi.
 4682        "},
 4683        markdown_language,
 4684        &mut cx,
 4685    );
 4686
 4687    assert_rewrap(
 4688        indoc! {"
 4689            Lorem ipsum dolor sit amet, ˇconsectetur adipiscing elit. Vivamus mollis elit purus, a ornare lacus gravida vitae. Proin consectetur felis vel purus auctor, eu lacinia sapien scelerisque. Vivamus sit amet neque et quam tincidunt hendrerit. Praesent semper egestas tellus id dignissim. Pellentesque odio lectus, iaculis ac volutpat et, blandit quis urna. Sed vestibulum nisi sit amet nisl venenatis tempus. Donec molestie blandit quam, et porta nunc laoreet in. Integer sit amet scelerisque nisi.
 4690        "},
 4691        indoc! {"
 4692            Lorem ipsum dolor sit amet, ˇconsectetur adipiscing elit. Vivamus mollis elit
 4693            purus, a ornare lacus gravida vitae. Proin consectetur felis vel purus auctor,
 4694            eu lacinia sapien scelerisque. Vivamus sit amet neque et quam tincidunt
 4695            hendrerit. Praesent semper egestas tellus id dignissim. Pellentesque odio
 4696            lectus, iaculis ac volutpat et, blandit quis urna. Sed vestibulum nisi sit amet
 4697            nisl venenatis tempus. Donec molestie blandit quam, et porta nunc laoreet in.
 4698            Integer sit amet scelerisque nisi.
 4699        "},
 4700        plaintext_language,
 4701        &mut cx,
 4702    );
 4703
 4704    // Test rewrapping unaligned comments in a selection.
 4705    assert_rewrap(
 4706        indoc! {"
 4707            fn foo() {
 4708                if true {
 4709            «        // Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus mollis elit purus, a ornare lacus gravida vitae.
 4710            // Praesent semper egestas tellus id dignissim.ˇ»
 4711                    do_something();
 4712                } else {
 4713                    //
 4714                }
 4715            }
 4716        "},
 4717        indoc! {"
 4718            fn foo() {
 4719                if true {
 4720            «        // Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus
 4721                    // mollis elit purus, a ornare lacus gravida vitae. Praesent semper
 4722                    // egestas tellus id dignissim.ˇ»
 4723                    do_something();
 4724                } else {
 4725                    //
 4726                }
 4727            }
 4728        "},
 4729        language_with_doc_comments.clone(),
 4730        &mut cx,
 4731    );
 4732
 4733    assert_rewrap(
 4734        indoc! {"
 4735            fn foo() {
 4736                if true {
 4737            «ˇ        // Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus mollis elit purus, a ornare lacus gravida vitae.
 4738            // Praesent semper egestas tellus id dignissim.»
 4739                    do_something();
 4740                } else {
 4741                    //
 4742                }
 4743
 4744            }
 4745        "},
 4746        indoc! {"
 4747            fn foo() {
 4748                if true {
 4749            «ˇ        // Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus
 4750                    // mollis elit purus, a ornare lacus gravida vitae. Praesent semper
 4751                    // egestas tellus id dignissim.»
 4752                    do_something();
 4753                } else {
 4754                    //
 4755                }
 4756
 4757            }
 4758        "},
 4759        language_with_doc_comments.clone(),
 4760        &mut cx,
 4761    );
 4762
 4763    #[track_caller]
 4764    fn assert_rewrap(
 4765        unwrapped_text: &str,
 4766        wrapped_text: &str,
 4767        language: Arc<Language>,
 4768        cx: &mut EditorTestContext,
 4769    ) {
 4770        cx.update_buffer(|buffer, cx| buffer.set_language(Some(language), cx));
 4771        cx.set_state(unwrapped_text);
 4772        cx.update_editor(|e, window, cx| e.rewrap(&Rewrap, window, cx));
 4773        cx.assert_editor_state(wrapped_text);
 4774    }
 4775}
 4776
 4777#[gpui::test]
 4778async fn test_hard_wrap(cx: &mut TestAppContext) {
 4779    init_test(cx, |_| {});
 4780    let mut cx = EditorTestContext::new(cx).await;
 4781
 4782    cx.update_buffer(|buffer, cx| buffer.set_language(Some(git_commit_lang()), cx));
 4783    cx.update_editor(|editor, _, cx| {
 4784        editor.set_hard_wrap(Some(14), cx);
 4785    });
 4786
 4787    cx.set_state(indoc!(
 4788        "
 4789        one two three ˇ
 4790        "
 4791    ));
 4792    cx.simulate_input("four");
 4793    cx.run_until_parked();
 4794
 4795    cx.assert_editor_state(indoc!(
 4796        "
 4797        one two three
 4798        fourˇ
 4799        "
 4800    ));
 4801
 4802    cx.update_editor(|editor, window, cx| {
 4803        editor.newline(&Default::default(), window, cx);
 4804    });
 4805    cx.run_until_parked();
 4806    cx.assert_editor_state(indoc!(
 4807        "
 4808        one two three
 4809        four
 4810        ˇ
 4811        "
 4812    ));
 4813
 4814    cx.simulate_input("five");
 4815    cx.run_until_parked();
 4816    cx.assert_editor_state(indoc!(
 4817        "
 4818        one two three
 4819        four
 4820        fiveˇ
 4821        "
 4822    ));
 4823
 4824    cx.update_editor(|editor, window, cx| {
 4825        editor.newline(&Default::default(), window, cx);
 4826    });
 4827    cx.run_until_parked();
 4828    cx.simulate_input("# ");
 4829    cx.run_until_parked();
 4830    cx.assert_editor_state(indoc!(
 4831        "
 4832        one two three
 4833        four
 4834        five
 4835        # ˇ
 4836        "
 4837    ));
 4838
 4839    cx.update_editor(|editor, window, cx| {
 4840        editor.newline(&Default::default(), window, cx);
 4841    });
 4842    cx.run_until_parked();
 4843    cx.assert_editor_state(indoc!(
 4844        "
 4845        one two three
 4846        four
 4847        five
 4848        #\x20
 4849 4850        "
 4851    ));
 4852
 4853    cx.simulate_input(" 6");
 4854    cx.run_until_parked();
 4855    cx.assert_editor_state(indoc!(
 4856        "
 4857        one two three
 4858        four
 4859        five
 4860        #
 4861        # 6ˇ
 4862        "
 4863    ));
 4864}
 4865
 4866#[gpui::test]
 4867async fn test_clipboard(cx: &mut TestAppContext) {
 4868    init_test(cx, |_| {});
 4869
 4870    let mut cx = EditorTestContext::new(cx).await;
 4871
 4872    cx.set_state("«one✅ ˇ»two «three ˇ»four «five ˇ»six ");
 4873    cx.update_editor(|e, window, cx| e.cut(&Cut, window, cx));
 4874    cx.assert_editor_state("ˇtwo ˇfour ˇsix ");
 4875
 4876    // Paste with three cursors. Each cursor pastes one slice of the clipboard text.
 4877    cx.set_state("two ˇfour ˇsix ˇ");
 4878    cx.update_editor(|e, window, cx| e.paste(&Paste, window, cx));
 4879    cx.assert_editor_state("two one✅ ˇfour three ˇsix five ˇ");
 4880
 4881    // Paste again but with only two cursors. Since the number of cursors doesn't
 4882    // match the number of slices in the clipboard, the entire clipboard text
 4883    // is pasted at each cursor.
 4884    cx.set_state("ˇtwo one✅ four three six five ˇ");
 4885    cx.update_editor(|e, window, cx| {
 4886        e.handle_input("( ", window, cx);
 4887        e.paste(&Paste, window, cx);
 4888        e.handle_input(") ", window, cx);
 4889    });
 4890    cx.assert_editor_state(
 4891        &([
 4892            "( one✅ ",
 4893            "three ",
 4894            "five ) ˇtwo one✅ four three six five ( one✅ ",
 4895            "three ",
 4896            "five ) ˇ",
 4897        ]
 4898        .join("\n")),
 4899    );
 4900
 4901    // Cut with three selections, one of which is full-line.
 4902    cx.set_state(indoc! {"
 4903        1«2ˇ»3
 4904        4ˇ567
 4905        «8ˇ»9"});
 4906    cx.update_editor(|e, window, cx| e.cut(&Cut, window, cx));
 4907    cx.assert_editor_state(indoc! {"
 4908        1ˇ3
 4909        ˇ9"});
 4910
 4911    // Paste with three selections, noticing how the copied selection that was full-line
 4912    // gets inserted before the second cursor.
 4913    cx.set_state(indoc! {"
 4914        1ˇ3
 4915 4916        «oˇ»ne"});
 4917    cx.update_editor(|e, window, cx| e.paste(&Paste, window, cx));
 4918    cx.assert_editor_state(indoc! {"
 4919        12ˇ3
 4920        4567
 4921 4922        8ˇne"});
 4923
 4924    // Copy with a single cursor only, which writes the whole line into the clipboard.
 4925    cx.set_state(indoc! {"
 4926        The quick brown
 4927        fox juˇmps over
 4928        the lazy dog"});
 4929    cx.update_editor(|e, window, cx| e.copy(&Copy, window, cx));
 4930    assert_eq!(
 4931        cx.read_from_clipboard()
 4932            .and_then(|item| item.text().as_deref().map(str::to_string)),
 4933        Some("fox jumps over\n".to_string())
 4934    );
 4935
 4936    // Paste with three selections, noticing how the copied full-line selection is inserted
 4937    // before the empty selections but replaces the selection that is non-empty.
 4938    cx.set_state(indoc! {"
 4939        Tˇhe quick brown
 4940        «foˇ»x jumps over
 4941        tˇhe lazy dog"});
 4942    cx.update_editor(|e, window, cx| e.paste(&Paste, window, cx));
 4943    cx.assert_editor_state(indoc! {"
 4944        fox jumps over
 4945        Tˇhe quick brown
 4946        fox jumps over
 4947        ˇx jumps over
 4948        fox jumps over
 4949        tˇhe lazy dog"});
 4950}
 4951
 4952#[gpui::test]
 4953async fn test_copy_trim(cx: &mut TestAppContext) {
 4954    init_test(cx, |_| {});
 4955
 4956    let mut cx = EditorTestContext::new(cx).await;
 4957    cx.set_state(
 4958        r#"            «for selection in selections.iter() {
 4959            let mut start = selection.start;
 4960            let mut end = selection.end;
 4961            let is_entire_line = selection.is_empty();
 4962            if is_entire_line {
 4963                start = Point::new(start.row, 0);ˇ»
 4964                end = cmp::min(max_point, Point::new(end.row + 1, 0));
 4965            }
 4966        "#,
 4967    );
 4968    cx.update_editor(|e, window, cx| e.copy(&Copy, window, cx));
 4969    assert_eq!(
 4970        cx.read_from_clipboard()
 4971            .and_then(|item| item.text().as_deref().map(str::to_string)),
 4972        Some(
 4973            "for selection in selections.iter() {
 4974            let mut start = selection.start;
 4975            let mut end = selection.end;
 4976            let is_entire_line = selection.is_empty();
 4977            if is_entire_line {
 4978                start = Point::new(start.row, 0);"
 4979                .to_string()
 4980        ),
 4981        "Regular copying preserves all indentation selected",
 4982    );
 4983    cx.update_editor(|e, window, cx| e.copy_and_trim(&CopyAndTrim, window, cx));
 4984    assert_eq!(
 4985        cx.read_from_clipboard()
 4986            .and_then(|item| item.text().as_deref().map(str::to_string)),
 4987        Some(
 4988            "for selection in selections.iter() {
 4989let mut start = selection.start;
 4990let mut end = selection.end;
 4991let is_entire_line = selection.is_empty();
 4992if is_entire_line {
 4993    start = Point::new(start.row, 0);"
 4994                .to_string()
 4995        ),
 4996        "Copying with stripping should strip all leading whitespaces"
 4997    );
 4998
 4999    cx.set_state(
 5000        r#"       «     for selection in selections.iter() {
 5001            let mut start = selection.start;
 5002            let mut end = selection.end;
 5003            let is_entire_line = selection.is_empty();
 5004            if is_entire_line {
 5005                start = Point::new(start.row, 0);ˇ»
 5006                end = cmp::min(max_point, Point::new(end.row + 1, 0));
 5007            }
 5008        "#,
 5009    );
 5010    cx.update_editor(|e, window, cx| e.copy(&Copy, window, cx));
 5011    assert_eq!(
 5012        cx.read_from_clipboard()
 5013            .and_then(|item| item.text().as_deref().map(str::to_string)),
 5014        Some(
 5015            "     for selection in selections.iter() {
 5016            let mut start = selection.start;
 5017            let mut end = selection.end;
 5018            let is_entire_line = selection.is_empty();
 5019            if is_entire_line {
 5020                start = Point::new(start.row, 0);"
 5021                .to_string()
 5022        ),
 5023        "Regular copying preserves all indentation selected",
 5024    );
 5025    cx.update_editor(|e, window, cx| e.copy_and_trim(&CopyAndTrim, window, cx));
 5026    assert_eq!(
 5027        cx.read_from_clipboard()
 5028            .and_then(|item| item.text().as_deref().map(str::to_string)),
 5029        Some(
 5030            "for selection in selections.iter() {
 5031let mut start = selection.start;
 5032let mut end = selection.end;
 5033let is_entire_line = selection.is_empty();
 5034if is_entire_line {
 5035    start = Point::new(start.row, 0);"
 5036                .to_string()
 5037        ),
 5038        "Copying with stripping should strip all leading whitespaces, even if some of it was selected"
 5039    );
 5040
 5041    cx.set_state(
 5042        r#"       «ˇ     for selection in selections.iter() {
 5043            let mut start = selection.start;
 5044            let mut end = selection.end;
 5045            let is_entire_line = selection.is_empty();
 5046            if is_entire_line {
 5047                start = Point::new(start.row, 0);»
 5048                end = cmp::min(max_point, Point::new(end.row + 1, 0));
 5049            }
 5050        "#,
 5051    );
 5052    cx.update_editor(|e, window, cx| e.copy(&Copy, window, cx));
 5053    assert_eq!(
 5054        cx.read_from_clipboard()
 5055            .and_then(|item| item.text().as_deref().map(str::to_string)),
 5056        Some(
 5057            "     for selection in selections.iter() {
 5058            let mut start = selection.start;
 5059            let mut end = selection.end;
 5060            let is_entire_line = selection.is_empty();
 5061            if is_entire_line {
 5062                start = Point::new(start.row, 0);"
 5063                .to_string()
 5064        ),
 5065        "Regular copying for reverse selection works the same",
 5066    );
 5067    cx.update_editor(|e, window, cx| e.copy_and_trim(&CopyAndTrim, window, cx));
 5068    assert_eq!(
 5069        cx.read_from_clipboard()
 5070            .and_then(|item| item.text().as_deref().map(str::to_string)),
 5071        Some(
 5072            "for selection in selections.iter() {
 5073let mut start = selection.start;
 5074let mut end = selection.end;
 5075let is_entire_line = selection.is_empty();
 5076if is_entire_line {
 5077    start = Point::new(start.row, 0);"
 5078                .to_string()
 5079        ),
 5080        "Copying with stripping for reverse selection works the same"
 5081    );
 5082
 5083    cx.set_state(
 5084        r#"            for selection «in selections.iter() {
 5085            let mut start = selection.start;
 5086            let mut end = selection.end;
 5087            let is_entire_line = selection.is_empty();
 5088            if is_entire_line {
 5089                start = Point::new(start.row, 0);ˇ»
 5090                end = cmp::min(max_point, Point::new(end.row + 1, 0));
 5091            }
 5092        "#,
 5093    );
 5094    cx.update_editor(|e, window, cx| e.copy(&Copy, window, cx));
 5095    assert_eq!(
 5096        cx.read_from_clipboard()
 5097            .and_then(|item| item.text().as_deref().map(str::to_string)),
 5098        Some(
 5099            "in selections.iter() {
 5100            let mut start = selection.start;
 5101            let mut end = selection.end;
 5102            let is_entire_line = selection.is_empty();
 5103            if is_entire_line {
 5104                start = Point::new(start.row, 0);"
 5105                .to_string()
 5106        ),
 5107        "When selecting past the indent, the copying works as usual",
 5108    );
 5109    cx.update_editor(|e, window, cx| e.copy_and_trim(&CopyAndTrim, window, cx));
 5110    assert_eq!(
 5111        cx.read_from_clipboard()
 5112            .and_then(|item| item.text().as_deref().map(str::to_string)),
 5113        Some(
 5114            "in selections.iter() {
 5115            let mut start = selection.start;
 5116            let mut end = selection.end;
 5117            let is_entire_line = selection.is_empty();
 5118            if is_entire_line {
 5119                start = Point::new(start.row, 0);"
 5120                .to_string()
 5121        ),
 5122        "When selecting past the indent, nothing is trimmed"
 5123    );
 5124
 5125    cx.set_state(
 5126        r#"            «for selection in selections.iter() {
 5127            let mut start = selection.start;
 5128
 5129            let mut end = selection.end;
 5130            let is_entire_line = selection.is_empty();
 5131            if is_entire_line {
 5132                start = Point::new(start.row, 0);
 5133ˇ»                end = cmp::min(max_point, Point::new(end.row + 1, 0));
 5134            }
 5135        "#,
 5136    );
 5137    cx.update_editor(|e, window, cx| e.copy_and_trim(&CopyAndTrim, window, cx));
 5138    assert_eq!(
 5139        cx.read_from_clipboard()
 5140            .and_then(|item| item.text().as_deref().map(str::to_string)),
 5141        Some(
 5142            "for selection in selections.iter() {
 5143let mut start = selection.start;
 5144
 5145let mut end = selection.end;
 5146let is_entire_line = selection.is_empty();
 5147if is_entire_line {
 5148    start = Point::new(start.row, 0);
 5149"
 5150            .to_string()
 5151        ),
 5152        "Copying with stripping should ignore empty lines"
 5153    );
 5154}
 5155
 5156#[gpui::test]
 5157async fn test_paste_multiline(cx: &mut TestAppContext) {
 5158    init_test(cx, |_| {});
 5159
 5160    let mut cx = EditorTestContext::new(cx).await;
 5161    cx.update_buffer(|buffer, cx| buffer.set_language(Some(rust_lang()), cx));
 5162
 5163    // Cut an indented block, without the leading whitespace.
 5164    cx.set_state(indoc! {"
 5165        const a: B = (
 5166            c(),
 5167            «d(
 5168                e,
 5169                f
 5170            )ˇ»
 5171        );
 5172    "});
 5173    cx.update_editor(|e, window, cx| e.cut(&Cut, window, cx));
 5174    cx.assert_editor_state(indoc! {"
 5175        const a: B = (
 5176            c(),
 5177            ˇ
 5178        );
 5179    "});
 5180
 5181    // Paste it at the same position.
 5182    cx.update_editor(|e, window, cx| e.paste(&Paste, window, cx));
 5183    cx.assert_editor_state(indoc! {"
 5184        const a: B = (
 5185            c(),
 5186            d(
 5187                e,
 5188                f
 5189 5190        );
 5191    "});
 5192
 5193    // Paste it at a line with a lower indent level.
 5194    cx.set_state(indoc! {"
 5195        ˇ
 5196        const a: B = (
 5197            c(),
 5198        );
 5199    "});
 5200    cx.update_editor(|e, window, cx| e.paste(&Paste, window, cx));
 5201    cx.assert_editor_state(indoc! {"
 5202        d(
 5203            e,
 5204            f
 5205 5206        const a: B = (
 5207            c(),
 5208        );
 5209    "});
 5210
 5211    // Cut an indented block, with the leading whitespace.
 5212    cx.set_state(indoc! {"
 5213        const a: B = (
 5214            c(),
 5215        «    d(
 5216                e,
 5217                f
 5218            )
 5219        ˇ»);
 5220    "});
 5221    cx.update_editor(|e, window, cx| e.cut(&Cut, window, cx));
 5222    cx.assert_editor_state(indoc! {"
 5223        const a: B = (
 5224            c(),
 5225        ˇ);
 5226    "});
 5227
 5228    // Paste it at the same position.
 5229    cx.update_editor(|e, window, cx| e.paste(&Paste, window, cx));
 5230    cx.assert_editor_state(indoc! {"
 5231        const a: B = (
 5232            c(),
 5233            d(
 5234                e,
 5235                f
 5236            )
 5237        ˇ);
 5238    "});
 5239
 5240    // Paste it at a line with a higher indent level.
 5241    cx.set_state(indoc! {"
 5242        const a: B = (
 5243            c(),
 5244            d(
 5245                e,
 5246 5247            )
 5248        );
 5249    "});
 5250    cx.update_editor(|e, window, cx| e.paste(&Paste, window, cx));
 5251    cx.assert_editor_state(indoc! {"
 5252        const a: B = (
 5253            c(),
 5254            d(
 5255                e,
 5256                f    d(
 5257                    e,
 5258                    f
 5259                )
 5260        ˇ
 5261            )
 5262        );
 5263    "});
 5264
 5265    // Copy an indented block, starting mid-line
 5266    cx.set_state(indoc! {"
 5267        const a: B = (
 5268            c(),
 5269            somethin«g(
 5270                e,
 5271                f
 5272            )ˇ»
 5273        );
 5274    "});
 5275    cx.update_editor(|e, window, cx| e.copy(&Copy, window, cx));
 5276
 5277    // Paste it on a line with a lower indent level
 5278    cx.update_editor(|e, window, cx| e.move_to_end(&Default::default(), window, cx));
 5279    cx.update_editor(|e, window, cx| e.paste(&Paste, window, cx));
 5280    cx.assert_editor_state(indoc! {"
 5281        const a: B = (
 5282            c(),
 5283            something(
 5284                e,
 5285                f
 5286            )
 5287        );
 5288        g(
 5289            e,
 5290            f
 5291"});
 5292}
 5293
 5294#[gpui::test]
 5295async fn test_paste_content_from_other_app(cx: &mut TestAppContext) {
 5296    init_test(cx, |_| {});
 5297
 5298    cx.write_to_clipboard(ClipboardItem::new_string(
 5299        "    d(\n        e\n    );\n".into(),
 5300    ));
 5301
 5302    let mut cx = EditorTestContext::new(cx).await;
 5303    cx.update_buffer(|buffer, cx| buffer.set_language(Some(rust_lang()), cx));
 5304
 5305    cx.set_state(indoc! {"
 5306        fn a() {
 5307            b();
 5308            if c() {
 5309                ˇ
 5310            }
 5311        }
 5312    "});
 5313
 5314    cx.update_editor(|e, window, cx| e.paste(&Paste, window, cx));
 5315    cx.assert_editor_state(indoc! {"
 5316        fn a() {
 5317            b();
 5318            if c() {
 5319                d(
 5320                    e
 5321                );
 5322        ˇ
 5323            }
 5324        }
 5325    "});
 5326
 5327    cx.set_state(indoc! {"
 5328        fn a() {
 5329            b();
 5330            ˇ
 5331        }
 5332    "});
 5333
 5334    cx.update_editor(|e, window, cx| e.paste(&Paste, window, cx));
 5335    cx.assert_editor_state(indoc! {"
 5336        fn a() {
 5337            b();
 5338            d(
 5339                e
 5340            );
 5341        ˇ
 5342        }
 5343    "});
 5344}
 5345
 5346#[gpui::test]
 5347fn test_select_all(cx: &mut TestAppContext) {
 5348    init_test(cx, |_| {});
 5349
 5350    let editor = cx.add_window(|window, cx| {
 5351        let buffer = MultiBuffer::build_simple("abc\nde\nfgh", cx);
 5352        build_editor(buffer, window, cx)
 5353    });
 5354    _ = editor.update(cx, |editor, window, cx| {
 5355        editor.select_all(&SelectAll, window, cx);
 5356        assert_eq!(
 5357            editor.selections.display_ranges(cx),
 5358            &[DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(2), 3)]
 5359        );
 5360    });
 5361}
 5362
 5363#[gpui::test]
 5364fn test_select_line(cx: &mut TestAppContext) {
 5365    init_test(cx, |_| {});
 5366
 5367    let editor = cx.add_window(|window, cx| {
 5368        let buffer = MultiBuffer::build_simple(&sample_text(6, 5, 'a'), cx);
 5369        build_editor(buffer, window, cx)
 5370    });
 5371    _ = editor.update(cx, |editor, window, cx| {
 5372        editor.change_selections(None, window, cx, |s| {
 5373            s.select_display_ranges([
 5374                DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(0), 1),
 5375                DisplayPoint::new(DisplayRow(0), 2)..DisplayPoint::new(DisplayRow(0), 2),
 5376                DisplayPoint::new(DisplayRow(1), 0)..DisplayPoint::new(DisplayRow(1), 0),
 5377                DisplayPoint::new(DisplayRow(4), 2)..DisplayPoint::new(DisplayRow(4), 2),
 5378            ])
 5379        });
 5380        editor.select_line(&SelectLine, window, cx);
 5381        assert_eq!(
 5382            editor.selections.display_ranges(cx),
 5383            vec![
 5384                DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(2), 0),
 5385                DisplayPoint::new(DisplayRow(4), 0)..DisplayPoint::new(DisplayRow(5), 0),
 5386            ]
 5387        );
 5388    });
 5389
 5390    _ = editor.update(cx, |editor, window, cx| {
 5391        editor.select_line(&SelectLine, window, cx);
 5392        assert_eq!(
 5393            editor.selections.display_ranges(cx),
 5394            vec![
 5395                DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(3), 0),
 5396                DisplayPoint::new(DisplayRow(4), 0)..DisplayPoint::new(DisplayRow(5), 5),
 5397            ]
 5398        );
 5399    });
 5400
 5401    _ = editor.update(cx, |editor, window, cx| {
 5402        editor.select_line(&SelectLine, window, cx);
 5403        assert_eq!(
 5404            editor.selections.display_ranges(cx),
 5405            vec![DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(5), 5)]
 5406        );
 5407    });
 5408}
 5409
 5410#[gpui::test]
 5411async fn test_split_selection_into_lines(cx: &mut TestAppContext) {
 5412    init_test(cx, |_| {});
 5413    let mut cx = EditorTestContext::new(cx).await;
 5414
 5415    #[track_caller]
 5416    fn test(cx: &mut EditorTestContext, initial_state: &'static str, expected_state: &'static str) {
 5417        cx.set_state(initial_state);
 5418        cx.update_editor(|e, window, cx| {
 5419            e.split_selection_into_lines(&SplitSelectionIntoLines, window, cx)
 5420        });
 5421        cx.assert_editor_state(expected_state);
 5422    }
 5423
 5424    // Selection starts and ends at the middle of lines, left-to-right
 5425    test(
 5426        &mut cx,
 5427        "aa\nb«ˇb\ncc\ndd\ne»e\nff",
 5428        "aa\nbbˇ\nccˇ\nddˇ\neˇe\nff",
 5429    );
 5430    // Same thing, right-to-left
 5431    test(
 5432        &mut cx,
 5433        "aa\nb«b\ncc\ndd\neˇ»e\nff",
 5434        "aa\nbbˇ\nccˇ\nddˇ\neˇe\nff",
 5435    );
 5436
 5437    // Whole buffer, left-to-right, last line *doesn't* end with newline
 5438    test(
 5439        &mut cx,
 5440        "«ˇaa\nbb\ncc\ndd\nee\nff»",
 5441        "aaˇ\nbbˇ\nccˇ\nddˇ\neeˇ\nffˇ",
 5442    );
 5443    // Same thing, right-to-left
 5444    test(
 5445        &mut cx,
 5446        "«aa\nbb\ncc\ndd\nee\nffˇ»",
 5447        "aaˇ\nbbˇ\nccˇ\nddˇ\neeˇ\nffˇ",
 5448    );
 5449
 5450    // Whole buffer, left-to-right, last line ends with newline
 5451    test(
 5452        &mut cx,
 5453        "«ˇaa\nbb\ncc\ndd\nee\nff\n»",
 5454        "aaˇ\nbbˇ\nccˇ\nddˇ\neeˇ\nffˇ\n",
 5455    );
 5456    // Same thing, right-to-left
 5457    test(
 5458        &mut cx,
 5459        "«aa\nbb\ncc\ndd\nee\nff\nˇ»",
 5460        "aaˇ\nbbˇ\nccˇ\nddˇ\neeˇ\nffˇ\n",
 5461    );
 5462
 5463    // Starts at the end of a line, ends at the start of another
 5464    test(
 5465        &mut cx,
 5466        "aa\nbb«ˇ\ncc\ndd\nee\n»ff\n",
 5467        "aa\nbbˇ\nccˇ\nddˇ\neeˇ\nff\n",
 5468    );
 5469}
 5470
 5471#[gpui::test]
 5472async fn test_split_selection_into_lines_interacting_with_creases(cx: &mut TestAppContext) {
 5473    init_test(cx, |_| {});
 5474
 5475    let editor = cx.add_window(|window, cx| {
 5476        let buffer = MultiBuffer::build_simple(&sample_text(9, 5, 'a'), cx);
 5477        build_editor(buffer, window, cx)
 5478    });
 5479
 5480    // setup
 5481    _ = editor.update(cx, |editor, window, cx| {
 5482        editor.fold_creases(
 5483            vec![
 5484                Crease::simple(Point::new(0, 2)..Point::new(1, 2), FoldPlaceholder::test()),
 5485                Crease::simple(Point::new(2, 3)..Point::new(4, 1), FoldPlaceholder::test()),
 5486                Crease::simple(Point::new(7, 0)..Point::new(8, 4), FoldPlaceholder::test()),
 5487            ],
 5488            true,
 5489            window,
 5490            cx,
 5491        );
 5492        assert_eq!(
 5493            editor.display_text(cx),
 5494            "aa⋯bbb\nccc⋯eeee\nfffff\nggggg\n⋯i"
 5495        );
 5496    });
 5497
 5498    _ = editor.update(cx, |editor, window, cx| {
 5499        editor.change_selections(None, window, cx, |s| {
 5500            s.select_display_ranges([
 5501                DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(0), 1),
 5502                DisplayPoint::new(DisplayRow(0), 2)..DisplayPoint::new(DisplayRow(0), 2),
 5503                DisplayPoint::new(DisplayRow(1), 0)..DisplayPoint::new(DisplayRow(1), 0),
 5504                DisplayPoint::new(DisplayRow(4), 4)..DisplayPoint::new(DisplayRow(4), 4),
 5505            ])
 5506        });
 5507        editor.split_selection_into_lines(&SplitSelectionIntoLines, window, cx);
 5508        assert_eq!(
 5509            editor.display_text(cx),
 5510            "aaaaa\nbbbbb\nccc⋯eeee\nfffff\nggggg\n⋯i"
 5511        );
 5512    });
 5513    EditorTestContext::for_editor(editor, cx)
 5514        .await
 5515        .assert_editor_state("aˇaˇaaa\nbbbbb\nˇccccc\nddddd\neeeee\nfffff\nggggg\nhhhhh\niiiiiˇ");
 5516
 5517    _ = editor.update(cx, |editor, window, cx| {
 5518        editor.change_selections(None, window, cx, |s| {
 5519            s.select_display_ranges([
 5520                DisplayPoint::new(DisplayRow(5), 0)..DisplayPoint::new(DisplayRow(0), 1)
 5521            ])
 5522        });
 5523        editor.split_selection_into_lines(&SplitSelectionIntoLines, window, cx);
 5524        assert_eq!(
 5525            editor.display_text(cx),
 5526            "aaaaa\nbbbbb\nccccc\nddddd\neeeee\nfffff\nggggg\nhhhhh\niiiii"
 5527        );
 5528        assert_eq!(
 5529            editor.selections.display_ranges(cx),
 5530            [
 5531                DisplayPoint::new(DisplayRow(0), 5)..DisplayPoint::new(DisplayRow(0), 5),
 5532                DisplayPoint::new(DisplayRow(1), 5)..DisplayPoint::new(DisplayRow(1), 5),
 5533                DisplayPoint::new(DisplayRow(2), 5)..DisplayPoint::new(DisplayRow(2), 5),
 5534                DisplayPoint::new(DisplayRow(3), 5)..DisplayPoint::new(DisplayRow(3), 5),
 5535                DisplayPoint::new(DisplayRow(4), 5)..DisplayPoint::new(DisplayRow(4), 5),
 5536                DisplayPoint::new(DisplayRow(5), 5)..DisplayPoint::new(DisplayRow(5), 5),
 5537                DisplayPoint::new(DisplayRow(6), 5)..DisplayPoint::new(DisplayRow(6), 5)
 5538            ]
 5539        );
 5540    });
 5541    EditorTestContext::for_editor(editor, cx)
 5542        .await
 5543        .assert_editor_state(
 5544            "aaaaaˇ\nbbbbbˇ\ncccccˇ\ndddddˇ\neeeeeˇ\nfffffˇ\ngggggˇ\nhhhhh\niiiii",
 5545        );
 5546}
 5547
 5548#[gpui::test]
 5549async fn test_add_selection_above_below(cx: &mut TestAppContext) {
 5550    init_test(cx, |_| {});
 5551
 5552    let mut cx = EditorTestContext::new(cx).await;
 5553
 5554    cx.set_state(indoc!(
 5555        r#"abc
 5556           defˇghi
 5557
 5558           jk
 5559           nlmo
 5560           "#
 5561    ));
 5562
 5563    cx.update_editor(|editor, window, cx| {
 5564        editor.add_selection_above(&Default::default(), window, cx);
 5565    });
 5566
 5567    cx.assert_editor_state(indoc!(
 5568        r#"abcˇ
 5569           defˇghi
 5570
 5571           jk
 5572           nlmo
 5573           "#
 5574    ));
 5575
 5576    cx.update_editor(|editor, window, cx| {
 5577        editor.add_selection_above(&Default::default(), window, cx);
 5578    });
 5579
 5580    cx.assert_editor_state(indoc!(
 5581        r#"abcˇ
 5582            defˇghi
 5583
 5584            jk
 5585            nlmo
 5586            "#
 5587    ));
 5588
 5589    cx.update_editor(|editor, window, cx| {
 5590        editor.add_selection_below(&Default::default(), window, cx);
 5591    });
 5592
 5593    cx.assert_editor_state(indoc!(
 5594        r#"abc
 5595           defˇghi
 5596
 5597           jk
 5598           nlmo
 5599           "#
 5600    ));
 5601
 5602    cx.update_editor(|editor, window, cx| {
 5603        editor.undo_selection(&Default::default(), window, cx);
 5604    });
 5605
 5606    cx.assert_editor_state(indoc!(
 5607        r#"abcˇ
 5608           defˇghi
 5609
 5610           jk
 5611           nlmo
 5612           "#
 5613    ));
 5614
 5615    cx.update_editor(|editor, window, cx| {
 5616        editor.redo_selection(&Default::default(), window, cx);
 5617    });
 5618
 5619    cx.assert_editor_state(indoc!(
 5620        r#"abc
 5621           defˇghi
 5622
 5623           jk
 5624           nlmo
 5625           "#
 5626    ));
 5627
 5628    cx.update_editor(|editor, window, cx| {
 5629        editor.add_selection_below(&Default::default(), window, cx);
 5630    });
 5631
 5632    cx.assert_editor_state(indoc!(
 5633        r#"abc
 5634           defˇghi
 5635
 5636           jk
 5637           nlmˇo
 5638           "#
 5639    ));
 5640
 5641    cx.update_editor(|editor, window, cx| {
 5642        editor.add_selection_below(&Default::default(), window, cx);
 5643    });
 5644
 5645    cx.assert_editor_state(indoc!(
 5646        r#"abc
 5647           defˇghi
 5648
 5649           jk
 5650           nlmˇo
 5651           "#
 5652    ));
 5653
 5654    // change selections
 5655    cx.set_state(indoc!(
 5656        r#"abc
 5657           def«ˇg»hi
 5658
 5659           jk
 5660           nlmo
 5661           "#
 5662    ));
 5663
 5664    cx.update_editor(|editor, window, cx| {
 5665        editor.add_selection_below(&Default::default(), window, cx);
 5666    });
 5667
 5668    cx.assert_editor_state(indoc!(
 5669        r#"abc
 5670           def«ˇg»hi
 5671
 5672           jk
 5673           nlm«ˇo»
 5674           "#
 5675    ));
 5676
 5677    cx.update_editor(|editor, window, cx| {
 5678        editor.add_selection_below(&Default::default(), window, cx);
 5679    });
 5680
 5681    cx.assert_editor_state(indoc!(
 5682        r#"abc
 5683           def«ˇg»hi
 5684
 5685           jk
 5686           nlm«ˇo»
 5687           "#
 5688    ));
 5689
 5690    cx.update_editor(|editor, window, cx| {
 5691        editor.add_selection_above(&Default::default(), window, cx);
 5692    });
 5693
 5694    cx.assert_editor_state(indoc!(
 5695        r#"abc
 5696           def«ˇg»hi
 5697
 5698           jk
 5699           nlmo
 5700           "#
 5701    ));
 5702
 5703    cx.update_editor(|editor, window, cx| {
 5704        editor.add_selection_above(&Default::default(), window, cx);
 5705    });
 5706
 5707    cx.assert_editor_state(indoc!(
 5708        r#"abc
 5709           def«ˇg»hi
 5710
 5711           jk
 5712           nlmo
 5713           "#
 5714    ));
 5715
 5716    // Change selections again
 5717    cx.set_state(indoc!(
 5718        r#"a«bc
 5719           defgˇ»hi
 5720
 5721           jk
 5722           nlmo
 5723           "#
 5724    ));
 5725
 5726    cx.update_editor(|editor, window, cx| {
 5727        editor.add_selection_below(&Default::default(), window, cx);
 5728    });
 5729
 5730    cx.assert_editor_state(indoc!(
 5731        r#"a«bcˇ»
 5732           d«efgˇ»hi
 5733
 5734           j«kˇ»
 5735           nlmo
 5736           "#
 5737    ));
 5738
 5739    cx.update_editor(|editor, window, cx| {
 5740        editor.add_selection_below(&Default::default(), window, cx);
 5741    });
 5742    cx.assert_editor_state(indoc!(
 5743        r#"a«bcˇ»
 5744           d«efgˇ»hi
 5745
 5746           j«kˇ»
 5747           n«lmoˇ»
 5748           "#
 5749    ));
 5750    cx.update_editor(|editor, window, cx| {
 5751        editor.add_selection_above(&Default::default(), window, cx);
 5752    });
 5753
 5754    cx.assert_editor_state(indoc!(
 5755        r#"a«bcˇ»
 5756           d«efgˇ»hi
 5757
 5758           j«kˇ»
 5759           nlmo
 5760           "#
 5761    ));
 5762
 5763    // Change selections again
 5764    cx.set_state(indoc!(
 5765        r#"abc
 5766           d«ˇefghi
 5767
 5768           jk
 5769           nlm»o
 5770           "#
 5771    ));
 5772
 5773    cx.update_editor(|editor, window, cx| {
 5774        editor.add_selection_above(&Default::default(), window, cx);
 5775    });
 5776
 5777    cx.assert_editor_state(indoc!(
 5778        r#"a«ˇbc»
 5779           d«ˇef»ghi
 5780
 5781           j«ˇk»
 5782           n«ˇlm»o
 5783           "#
 5784    ));
 5785
 5786    cx.update_editor(|editor, window, cx| {
 5787        editor.add_selection_below(&Default::default(), window, cx);
 5788    });
 5789
 5790    cx.assert_editor_state(indoc!(
 5791        r#"abc
 5792           d«ˇef»ghi
 5793
 5794           j«ˇk»
 5795           n«ˇlm»o
 5796           "#
 5797    ));
 5798}
 5799
 5800#[gpui::test]
 5801async fn test_select_next(cx: &mut TestAppContext) {
 5802    init_test(cx, |_| {});
 5803
 5804    let mut cx = EditorTestContext::new(cx).await;
 5805    cx.set_state("abc\nˇabc abc\ndefabc\nabc");
 5806
 5807    cx.update_editor(|e, window, cx| e.select_next(&SelectNext::default(), window, cx))
 5808        .unwrap();
 5809    cx.assert_editor_state("abc\n«abcˇ» abc\ndefabc\nabc");
 5810
 5811    cx.update_editor(|e, window, cx| e.select_next(&SelectNext::default(), window, cx))
 5812        .unwrap();
 5813    cx.assert_editor_state("abc\n«abcˇ» «abcˇ»\ndefabc\nabc");
 5814
 5815    cx.update_editor(|editor, window, cx| editor.undo_selection(&UndoSelection, window, cx));
 5816    cx.assert_editor_state("abc\n«abcˇ» abc\ndefabc\nabc");
 5817
 5818    cx.update_editor(|editor, window, cx| editor.redo_selection(&RedoSelection, window, cx));
 5819    cx.assert_editor_state("abc\n«abcˇ» «abcˇ»\ndefabc\nabc");
 5820
 5821    cx.update_editor(|e, window, cx| e.select_next(&SelectNext::default(), window, cx))
 5822        .unwrap();
 5823    cx.assert_editor_state("abc\n«abcˇ» «abcˇ»\ndefabc\n«abcˇ»");
 5824
 5825    cx.update_editor(|e, window, cx| e.select_next(&SelectNext::default(), window, cx))
 5826        .unwrap();
 5827    cx.assert_editor_state("«abcˇ»\n«abcˇ» «abcˇ»\ndefabc\n«abcˇ»");
 5828}
 5829
 5830#[gpui::test]
 5831async fn test_select_all_matches(cx: &mut TestAppContext) {
 5832    init_test(cx, |_| {});
 5833
 5834    let mut cx = EditorTestContext::new(cx).await;
 5835
 5836    // Test caret-only selections
 5837    cx.set_state("abc\nˇabc abc\ndefabc\nabc");
 5838    cx.update_editor(|e, window, cx| e.select_all_matches(&SelectAllMatches, window, cx))
 5839        .unwrap();
 5840    cx.assert_editor_state("«abcˇ»\n«abcˇ» «abcˇ»\ndefabc\n«abcˇ»");
 5841
 5842    // Test left-to-right selections
 5843    cx.set_state("abc\n«abcˇ»\nabc");
 5844    cx.update_editor(|e, window, cx| e.select_all_matches(&SelectAllMatches, window, cx))
 5845        .unwrap();
 5846    cx.assert_editor_state("«abcˇ»\n«abcˇ»\n«abcˇ»");
 5847
 5848    // Test right-to-left selections
 5849    cx.set_state("abc\n«ˇabc»\nabc");
 5850    cx.update_editor(|e, window, cx| e.select_all_matches(&SelectAllMatches, window, cx))
 5851        .unwrap();
 5852    cx.assert_editor_state("«ˇabc»\n«ˇabc»\n«ˇabc»");
 5853
 5854    // Test selecting whitespace with caret selection
 5855    cx.set_state("abc\nˇ   abc\nabc");
 5856    cx.update_editor(|e, window, cx| e.select_all_matches(&SelectAllMatches, window, cx))
 5857        .unwrap();
 5858    cx.assert_editor_state("abc\n«   ˇ»abc\nabc");
 5859
 5860    // Test selecting whitespace with left-to-right selection
 5861    cx.set_state("abc\n«ˇ  »abc\nabc");
 5862    cx.update_editor(|e, window, cx| e.select_all_matches(&SelectAllMatches, window, cx))
 5863        .unwrap();
 5864    cx.assert_editor_state("abc\n«ˇ  »abc\nabc");
 5865
 5866    // Test no matches with right-to-left selection
 5867    cx.set_state("abc\n«  ˇ»abc\nabc");
 5868    cx.update_editor(|e, window, cx| e.select_all_matches(&SelectAllMatches, window, cx))
 5869        .unwrap();
 5870    cx.assert_editor_state("abc\n«  ˇ»abc\nabc");
 5871}
 5872
 5873#[gpui::test]
 5874async fn test_select_all_matches_does_not_scroll(cx: &mut TestAppContext) {
 5875    init_test(cx, |_| {});
 5876
 5877    let mut cx = EditorTestContext::new(cx).await;
 5878
 5879    let large_body_1 = "\nd".repeat(200);
 5880    let large_body_2 = "\ne".repeat(200);
 5881
 5882    cx.set_state(&format!(
 5883        "abc\nabc{large_body_1} «ˇa»bc{large_body_2}\nefabc\nabc"
 5884    ));
 5885    let initial_scroll_position = cx.update_editor(|editor, _, cx| {
 5886        let scroll_position = editor.scroll_position(cx);
 5887        assert!(scroll_position.y > 0.0, "Initial selection is between two large bodies and should have the editor scrolled to it");
 5888        scroll_position
 5889    });
 5890
 5891    cx.update_editor(|e, window, cx| e.select_all_matches(&SelectAllMatches, window, cx))
 5892        .unwrap();
 5893    cx.assert_editor_state(&format!(
 5894        "«ˇa»bc\n«ˇa»bc{large_body_1} «ˇa»bc{large_body_2}\nef«ˇa»bc\n«ˇa»bc"
 5895    ));
 5896    let scroll_position_after_selection =
 5897        cx.update_editor(|editor, _, cx| editor.scroll_position(cx));
 5898    assert_eq!(
 5899        initial_scroll_position, scroll_position_after_selection,
 5900        "Scroll position should not change after selecting all matches"
 5901    );
 5902}
 5903
 5904#[gpui::test]
 5905async fn test_undo_format_scrolls_to_last_edit_pos(cx: &mut TestAppContext) {
 5906    init_test(cx, |_| {});
 5907
 5908    let mut cx = EditorLspTestContext::new_rust(
 5909        lsp::ServerCapabilities {
 5910            document_formatting_provider: Some(lsp::OneOf::Left(true)),
 5911            ..Default::default()
 5912        },
 5913        cx,
 5914    )
 5915    .await;
 5916
 5917    cx.set_state(indoc! {"
 5918        line 1
 5919        line 2
 5920        linˇe 3
 5921        line 4
 5922        line 5
 5923    "});
 5924
 5925    // Make an edit
 5926    cx.update_editor(|editor, window, cx| {
 5927        editor.handle_input("X", window, cx);
 5928    });
 5929
 5930    // Move cursor to a different position
 5931    cx.update_editor(|editor, window, cx| {
 5932        editor.change_selections(None, window, cx, |s| {
 5933            s.select_ranges([Point::new(4, 2)..Point::new(4, 2)]);
 5934        });
 5935    });
 5936
 5937    cx.assert_editor_state(indoc! {"
 5938        line 1
 5939        line 2
 5940        linXe 3
 5941        line 4
 5942        liˇne 5
 5943    "});
 5944
 5945    cx.lsp
 5946        .set_request_handler::<lsp::request::Formatting, _, _>(move |_, _| async move {
 5947            Ok(Some(vec![lsp::TextEdit::new(
 5948                lsp::Range::new(lsp::Position::new(0, 0), lsp::Position::new(0, 0)),
 5949                "PREFIX ".to_string(),
 5950            )]))
 5951        });
 5952
 5953    cx.update_editor(|editor, window, cx| editor.format(&Default::default(), window, cx))
 5954        .unwrap()
 5955        .await
 5956        .unwrap();
 5957
 5958    cx.assert_editor_state(indoc! {"
 5959        PREFIX line 1
 5960        line 2
 5961        linXe 3
 5962        line 4
 5963        liˇne 5
 5964    "});
 5965
 5966    // Undo formatting
 5967    cx.update_editor(|editor, window, cx| {
 5968        editor.undo(&Default::default(), window, cx);
 5969    });
 5970
 5971    // Verify cursor moved back to position after edit
 5972    cx.assert_editor_state(indoc! {"
 5973        line 1
 5974        line 2
 5975        linXˇe 3
 5976        line 4
 5977        line 5
 5978    "});
 5979}
 5980
 5981#[gpui::test]
 5982async fn test_select_next_with_multiple_carets(cx: &mut TestAppContext) {
 5983    init_test(cx, |_| {});
 5984
 5985    let mut cx = EditorTestContext::new(cx).await;
 5986    cx.set_state(
 5987        r#"let foo = 2;
 5988lˇet foo = 2;
 5989let fooˇ = 2;
 5990let foo = 2;
 5991let foo = ˇ2;"#,
 5992    );
 5993
 5994    cx.update_editor(|e, window, cx| e.select_next(&SelectNext::default(), window, cx))
 5995        .unwrap();
 5996    cx.assert_editor_state(
 5997        r#"let foo = 2;
 5998«letˇ» foo = 2;
 5999let «fooˇ» = 2;
 6000let foo = 2;
 6001let foo = «2ˇ»;"#,
 6002    );
 6003
 6004    // noop for multiple selections with different contents
 6005    cx.update_editor(|e, window, cx| e.select_next(&SelectNext::default(), window, cx))
 6006        .unwrap();
 6007    cx.assert_editor_state(
 6008        r#"let foo = 2;
 6009«letˇ» foo = 2;
 6010let «fooˇ» = 2;
 6011let foo = 2;
 6012let foo = «2ˇ»;"#,
 6013    );
 6014}
 6015
 6016#[gpui::test]
 6017async fn test_select_previous_multibuffer(cx: &mut TestAppContext) {
 6018    init_test(cx, |_| {});
 6019
 6020    let mut cx =
 6021        EditorTestContext::new_multibuffer(cx, ["aaa\n«bbb\nccc\n»ddd", "aaa\n«bbb\nccc\n»ddd"]);
 6022
 6023    cx.assert_editor_state(indoc! {"
 6024        ˇbbb
 6025        ccc
 6026
 6027        bbb
 6028        ccc
 6029        "});
 6030    cx.dispatch_action(SelectPrevious::default());
 6031    cx.assert_editor_state(indoc! {"
 6032                «bbbˇ»
 6033                ccc
 6034
 6035                bbb
 6036                ccc
 6037                "});
 6038    cx.dispatch_action(SelectPrevious::default());
 6039    cx.assert_editor_state(indoc! {"
 6040                «bbbˇ»
 6041                ccc
 6042
 6043                «bbbˇ»
 6044                ccc
 6045                "});
 6046}
 6047
 6048#[gpui::test]
 6049async fn test_select_previous_with_single_caret(cx: &mut TestAppContext) {
 6050    init_test(cx, |_| {});
 6051
 6052    let mut cx = EditorTestContext::new(cx).await;
 6053    cx.set_state("abc\nˇabc abc\ndefabc\nabc");
 6054
 6055    cx.update_editor(|e, window, cx| e.select_previous(&SelectPrevious::default(), window, cx))
 6056        .unwrap();
 6057    cx.assert_editor_state("abc\n«abcˇ» abc\ndefabc\nabc");
 6058
 6059    cx.update_editor(|e, window, cx| e.select_previous(&SelectPrevious::default(), window, cx))
 6060        .unwrap();
 6061    cx.assert_editor_state("«abcˇ»\n«abcˇ» abc\ndefabc\nabc");
 6062
 6063    cx.update_editor(|editor, window, cx| editor.undo_selection(&UndoSelection, window, cx));
 6064    cx.assert_editor_state("abc\n«abcˇ» abc\ndefabc\nabc");
 6065
 6066    cx.update_editor(|editor, window, cx| editor.redo_selection(&RedoSelection, window, cx));
 6067    cx.assert_editor_state("«abcˇ»\n«abcˇ» abc\ndefabc\nabc");
 6068
 6069    cx.update_editor(|e, window, cx| e.select_previous(&SelectPrevious::default(), window, cx))
 6070        .unwrap();
 6071    cx.assert_editor_state("«abcˇ»\n«abcˇ» abc\ndefabc\n«abcˇ»");
 6072
 6073    cx.update_editor(|e, window, cx| e.select_previous(&SelectPrevious::default(), window, cx))
 6074        .unwrap();
 6075    cx.assert_editor_state("«abcˇ»\n«abcˇ» abc\ndef«abcˇ»\n«abcˇ»");
 6076
 6077    cx.update_editor(|e, window, cx| e.select_previous(&SelectPrevious::default(), window, cx))
 6078        .unwrap();
 6079    cx.assert_editor_state("«abcˇ»\n«abcˇ» «abcˇ»\ndef«abcˇ»\n«abcˇ»");
 6080}
 6081
 6082#[gpui::test]
 6083async fn test_select_previous_empty_buffer(cx: &mut TestAppContext) {
 6084    init_test(cx, |_| {});
 6085
 6086    let mut cx = EditorTestContext::new(cx).await;
 6087    cx.set_state("");
 6088
 6089    cx.update_editor(|e, window, cx| e.select_previous(&SelectPrevious::default(), window, cx))
 6090        .unwrap();
 6091    cx.assert_editor_state("«aˇ»");
 6092    cx.update_editor(|e, window, cx| e.select_previous(&SelectPrevious::default(), window, cx))
 6093        .unwrap();
 6094    cx.assert_editor_state("«aˇ»");
 6095}
 6096
 6097#[gpui::test]
 6098async fn test_select_previous_with_multiple_carets(cx: &mut TestAppContext) {
 6099    init_test(cx, |_| {});
 6100
 6101    let mut cx = EditorTestContext::new(cx).await;
 6102    cx.set_state(
 6103        r#"let foo = 2;
 6104lˇet foo = 2;
 6105let fooˇ = 2;
 6106let foo = 2;
 6107let foo = ˇ2;"#,
 6108    );
 6109
 6110    cx.update_editor(|e, window, cx| e.select_previous(&SelectPrevious::default(), window, cx))
 6111        .unwrap();
 6112    cx.assert_editor_state(
 6113        r#"let foo = 2;
 6114«letˇ» foo = 2;
 6115let «fooˇ» = 2;
 6116let foo = 2;
 6117let foo = «2ˇ»;"#,
 6118    );
 6119
 6120    // noop for multiple selections with different contents
 6121    cx.update_editor(|e, window, cx| e.select_previous(&SelectPrevious::default(), window, cx))
 6122        .unwrap();
 6123    cx.assert_editor_state(
 6124        r#"let foo = 2;
 6125«letˇ» foo = 2;
 6126let «fooˇ» = 2;
 6127let foo = 2;
 6128let foo = «2ˇ»;"#,
 6129    );
 6130}
 6131
 6132#[gpui::test]
 6133async fn test_select_previous_with_single_selection(cx: &mut TestAppContext) {
 6134    init_test(cx, |_| {});
 6135
 6136    let mut cx = EditorTestContext::new(cx).await;
 6137    cx.set_state("abc\n«ˇabc» abc\ndefabc\nabc");
 6138
 6139    cx.update_editor(|e, window, cx| e.select_previous(&SelectPrevious::default(), window, cx))
 6140        .unwrap();
 6141    cx.assert_editor_state("«abcˇ»\n«ˇabc» abc\ndefabc\nabc");
 6142
 6143    cx.update_editor(|e, window, cx| e.select_previous(&SelectPrevious::default(), window, cx))
 6144        .unwrap();
 6145    cx.assert_editor_state("«abcˇ»\n«ˇabc» abc\ndefabc\n«abcˇ»");
 6146
 6147    cx.update_editor(|editor, window, cx| editor.undo_selection(&UndoSelection, window, cx));
 6148    cx.assert_editor_state("«abcˇ»\n«ˇabc» abc\ndefabc\nabc");
 6149
 6150    cx.update_editor(|editor, window, cx| editor.redo_selection(&RedoSelection, window, cx));
 6151    cx.assert_editor_state("«abcˇ»\n«ˇabc» abc\ndefabc\n«abcˇ»");
 6152
 6153    cx.update_editor(|e, window, cx| e.select_previous(&SelectPrevious::default(), window, cx))
 6154        .unwrap();
 6155    cx.assert_editor_state("«abcˇ»\n«ˇabc» abc\ndef«abcˇ»\n«abcˇ»");
 6156
 6157    cx.update_editor(|e, window, cx| e.select_previous(&SelectPrevious::default(), window, cx))
 6158        .unwrap();
 6159    cx.assert_editor_state("«abcˇ»\n«ˇabc» «abcˇ»\ndef«abcˇ»\n«abcˇ»");
 6160}
 6161
 6162#[gpui::test]
 6163async fn test_select_larger_smaller_syntax_node(cx: &mut TestAppContext) {
 6164    init_test(cx, |_| {});
 6165
 6166    let language = Arc::new(Language::new(
 6167        LanguageConfig::default(),
 6168        Some(tree_sitter_rust::LANGUAGE.into()),
 6169    ));
 6170
 6171    let text = r#"
 6172        use mod1::mod2::{mod3, mod4};
 6173
 6174        fn fn_1(param1: bool, param2: &str) {
 6175            let var1 = "text";
 6176        }
 6177    "#
 6178    .unindent();
 6179
 6180    let buffer = cx.new(|cx| Buffer::local(text, cx).with_language(language, cx));
 6181    let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 6182    let (editor, cx) = cx.add_window_view(|window, cx| build_editor(buffer, window, cx));
 6183
 6184    editor
 6185        .condition::<crate::EditorEvent>(cx, |editor, cx| !editor.buffer.read(cx).is_parsing(cx))
 6186        .await;
 6187
 6188    editor.update_in(cx, |editor, window, cx| {
 6189        editor.change_selections(None, window, cx, |s| {
 6190            s.select_display_ranges([
 6191                DisplayPoint::new(DisplayRow(0), 25)..DisplayPoint::new(DisplayRow(0), 25),
 6192                DisplayPoint::new(DisplayRow(2), 24)..DisplayPoint::new(DisplayRow(2), 12),
 6193                DisplayPoint::new(DisplayRow(3), 18)..DisplayPoint::new(DisplayRow(3), 18),
 6194            ]);
 6195        });
 6196        editor.select_larger_syntax_node(&SelectLargerSyntaxNode, window, cx);
 6197    });
 6198    editor.update(cx, |editor, cx| {
 6199        assert_text_with_selections(
 6200            editor,
 6201            indoc! {r#"
 6202                use mod1::mod2::{mod3, «mod4ˇ»};
 6203
 6204                fn fn_1«ˇ(param1: bool, param2: &str)» {
 6205                    let var1 = "«ˇtext»";
 6206                }
 6207            "#},
 6208            cx,
 6209        );
 6210    });
 6211
 6212    editor.update_in(cx, |editor, window, cx| {
 6213        editor.select_larger_syntax_node(&SelectLargerSyntaxNode, window, cx);
 6214    });
 6215    editor.update(cx, |editor, cx| {
 6216        assert_text_with_selections(
 6217            editor,
 6218            indoc! {r#"
 6219                use mod1::mod2::«{mod3, mod4}ˇ»;
 6220
 6221                «ˇfn fn_1(param1: bool, param2: &str) {
 6222                    let var1 = "text";
 6223 6224            "#},
 6225            cx,
 6226        );
 6227    });
 6228
 6229    editor.update_in(cx, |editor, window, cx| {
 6230        editor.select_larger_syntax_node(&SelectLargerSyntaxNode, window, cx);
 6231    });
 6232    assert_eq!(
 6233        editor.update(cx, |editor, cx| editor.selections.display_ranges(cx)),
 6234        &[DisplayPoint::new(DisplayRow(5), 0)..DisplayPoint::new(DisplayRow(0), 0)]
 6235    );
 6236
 6237    // Trying to expand the selected syntax node one more time has no effect.
 6238    editor.update_in(cx, |editor, window, cx| {
 6239        editor.select_larger_syntax_node(&SelectLargerSyntaxNode, window, cx);
 6240    });
 6241    assert_eq!(
 6242        editor.update(cx, |editor, cx| editor.selections.display_ranges(cx)),
 6243        &[DisplayPoint::new(DisplayRow(5), 0)..DisplayPoint::new(DisplayRow(0), 0)]
 6244    );
 6245
 6246    editor.update_in(cx, |editor, window, cx| {
 6247        editor.select_smaller_syntax_node(&SelectSmallerSyntaxNode, window, cx);
 6248    });
 6249    editor.update(cx, |editor, cx| {
 6250        assert_text_with_selections(
 6251            editor,
 6252            indoc! {r#"
 6253                use mod1::mod2::«{mod3, mod4}ˇ»;
 6254
 6255                «ˇfn fn_1(param1: bool, param2: &str) {
 6256                    let var1 = "text";
 6257 6258            "#},
 6259            cx,
 6260        );
 6261    });
 6262
 6263    editor.update_in(cx, |editor, window, cx| {
 6264        editor.select_smaller_syntax_node(&SelectSmallerSyntaxNode, window, cx);
 6265    });
 6266    editor.update(cx, |editor, cx| {
 6267        assert_text_with_selections(
 6268            editor,
 6269            indoc! {r#"
 6270                use mod1::mod2::{mod3, «mod4ˇ»};
 6271
 6272                fn fn_1«ˇ(param1: bool, param2: &str)» {
 6273                    let var1 = "«ˇtext»";
 6274                }
 6275            "#},
 6276            cx,
 6277        );
 6278    });
 6279
 6280    editor.update_in(cx, |editor, window, cx| {
 6281        editor.select_smaller_syntax_node(&SelectSmallerSyntaxNode, window, cx);
 6282    });
 6283    editor.update(cx, |editor, cx| {
 6284        assert_text_with_selections(
 6285            editor,
 6286            indoc! {r#"
 6287                use mod1::mod2::{mod3, mo«ˇ»d4};
 6288
 6289                fn fn_1(para«ˇm1: bool, pa»ram2: &str) {
 6290                    let var1 = "te«ˇ»xt";
 6291                }
 6292            "#},
 6293            cx,
 6294        );
 6295    });
 6296
 6297    // Trying to shrink the selected syntax node one more time has no effect.
 6298    editor.update_in(cx, |editor, window, cx| {
 6299        editor.select_smaller_syntax_node(&SelectSmallerSyntaxNode, window, cx);
 6300    });
 6301    editor.update_in(cx, |editor, _, cx| {
 6302        assert_text_with_selections(
 6303            editor,
 6304            indoc! {r#"
 6305                use mod1::mod2::{mod3, mo«ˇ»d4};
 6306
 6307                fn fn_1(para«ˇm1: bool, pa»ram2: &str) {
 6308                    let var1 = "te«ˇ»xt";
 6309                }
 6310            "#},
 6311            cx,
 6312        );
 6313    });
 6314
 6315    // Ensure that we keep expanding the selection if the larger selection starts or ends within
 6316    // a fold.
 6317    editor.update_in(cx, |editor, window, cx| {
 6318        editor.fold_creases(
 6319            vec![
 6320                Crease::simple(
 6321                    Point::new(0, 21)..Point::new(0, 24),
 6322                    FoldPlaceholder::test(),
 6323                ),
 6324                Crease::simple(
 6325                    Point::new(3, 20)..Point::new(3, 22),
 6326                    FoldPlaceholder::test(),
 6327                ),
 6328            ],
 6329            true,
 6330            window,
 6331            cx,
 6332        );
 6333        editor.select_larger_syntax_node(&SelectLargerSyntaxNode, window, cx);
 6334    });
 6335    editor.update(cx, |editor, cx| {
 6336        assert_text_with_selections(
 6337            editor,
 6338            indoc! {r#"
 6339                use mod1::mod2::«{mod3, mod4}ˇ»;
 6340
 6341                fn fn_1«ˇ(param1: bool, param2: &str)» {
 6342                    let var1 = "«ˇtext»";
 6343                }
 6344            "#},
 6345            cx,
 6346        );
 6347    });
 6348}
 6349
 6350#[gpui::test]
 6351async fn test_select_larger_smaller_syntax_node_for_string(cx: &mut TestAppContext) {
 6352    init_test(cx, |_| {});
 6353
 6354    let language = Arc::new(Language::new(
 6355        LanguageConfig::default(),
 6356        Some(tree_sitter_rust::LANGUAGE.into()),
 6357    ));
 6358
 6359    let text = r#"
 6360        use mod1::mod2::{mod3, mod4};
 6361
 6362        fn fn_1(param1: bool, param2: &str) {
 6363            let var1 = "hello world";
 6364        }
 6365    "#
 6366    .unindent();
 6367
 6368    let buffer = cx.new(|cx| Buffer::local(text, cx).with_language(language, cx));
 6369    let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 6370    let (editor, cx) = cx.add_window_view(|window, cx| build_editor(buffer, window, cx));
 6371
 6372    editor
 6373        .condition::<crate::EditorEvent>(cx, |editor, cx| !editor.buffer.read(cx).is_parsing(cx))
 6374        .await;
 6375
 6376    // Test 1: Cursor on a letter of a string word
 6377    editor.update_in(cx, |editor, window, cx| {
 6378        editor.change_selections(None, window, cx, |s| {
 6379            s.select_display_ranges([
 6380                DisplayPoint::new(DisplayRow(3), 17)..DisplayPoint::new(DisplayRow(3), 17)
 6381            ]);
 6382        });
 6383    });
 6384    editor.update_in(cx, |editor, window, cx| {
 6385        assert_text_with_selections(
 6386            editor,
 6387            indoc! {r#"
 6388                use mod1::mod2::{mod3, mod4};
 6389
 6390                fn fn_1(param1: bool, param2: &str) {
 6391                    let var1 = "hˇello world";
 6392                }
 6393            "#},
 6394            cx,
 6395        );
 6396        editor.select_larger_syntax_node(&SelectLargerSyntaxNode, window, cx);
 6397        assert_text_with_selections(
 6398            editor,
 6399            indoc! {r#"
 6400                use mod1::mod2::{mod3, mod4};
 6401
 6402                fn fn_1(param1: bool, param2: &str) {
 6403                    let var1 = "«ˇhello» world";
 6404                }
 6405            "#},
 6406            cx,
 6407        );
 6408    });
 6409
 6410    // Test 2: Partial selection within a word
 6411    editor.update_in(cx, |editor, window, cx| {
 6412        editor.change_selections(None, window, cx, |s| {
 6413            s.select_display_ranges([
 6414                DisplayPoint::new(DisplayRow(3), 17)..DisplayPoint::new(DisplayRow(3), 19)
 6415            ]);
 6416        });
 6417    });
 6418    editor.update_in(cx, |editor, window, cx| {
 6419        assert_text_with_selections(
 6420            editor,
 6421            indoc! {r#"
 6422                use mod1::mod2::{mod3, mod4};
 6423
 6424                fn fn_1(param1: bool, param2: &str) {
 6425                    let var1 = "h«elˇ»lo world";
 6426                }
 6427            "#},
 6428            cx,
 6429        );
 6430        editor.select_larger_syntax_node(&SelectLargerSyntaxNode, window, cx);
 6431        assert_text_with_selections(
 6432            editor,
 6433            indoc! {r#"
 6434                use mod1::mod2::{mod3, mod4};
 6435
 6436                fn fn_1(param1: bool, param2: &str) {
 6437                    let var1 = "«ˇhello» world";
 6438                }
 6439            "#},
 6440            cx,
 6441        );
 6442    });
 6443
 6444    // Test 3: Complete word already selected
 6445    editor.update_in(cx, |editor, window, cx| {
 6446        editor.change_selections(None, window, cx, |s| {
 6447            s.select_display_ranges([
 6448                DisplayPoint::new(DisplayRow(3), 16)..DisplayPoint::new(DisplayRow(3), 21)
 6449            ]);
 6450        });
 6451    });
 6452    editor.update_in(cx, |editor, window, cx| {
 6453        assert_text_with_selections(
 6454            editor,
 6455            indoc! {r#"
 6456                use mod1::mod2::{mod3, mod4};
 6457
 6458                fn fn_1(param1: bool, param2: &str) {
 6459                    let var1 = "«helloˇ» world";
 6460                }
 6461            "#},
 6462            cx,
 6463        );
 6464        editor.select_larger_syntax_node(&SelectLargerSyntaxNode, window, cx);
 6465        assert_text_with_selections(
 6466            editor,
 6467            indoc! {r#"
 6468                use mod1::mod2::{mod3, mod4};
 6469
 6470                fn fn_1(param1: bool, param2: &str) {
 6471                    let var1 = "«hello worldˇ»";
 6472                }
 6473            "#},
 6474            cx,
 6475        );
 6476    });
 6477
 6478    // Test 4: Selection spanning across words
 6479    editor.update_in(cx, |editor, window, cx| {
 6480        editor.change_selections(None, window, cx, |s| {
 6481            s.select_display_ranges([
 6482                DisplayPoint::new(DisplayRow(3), 19)..DisplayPoint::new(DisplayRow(3), 24)
 6483            ]);
 6484        });
 6485    });
 6486    editor.update_in(cx, |editor, window, cx| {
 6487        assert_text_with_selections(
 6488            editor,
 6489            indoc! {r#"
 6490                use mod1::mod2::{mod3, mod4};
 6491
 6492                fn fn_1(param1: bool, param2: &str) {
 6493                    let var1 = "hel«lo woˇ»rld";
 6494                }
 6495            "#},
 6496            cx,
 6497        );
 6498        editor.select_larger_syntax_node(&SelectLargerSyntaxNode, window, cx);
 6499        assert_text_with_selections(
 6500            editor,
 6501            indoc! {r#"
 6502                use mod1::mod2::{mod3, mod4};
 6503
 6504                fn fn_1(param1: bool, param2: &str) {
 6505                    let var1 = "«ˇhello world»";
 6506                }
 6507            "#},
 6508            cx,
 6509        );
 6510    });
 6511
 6512    // Test 5: Expansion beyond string
 6513    editor.update_in(cx, |editor, window, cx| {
 6514        editor.select_larger_syntax_node(&SelectLargerSyntaxNode, window, cx);
 6515        editor.select_larger_syntax_node(&SelectLargerSyntaxNode, window, cx);
 6516        assert_text_with_selections(
 6517            editor,
 6518            indoc! {r#"
 6519                use mod1::mod2::{mod3, mod4};
 6520
 6521                fn fn_1(param1: bool, param2: &str) {
 6522                    «ˇlet var1 = "hello world";»
 6523                }
 6524            "#},
 6525            cx,
 6526        );
 6527    });
 6528}
 6529
 6530#[gpui::test]
 6531async fn test_fold_function_bodies(cx: &mut TestAppContext) {
 6532    init_test(cx, |_| {});
 6533
 6534    let base_text = r#"
 6535        impl A {
 6536            // this is an uncommitted comment
 6537
 6538            fn b() {
 6539                c();
 6540            }
 6541
 6542            // this is another uncommitted comment
 6543
 6544            fn d() {
 6545                // e
 6546                // f
 6547            }
 6548        }
 6549
 6550        fn g() {
 6551            // h
 6552        }
 6553    "#
 6554    .unindent();
 6555
 6556    let text = r#"
 6557        ˇimpl A {
 6558
 6559            fn b() {
 6560                c();
 6561            }
 6562
 6563            fn d() {
 6564                // e
 6565                // f
 6566            }
 6567        }
 6568
 6569        fn g() {
 6570            // h
 6571        }
 6572    "#
 6573    .unindent();
 6574
 6575    let mut cx = EditorLspTestContext::new_rust(Default::default(), cx).await;
 6576    cx.set_state(&text);
 6577    cx.set_head_text(&base_text);
 6578    cx.update_editor(|editor, window, cx| {
 6579        editor.expand_all_diff_hunks(&Default::default(), window, cx);
 6580    });
 6581
 6582    cx.assert_state_with_diff(
 6583        "
 6584        ˇimpl A {
 6585      -     // this is an uncommitted comment
 6586
 6587            fn b() {
 6588                c();
 6589            }
 6590
 6591      -     // this is another uncommitted comment
 6592      -
 6593            fn d() {
 6594                // e
 6595                // f
 6596            }
 6597        }
 6598
 6599        fn g() {
 6600            // h
 6601        }
 6602    "
 6603        .unindent(),
 6604    );
 6605
 6606    let expected_display_text = "
 6607        impl A {
 6608            // this is an uncommitted comment
 6609
 6610            fn b() {
 6611 6612            }
 6613
 6614            // this is another uncommitted comment
 6615
 6616            fn d() {
 6617 6618            }
 6619        }
 6620
 6621        fn g() {
 6622 6623        }
 6624        "
 6625    .unindent();
 6626
 6627    cx.update_editor(|editor, window, cx| {
 6628        editor.fold_function_bodies(&FoldFunctionBodies, window, cx);
 6629        assert_eq!(editor.display_text(cx), expected_display_text);
 6630    });
 6631}
 6632
 6633#[gpui::test]
 6634async fn test_autoindent(cx: &mut TestAppContext) {
 6635    init_test(cx, |_| {});
 6636
 6637    let language = Arc::new(
 6638        Language::new(
 6639            LanguageConfig {
 6640                brackets: BracketPairConfig {
 6641                    pairs: vec![
 6642                        BracketPair {
 6643                            start: "{".to_string(),
 6644                            end: "}".to_string(),
 6645                            close: false,
 6646                            surround: false,
 6647                            newline: true,
 6648                        },
 6649                        BracketPair {
 6650                            start: "(".to_string(),
 6651                            end: ")".to_string(),
 6652                            close: false,
 6653                            surround: false,
 6654                            newline: true,
 6655                        },
 6656                    ],
 6657                    ..Default::default()
 6658                },
 6659                ..Default::default()
 6660            },
 6661            Some(tree_sitter_rust::LANGUAGE.into()),
 6662        )
 6663        .with_indents_query(
 6664            r#"
 6665                (_ "(" ")" @end) @indent
 6666                (_ "{" "}" @end) @indent
 6667            "#,
 6668        )
 6669        .unwrap(),
 6670    );
 6671
 6672    let text = "fn a() {}";
 6673
 6674    let buffer = cx.new(|cx| Buffer::local(text, cx).with_language(language, cx));
 6675    let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 6676    let (editor, cx) = cx.add_window_view(|window, cx| build_editor(buffer, window, cx));
 6677    editor
 6678        .condition::<crate::EditorEvent>(cx, |editor, cx| !editor.buffer.read(cx).is_parsing(cx))
 6679        .await;
 6680
 6681    editor.update_in(cx, |editor, window, cx| {
 6682        editor.change_selections(None, window, cx, |s| s.select_ranges([5..5, 8..8, 9..9]));
 6683        editor.newline(&Newline, window, cx);
 6684        assert_eq!(editor.text(cx), "fn a(\n    \n) {\n    \n}\n");
 6685        assert_eq!(
 6686            editor.selections.ranges(cx),
 6687            &[
 6688                Point::new(1, 4)..Point::new(1, 4),
 6689                Point::new(3, 4)..Point::new(3, 4),
 6690                Point::new(5, 0)..Point::new(5, 0)
 6691            ]
 6692        );
 6693    });
 6694}
 6695
 6696#[gpui::test]
 6697async fn test_autoindent_selections(cx: &mut TestAppContext) {
 6698    init_test(cx, |_| {});
 6699
 6700    {
 6701        let mut cx = EditorLspTestContext::new_rust(Default::default(), cx).await;
 6702        cx.set_state(indoc! {"
 6703            impl A {
 6704
 6705                fn b() {}
 6706
 6707            «fn c() {
 6708
 6709            }ˇ»
 6710            }
 6711        "});
 6712
 6713        cx.update_editor(|editor, window, cx| {
 6714            editor.autoindent(&Default::default(), window, cx);
 6715        });
 6716
 6717        cx.assert_editor_state(indoc! {"
 6718            impl A {
 6719
 6720                fn b() {}
 6721
 6722                «fn c() {
 6723
 6724                }ˇ»
 6725            }
 6726        "});
 6727    }
 6728
 6729    {
 6730        let mut cx = EditorTestContext::new_multibuffer(
 6731            cx,
 6732            [indoc! { "
 6733                impl A {
 6734                «
 6735                // a
 6736                fn b(){}
 6737                »
 6738                «
 6739                    }
 6740                    fn c(){}
 6741                »
 6742            "}],
 6743        );
 6744
 6745        let buffer = cx.update_editor(|editor, _, cx| {
 6746            let buffer = editor.buffer().update(cx, |buffer, _| {
 6747                buffer.all_buffers().iter().next().unwrap().clone()
 6748            });
 6749            buffer.update(cx, |buffer, cx| buffer.set_language(Some(rust_lang()), cx));
 6750            buffer
 6751        });
 6752
 6753        cx.run_until_parked();
 6754        cx.update_editor(|editor, window, cx| {
 6755            editor.select_all(&Default::default(), window, cx);
 6756            editor.autoindent(&Default::default(), window, cx)
 6757        });
 6758        cx.run_until_parked();
 6759
 6760        cx.update(|_, cx| {
 6761            assert_eq!(
 6762                buffer.read(cx).text(),
 6763                indoc! { "
 6764                    impl A {
 6765
 6766                        // a
 6767                        fn b(){}
 6768
 6769
 6770                    }
 6771                    fn c(){}
 6772
 6773                " }
 6774            )
 6775        });
 6776    }
 6777}
 6778
 6779#[gpui::test]
 6780async fn test_autoclose_and_auto_surround_pairs(cx: &mut TestAppContext) {
 6781    init_test(cx, |_| {});
 6782
 6783    let mut cx = EditorTestContext::new(cx).await;
 6784
 6785    let language = Arc::new(Language::new(
 6786        LanguageConfig {
 6787            brackets: BracketPairConfig {
 6788                pairs: vec![
 6789                    BracketPair {
 6790                        start: "{".to_string(),
 6791                        end: "}".to_string(),
 6792                        close: true,
 6793                        surround: true,
 6794                        newline: true,
 6795                    },
 6796                    BracketPair {
 6797                        start: "(".to_string(),
 6798                        end: ")".to_string(),
 6799                        close: true,
 6800                        surround: true,
 6801                        newline: true,
 6802                    },
 6803                    BracketPair {
 6804                        start: "/*".to_string(),
 6805                        end: " */".to_string(),
 6806                        close: true,
 6807                        surround: true,
 6808                        newline: true,
 6809                    },
 6810                    BracketPair {
 6811                        start: "[".to_string(),
 6812                        end: "]".to_string(),
 6813                        close: false,
 6814                        surround: false,
 6815                        newline: true,
 6816                    },
 6817                    BracketPair {
 6818                        start: "\"".to_string(),
 6819                        end: "\"".to_string(),
 6820                        close: true,
 6821                        surround: true,
 6822                        newline: false,
 6823                    },
 6824                    BracketPair {
 6825                        start: "<".to_string(),
 6826                        end: ">".to_string(),
 6827                        close: false,
 6828                        surround: true,
 6829                        newline: true,
 6830                    },
 6831                ],
 6832                ..Default::default()
 6833            },
 6834            autoclose_before: "})]".to_string(),
 6835            ..Default::default()
 6836        },
 6837        Some(tree_sitter_rust::LANGUAGE.into()),
 6838    ));
 6839
 6840    cx.language_registry().add(language.clone());
 6841    cx.update_buffer(|buffer, cx| {
 6842        buffer.set_language(Some(language), cx);
 6843    });
 6844
 6845    cx.set_state(
 6846        &r#"
 6847            🏀ˇ
 6848            εˇ
 6849            ❤️ˇ
 6850        "#
 6851        .unindent(),
 6852    );
 6853
 6854    // autoclose multiple nested brackets at multiple cursors
 6855    cx.update_editor(|editor, window, cx| {
 6856        editor.handle_input("{", window, cx);
 6857        editor.handle_input("{", window, cx);
 6858        editor.handle_input("{", window, cx);
 6859    });
 6860    cx.assert_editor_state(
 6861        &"
 6862            🏀{{{ˇ}}}
 6863            ε{{{ˇ}}}
 6864            ❤️{{{ˇ}}}
 6865        "
 6866        .unindent(),
 6867    );
 6868
 6869    // insert a different closing bracket
 6870    cx.update_editor(|editor, window, cx| {
 6871        editor.handle_input(")", window, cx);
 6872    });
 6873    cx.assert_editor_state(
 6874        &"
 6875            🏀{{{)ˇ}}}
 6876            ε{{{)ˇ}}}
 6877            ❤️{{{)ˇ}}}
 6878        "
 6879        .unindent(),
 6880    );
 6881
 6882    // skip over the auto-closed brackets when typing a closing bracket
 6883    cx.update_editor(|editor, window, cx| {
 6884        editor.move_right(&MoveRight, window, cx);
 6885        editor.handle_input("}", window, cx);
 6886        editor.handle_input("}", window, cx);
 6887        editor.handle_input("}", window, cx);
 6888    });
 6889    cx.assert_editor_state(
 6890        &"
 6891            🏀{{{)}}}}ˇ
 6892            ε{{{)}}}}ˇ
 6893            ❤️{{{)}}}}ˇ
 6894        "
 6895        .unindent(),
 6896    );
 6897
 6898    // autoclose multi-character pairs
 6899    cx.set_state(
 6900        &"
 6901            ˇ
 6902            ˇ
 6903        "
 6904        .unindent(),
 6905    );
 6906    cx.update_editor(|editor, window, cx| {
 6907        editor.handle_input("/", window, cx);
 6908        editor.handle_input("*", window, cx);
 6909    });
 6910    cx.assert_editor_state(
 6911        &"
 6912            /*ˇ */
 6913            /*ˇ */
 6914        "
 6915        .unindent(),
 6916    );
 6917
 6918    // one cursor autocloses a multi-character pair, one cursor
 6919    // does not autoclose.
 6920    cx.set_state(
 6921        &"
 6922 6923            ˇ
 6924        "
 6925        .unindent(),
 6926    );
 6927    cx.update_editor(|editor, window, cx| editor.handle_input("*", window, cx));
 6928    cx.assert_editor_state(
 6929        &"
 6930            /*ˇ */
 6931 6932        "
 6933        .unindent(),
 6934    );
 6935
 6936    // Don't autoclose if the next character isn't whitespace and isn't
 6937    // listed in the language's "autoclose_before" section.
 6938    cx.set_state("ˇa b");
 6939    cx.update_editor(|editor, window, cx| editor.handle_input("{", window, cx));
 6940    cx.assert_editor_state("{ˇa b");
 6941
 6942    // Don't autoclose if `close` is false for the bracket pair
 6943    cx.set_state("ˇ");
 6944    cx.update_editor(|editor, window, cx| editor.handle_input("[", window, cx));
 6945    cx.assert_editor_state("");
 6946
 6947    // Surround with brackets if text is selected
 6948    cx.set_state("«aˇ» b");
 6949    cx.update_editor(|editor, window, cx| editor.handle_input("{", window, cx));
 6950    cx.assert_editor_state("{«aˇ»} b");
 6951
 6952    // Autoclose when not immediately after a word character
 6953    cx.set_state("a ˇ");
 6954    cx.update_editor(|editor, window, cx| editor.handle_input("\"", window, cx));
 6955    cx.assert_editor_state("a \"ˇ\"");
 6956
 6957    // Autoclose pair where the start and end characters are the same
 6958    cx.update_editor(|editor, window, cx| editor.handle_input("\"", window, cx));
 6959    cx.assert_editor_state("a \"\"ˇ");
 6960
 6961    // Don't autoclose when immediately after a word character
 6962    cx.set_state("");
 6963    cx.update_editor(|editor, window, cx| editor.handle_input("\"", window, cx));
 6964    cx.assert_editor_state("a\"ˇ");
 6965
 6966    // Do autoclose when after a non-word character
 6967    cx.set_state("");
 6968    cx.update_editor(|editor, window, cx| editor.handle_input("\"", window, cx));
 6969    cx.assert_editor_state("{\"ˇ\"");
 6970
 6971    // Non identical pairs autoclose regardless of preceding character
 6972    cx.set_state("");
 6973    cx.update_editor(|editor, window, cx| editor.handle_input("{", window, cx));
 6974    cx.assert_editor_state("a{ˇ}");
 6975
 6976    // Don't autoclose pair if autoclose is disabled
 6977    cx.set_state("ˇ");
 6978    cx.update_editor(|editor, window, cx| editor.handle_input("<", window, cx));
 6979    cx.assert_editor_state("");
 6980
 6981    // Surround with brackets if text is selected and auto_surround is enabled, even if autoclose is disabled
 6982    cx.set_state("«aˇ» b");
 6983    cx.update_editor(|editor, window, cx| editor.handle_input("<", window, cx));
 6984    cx.assert_editor_state("<«aˇ»> b");
 6985}
 6986
 6987#[gpui::test]
 6988async fn test_always_treat_brackets_as_autoclosed_skip_over(cx: &mut TestAppContext) {
 6989    init_test(cx, |settings| {
 6990        settings.defaults.always_treat_brackets_as_autoclosed = Some(true);
 6991    });
 6992
 6993    let mut cx = EditorTestContext::new(cx).await;
 6994
 6995    let language = Arc::new(Language::new(
 6996        LanguageConfig {
 6997            brackets: BracketPairConfig {
 6998                pairs: vec![
 6999                    BracketPair {
 7000                        start: "{".to_string(),
 7001                        end: "}".to_string(),
 7002                        close: true,
 7003                        surround: true,
 7004                        newline: true,
 7005                    },
 7006                    BracketPair {
 7007                        start: "(".to_string(),
 7008                        end: ")".to_string(),
 7009                        close: true,
 7010                        surround: true,
 7011                        newline: true,
 7012                    },
 7013                    BracketPair {
 7014                        start: "[".to_string(),
 7015                        end: "]".to_string(),
 7016                        close: false,
 7017                        surround: false,
 7018                        newline: true,
 7019                    },
 7020                ],
 7021                ..Default::default()
 7022            },
 7023            autoclose_before: "})]".to_string(),
 7024            ..Default::default()
 7025        },
 7026        Some(tree_sitter_rust::LANGUAGE.into()),
 7027    ));
 7028
 7029    cx.language_registry().add(language.clone());
 7030    cx.update_buffer(|buffer, cx| {
 7031        buffer.set_language(Some(language), cx);
 7032    });
 7033
 7034    cx.set_state(
 7035        &"
 7036            ˇ
 7037            ˇ
 7038            ˇ
 7039        "
 7040        .unindent(),
 7041    );
 7042
 7043    // ensure only matching closing brackets are skipped over
 7044    cx.update_editor(|editor, window, cx| {
 7045        editor.handle_input("}", window, cx);
 7046        editor.move_left(&MoveLeft, window, cx);
 7047        editor.handle_input(")", window, cx);
 7048        editor.move_left(&MoveLeft, window, cx);
 7049    });
 7050    cx.assert_editor_state(
 7051        &"
 7052            ˇ)}
 7053            ˇ)}
 7054            ˇ)}
 7055        "
 7056        .unindent(),
 7057    );
 7058
 7059    // skip-over closing brackets at multiple cursors
 7060    cx.update_editor(|editor, window, cx| {
 7061        editor.handle_input(")", window, cx);
 7062        editor.handle_input("}", window, cx);
 7063    });
 7064    cx.assert_editor_state(
 7065        &"
 7066            )}ˇ
 7067            )}ˇ
 7068            )}ˇ
 7069        "
 7070        .unindent(),
 7071    );
 7072
 7073    // ignore non-close brackets
 7074    cx.update_editor(|editor, window, cx| {
 7075        editor.handle_input("]", window, cx);
 7076        editor.move_left(&MoveLeft, window, cx);
 7077        editor.handle_input("]", window, cx);
 7078    });
 7079    cx.assert_editor_state(
 7080        &"
 7081            )}]ˇ]
 7082            )}]ˇ]
 7083            )}]ˇ]
 7084        "
 7085        .unindent(),
 7086    );
 7087}
 7088
 7089#[gpui::test]
 7090async fn test_autoclose_with_embedded_language(cx: &mut TestAppContext) {
 7091    init_test(cx, |_| {});
 7092
 7093    let mut cx = EditorTestContext::new(cx).await;
 7094
 7095    let html_language = Arc::new(
 7096        Language::new(
 7097            LanguageConfig {
 7098                name: "HTML".into(),
 7099                brackets: BracketPairConfig {
 7100                    pairs: vec![
 7101                        BracketPair {
 7102                            start: "<".into(),
 7103                            end: ">".into(),
 7104                            close: true,
 7105                            ..Default::default()
 7106                        },
 7107                        BracketPair {
 7108                            start: "{".into(),
 7109                            end: "}".into(),
 7110                            close: true,
 7111                            ..Default::default()
 7112                        },
 7113                        BracketPair {
 7114                            start: "(".into(),
 7115                            end: ")".into(),
 7116                            close: true,
 7117                            ..Default::default()
 7118                        },
 7119                    ],
 7120                    ..Default::default()
 7121                },
 7122                autoclose_before: "})]>".into(),
 7123                ..Default::default()
 7124            },
 7125            Some(tree_sitter_html::LANGUAGE.into()),
 7126        )
 7127        .with_injection_query(
 7128            r#"
 7129            (script_element
 7130                (raw_text) @injection.content
 7131                (#set! injection.language "javascript"))
 7132            "#,
 7133        )
 7134        .unwrap(),
 7135    );
 7136
 7137    let javascript_language = Arc::new(Language::new(
 7138        LanguageConfig {
 7139            name: "JavaScript".into(),
 7140            brackets: BracketPairConfig {
 7141                pairs: vec![
 7142                    BracketPair {
 7143                        start: "/*".into(),
 7144                        end: " */".into(),
 7145                        close: true,
 7146                        ..Default::default()
 7147                    },
 7148                    BracketPair {
 7149                        start: "{".into(),
 7150                        end: "}".into(),
 7151                        close: true,
 7152                        ..Default::default()
 7153                    },
 7154                    BracketPair {
 7155                        start: "(".into(),
 7156                        end: ")".into(),
 7157                        close: true,
 7158                        ..Default::default()
 7159                    },
 7160                ],
 7161                ..Default::default()
 7162            },
 7163            autoclose_before: "})]>".into(),
 7164            ..Default::default()
 7165        },
 7166        Some(tree_sitter_typescript::LANGUAGE_TSX.into()),
 7167    ));
 7168
 7169    cx.language_registry().add(html_language.clone());
 7170    cx.language_registry().add(javascript_language.clone());
 7171
 7172    cx.update_buffer(|buffer, cx| {
 7173        buffer.set_language(Some(html_language), cx);
 7174    });
 7175
 7176    cx.set_state(
 7177        &r#"
 7178            <body>ˇ
 7179                <script>
 7180                    var x = 1;ˇ
 7181                </script>
 7182            </body>ˇ
 7183        "#
 7184        .unindent(),
 7185    );
 7186
 7187    // Precondition: different languages are active at different locations.
 7188    cx.update_editor(|editor, window, cx| {
 7189        let snapshot = editor.snapshot(window, cx);
 7190        let cursors = editor.selections.ranges::<usize>(cx);
 7191        let languages = cursors
 7192            .iter()
 7193            .map(|c| snapshot.language_at(c.start).unwrap().name())
 7194            .collect::<Vec<_>>();
 7195        assert_eq!(
 7196            languages,
 7197            &["HTML".into(), "JavaScript".into(), "HTML".into()]
 7198        );
 7199    });
 7200
 7201    // Angle brackets autoclose in HTML, but not JavaScript.
 7202    cx.update_editor(|editor, window, cx| {
 7203        editor.handle_input("<", window, cx);
 7204        editor.handle_input("a", window, cx);
 7205    });
 7206    cx.assert_editor_state(
 7207        &r#"
 7208            <body><aˇ>
 7209                <script>
 7210                    var x = 1;<aˇ
 7211                </script>
 7212            </body><aˇ>
 7213        "#
 7214        .unindent(),
 7215    );
 7216
 7217    // Curly braces and parens autoclose in both HTML and JavaScript.
 7218    cx.update_editor(|editor, window, cx| {
 7219        editor.handle_input(" b=", window, cx);
 7220        editor.handle_input("{", window, cx);
 7221        editor.handle_input("c", window, cx);
 7222        editor.handle_input("(", window, cx);
 7223    });
 7224    cx.assert_editor_state(
 7225        &r#"
 7226            <body><a b={c(ˇ)}>
 7227                <script>
 7228                    var x = 1;<a b={c(ˇ)}
 7229                </script>
 7230            </body><a b={c(ˇ)}>
 7231        "#
 7232        .unindent(),
 7233    );
 7234
 7235    // Brackets that were already autoclosed are skipped.
 7236    cx.update_editor(|editor, window, cx| {
 7237        editor.handle_input(")", window, cx);
 7238        editor.handle_input("d", window, cx);
 7239        editor.handle_input("}", window, cx);
 7240    });
 7241    cx.assert_editor_state(
 7242        &r#"
 7243            <body><a b={c()d}ˇ>
 7244                <script>
 7245                    var x = 1;<a b={c()d}ˇ
 7246                </script>
 7247            </body><a b={c()d}ˇ>
 7248        "#
 7249        .unindent(),
 7250    );
 7251    cx.update_editor(|editor, window, cx| {
 7252        editor.handle_input(">", window, cx);
 7253    });
 7254    cx.assert_editor_state(
 7255        &r#"
 7256            <body><a b={c()d}>ˇ
 7257                <script>
 7258                    var x = 1;<a b={c()d}>ˇ
 7259                </script>
 7260            </body><a b={c()d}>ˇ
 7261        "#
 7262        .unindent(),
 7263    );
 7264
 7265    // Reset
 7266    cx.set_state(
 7267        &r#"
 7268            <body>ˇ
 7269                <script>
 7270                    var x = 1;ˇ
 7271                </script>
 7272            </body>ˇ
 7273        "#
 7274        .unindent(),
 7275    );
 7276
 7277    cx.update_editor(|editor, window, cx| {
 7278        editor.handle_input("<", window, cx);
 7279    });
 7280    cx.assert_editor_state(
 7281        &r#"
 7282            <body><ˇ>
 7283                <script>
 7284                    var x = 1;<ˇ
 7285                </script>
 7286            </body><ˇ>
 7287        "#
 7288        .unindent(),
 7289    );
 7290
 7291    // When backspacing, the closing angle brackets are removed.
 7292    cx.update_editor(|editor, window, cx| {
 7293        editor.backspace(&Backspace, window, cx);
 7294    });
 7295    cx.assert_editor_state(
 7296        &r#"
 7297            <body>ˇ
 7298                <script>
 7299                    var x = 1;ˇ
 7300                </script>
 7301            </body>ˇ
 7302        "#
 7303        .unindent(),
 7304    );
 7305
 7306    // Block comments autoclose in JavaScript, but not HTML.
 7307    cx.update_editor(|editor, window, cx| {
 7308        editor.handle_input("/", window, cx);
 7309        editor.handle_input("*", window, cx);
 7310    });
 7311    cx.assert_editor_state(
 7312        &r#"
 7313            <body>/*ˇ
 7314                <script>
 7315                    var x = 1;/*ˇ */
 7316                </script>
 7317            </body>/*ˇ
 7318        "#
 7319        .unindent(),
 7320    );
 7321}
 7322
 7323#[gpui::test]
 7324async fn test_autoclose_with_overrides(cx: &mut TestAppContext) {
 7325    init_test(cx, |_| {});
 7326
 7327    let mut cx = EditorTestContext::new(cx).await;
 7328
 7329    let rust_language = Arc::new(
 7330        Language::new(
 7331            LanguageConfig {
 7332                name: "Rust".into(),
 7333                brackets: serde_json::from_value(json!([
 7334                    { "start": "{", "end": "}", "close": true, "newline": true },
 7335                    { "start": "\"", "end": "\"", "close": true, "newline": false, "not_in": ["string"] },
 7336                ]))
 7337                .unwrap(),
 7338                autoclose_before: "})]>".into(),
 7339                ..Default::default()
 7340            },
 7341            Some(tree_sitter_rust::LANGUAGE.into()),
 7342        )
 7343        .with_override_query("(string_literal) @string")
 7344        .unwrap(),
 7345    );
 7346
 7347    cx.language_registry().add(rust_language.clone());
 7348    cx.update_buffer(|buffer, cx| {
 7349        buffer.set_language(Some(rust_language), cx);
 7350    });
 7351
 7352    cx.set_state(
 7353        &r#"
 7354            let x = ˇ
 7355        "#
 7356        .unindent(),
 7357    );
 7358
 7359    // Inserting a quotation mark. A closing quotation mark is automatically inserted.
 7360    cx.update_editor(|editor, window, cx| {
 7361        editor.handle_input("\"", window, cx);
 7362    });
 7363    cx.assert_editor_state(
 7364        &r#"
 7365            let x = "ˇ"
 7366        "#
 7367        .unindent(),
 7368    );
 7369
 7370    // Inserting another quotation mark. The cursor moves across the existing
 7371    // automatically-inserted quotation mark.
 7372    cx.update_editor(|editor, window, cx| {
 7373        editor.handle_input("\"", window, cx);
 7374    });
 7375    cx.assert_editor_state(
 7376        &r#"
 7377            let x = ""ˇ
 7378        "#
 7379        .unindent(),
 7380    );
 7381
 7382    // Reset
 7383    cx.set_state(
 7384        &r#"
 7385            let x = ˇ
 7386        "#
 7387        .unindent(),
 7388    );
 7389
 7390    // Inserting a quotation mark inside of a string. A second quotation mark is not inserted.
 7391    cx.update_editor(|editor, window, cx| {
 7392        editor.handle_input("\"", window, cx);
 7393        editor.handle_input(" ", window, cx);
 7394        editor.move_left(&Default::default(), window, cx);
 7395        editor.handle_input("\\", window, cx);
 7396        editor.handle_input("\"", window, cx);
 7397    });
 7398    cx.assert_editor_state(
 7399        &r#"
 7400            let x = "\"ˇ "
 7401        "#
 7402        .unindent(),
 7403    );
 7404
 7405    // Inserting a closing quotation mark at the position of an automatically-inserted quotation
 7406    // mark. Nothing is inserted.
 7407    cx.update_editor(|editor, window, cx| {
 7408        editor.move_right(&Default::default(), window, cx);
 7409        editor.handle_input("\"", window, cx);
 7410    });
 7411    cx.assert_editor_state(
 7412        &r#"
 7413            let x = "\" "ˇ
 7414        "#
 7415        .unindent(),
 7416    );
 7417}
 7418
 7419#[gpui::test]
 7420async fn test_surround_with_pair(cx: &mut TestAppContext) {
 7421    init_test(cx, |_| {});
 7422
 7423    let language = Arc::new(Language::new(
 7424        LanguageConfig {
 7425            brackets: BracketPairConfig {
 7426                pairs: vec![
 7427                    BracketPair {
 7428                        start: "{".to_string(),
 7429                        end: "}".to_string(),
 7430                        close: true,
 7431                        surround: true,
 7432                        newline: true,
 7433                    },
 7434                    BracketPair {
 7435                        start: "/* ".to_string(),
 7436                        end: "*/".to_string(),
 7437                        close: true,
 7438                        surround: true,
 7439                        ..Default::default()
 7440                    },
 7441                ],
 7442                ..Default::default()
 7443            },
 7444            ..Default::default()
 7445        },
 7446        Some(tree_sitter_rust::LANGUAGE.into()),
 7447    ));
 7448
 7449    let text = r#"
 7450        a
 7451        b
 7452        c
 7453    "#
 7454    .unindent();
 7455
 7456    let buffer = cx.new(|cx| Buffer::local(text, cx).with_language(language, cx));
 7457    let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 7458    let (editor, cx) = cx.add_window_view(|window, cx| build_editor(buffer, window, cx));
 7459    editor
 7460        .condition::<crate::EditorEvent>(cx, |editor, cx| !editor.buffer.read(cx).is_parsing(cx))
 7461        .await;
 7462
 7463    editor.update_in(cx, |editor, window, cx| {
 7464        editor.change_selections(None, window, cx, |s| {
 7465            s.select_display_ranges([
 7466                DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(0), 1),
 7467                DisplayPoint::new(DisplayRow(1), 0)..DisplayPoint::new(DisplayRow(1), 1),
 7468                DisplayPoint::new(DisplayRow(2), 0)..DisplayPoint::new(DisplayRow(2), 1),
 7469            ])
 7470        });
 7471
 7472        editor.handle_input("{", window, cx);
 7473        editor.handle_input("{", window, cx);
 7474        editor.handle_input("{", window, cx);
 7475        assert_eq!(
 7476            editor.text(cx),
 7477            "
 7478                {{{a}}}
 7479                {{{b}}}
 7480                {{{c}}}
 7481            "
 7482            .unindent()
 7483        );
 7484        assert_eq!(
 7485            editor.selections.display_ranges(cx),
 7486            [
 7487                DisplayPoint::new(DisplayRow(0), 3)..DisplayPoint::new(DisplayRow(0), 4),
 7488                DisplayPoint::new(DisplayRow(1), 3)..DisplayPoint::new(DisplayRow(1), 4),
 7489                DisplayPoint::new(DisplayRow(2), 3)..DisplayPoint::new(DisplayRow(2), 4)
 7490            ]
 7491        );
 7492
 7493        editor.undo(&Undo, window, cx);
 7494        editor.undo(&Undo, window, cx);
 7495        editor.undo(&Undo, window, cx);
 7496        assert_eq!(
 7497            editor.text(cx),
 7498            "
 7499                a
 7500                b
 7501                c
 7502            "
 7503            .unindent()
 7504        );
 7505        assert_eq!(
 7506            editor.selections.display_ranges(cx),
 7507            [
 7508                DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(0), 1),
 7509                DisplayPoint::new(DisplayRow(1), 0)..DisplayPoint::new(DisplayRow(1), 1),
 7510                DisplayPoint::new(DisplayRow(2), 0)..DisplayPoint::new(DisplayRow(2), 1)
 7511            ]
 7512        );
 7513
 7514        // Ensure inserting the first character of a multi-byte bracket pair
 7515        // doesn't surround the selections with the bracket.
 7516        editor.handle_input("/", window, cx);
 7517        assert_eq!(
 7518            editor.text(cx),
 7519            "
 7520                /
 7521                /
 7522                /
 7523            "
 7524            .unindent()
 7525        );
 7526        assert_eq!(
 7527            editor.selections.display_ranges(cx),
 7528            [
 7529                DisplayPoint::new(DisplayRow(0), 1)..DisplayPoint::new(DisplayRow(0), 1),
 7530                DisplayPoint::new(DisplayRow(1), 1)..DisplayPoint::new(DisplayRow(1), 1),
 7531                DisplayPoint::new(DisplayRow(2), 1)..DisplayPoint::new(DisplayRow(2), 1)
 7532            ]
 7533        );
 7534
 7535        editor.undo(&Undo, window, cx);
 7536        assert_eq!(
 7537            editor.text(cx),
 7538            "
 7539                a
 7540                b
 7541                c
 7542            "
 7543            .unindent()
 7544        );
 7545        assert_eq!(
 7546            editor.selections.display_ranges(cx),
 7547            [
 7548                DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(0), 1),
 7549                DisplayPoint::new(DisplayRow(1), 0)..DisplayPoint::new(DisplayRow(1), 1),
 7550                DisplayPoint::new(DisplayRow(2), 0)..DisplayPoint::new(DisplayRow(2), 1)
 7551            ]
 7552        );
 7553
 7554        // Ensure inserting the last character of a multi-byte bracket pair
 7555        // doesn't surround the selections with the bracket.
 7556        editor.handle_input("*", window, cx);
 7557        assert_eq!(
 7558            editor.text(cx),
 7559            "
 7560                *
 7561                *
 7562                *
 7563            "
 7564            .unindent()
 7565        );
 7566        assert_eq!(
 7567            editor.selections.display_ranges(cx),
 7568            [
 7569                DisplayPoint::new(DisplayRow(0), 1)..DisplayPoint::new(DisplayRow(0), 1),
 7570                DisplayPoint::new(DisplayRow(1), 1)..DisplayPoint::new(DisplayRow(1), 1),
 7571                DisplayPoint::new(DisplayRow(2), 1)..DisplayPoint::new(DisplayRow(2), 1)
 7572            ]
 7573        );
 7574    });
 7575}
 7576
 7577#[gpui::test]
 7578async fn test_delete_autoclose_pair(cx: &mut TestAppContext) {
 7579    init_test(cx, |_| {});
 7580
 7581    let language = Arc::new(Language::new(
 7582        LanguageConfig {
 7583            brackets: BracketPairConfig {
 7584                pairs: vec![BracketPair {
 7585                    start: "{".to_string(),
 7586                    end: "}".to_string(),
 7587                    close: true,
 7588                    surround: true,
 7589                    newline: true,
 7590                }],
 7591                ..Default::default()
 7592            },
 7593            autoclose_before: "}".to_string(),
 7594            ..Default::default()
 7595        },
 7596        Some(tree_sitter_rust::LANGUAGE.into()),
 7597    ));
 7598
 7599    let text = r#"
 7600        a
 7601        b
 7602        c
 7603    "#
 7604    .unindent();
 7605
 7606    let buffer = cx.new(|cx| Buffer::local(text, cx).with_language(language, cx));
 7607    let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 7608    let (editor, cx) = cx.add_window_view(|window, cx| build_editor(buffer, window, cx));
 7609    editor
 7610        .condition::<crate::EditorEvent>(cx, |editor, cx| !editor.buffer.read(cx).is_parsing(cx))
 7611        .await;
 7612
 7613    editor.update_in(cx, |editor, window, cx| {
 7614        editor.change_selections(None, window, cx, |s| {
 7615            s.select_ranges([
 7616                Point::new(0, 1)..Point::new(0, 1),
 7617                Point::new(1, 1)..Point::new(1, 1),
 7618                Point::new(2, 1)..Point::new(2, 1),
 7619            ])
 7620        });
 7621
 7622        editor.handle_input("{", window, cx);
 7623        editor.handle_input("{", window, cx);
 7624        editor.handle_input("_", window, cx);
 7625        assert_eq!(
 7626            editor.text(cx),
 7627            "
 7628                a{{_}}
 7629                b{{_}}
 7630                c{{_}}
 7631            "
 7632            .unindent()
 7633        );
 7634        assert_eq!(
 7635            editor.selections.ranges::<Point>(cx),
 7636            [
 7637                Point::new(0, 4)..Point::new(0, 4),
 7638                Point::new(1, 4)..Point::new(1, 4),
 7639                Point::new(2, 4)..Point::new(2, 4)
 7640            ]
 7641        );
 7642
 7643        editor.backspace(&Default::default(), window, cx);
 7644        editor.backspace(&Default::default(), window, cx);
 7645        assert_eq!(
 7646            editor.text(cx),
 7647            "
 7648                a{}
 7649                b{}
 7650                c{}
 7651            "
 7652            .unindent()
 7653        );
 7654        assert_eq!(
 7655            editor.selections.ranges::<Point>(cx),
 7656            [
 7657                Point::new(0, 2)..Point::new(0, 2),
 7658                Point::new(1, 2)..Point::new(1, 2),
 7659                Point::new(2, 2)..Point::new(2, 2)
 7660            ]
 7661        );
 7662
 7663        editor.delete_to_previous_word_start(&Default::default(), window, cx);
 7664        assert_eq!(
 7665            editor.text(cx),
 7666            "
 7667                a
 7668                b
 7669                c
 7670            "
 7671            .unindent()
 7672        );
 7673        assert_eq!(
 7674            editor.selections.ranges::<Point>(cx),
 7675            [
 7676                Point::new(0, 1)..Point::new(0, 1),
 7677                Point::new(1, 1)..Point::new(1, 1),
 7678                Point::new(2, 1)..Point::new(2, 1)
 7679            ]
 7680        );
 7681    });
 7682}
 7683
 7684#[gpui::test]
 7685async fn test_always_treat_brackets_as_autoclosed_delete(cx: &mut TestAppContext) {
 7686    init_test(cx, |settings| {
 7687        settings.defaults.always_treat_brackets_as_autoclosed = Some(true);
 7688    });
 7689
 7690    let mut cx = EditorTestContext::new(cx).await;
 7691
 7692    let language = Arc::new(Language::new(
 7693        LanguageConfig {
 7694            brackets: BracketPairConfig {
 7695                pairs: vec![
 7696                    BracketPair {
 7697                        start: "{".to_string(),
 7698                        end: "}".to_string(),
 7699                        close: true,
 7700                        surround: true,
 7701                        newline: true,
 7702                    },
 7703                    BracketPair {
 7704                        start: "(".to_string(),
 7705                        end: ")".to_string(),
 7706                        close: true,
 7707                        surround: true,
 7708                        newline: true,
 7709                    },
 7710                    BracketPair {
 7711                        start: "[".to_string(),
 7712                        end: "]".to_string(),
 7713                        close: false,
 7714                        surround: true,
 7715                        newline: true,
 7716                    },
 7717                ],
 7718                ..Default::default()
 7719            },
 7720            autoclose_before: "})]".to_string(),
 7721            ..Default::default()
 7722        },
 7723        Some(tree_sitter_rust::LANGUAGE.into()),
 7724    ));
 7725
 7726    cx.language_registry().add(language.clone());
 7727    cx.update_buffer(|buffer, cx| {
 7728        buffer.set_language(Some(language), cx);
 7729    });
 7730
 7731    cx.set_state(
 7732        &"
 7733            {(ˇ)}
 7734            [[ˇ]]
 7735            {(ˇ)}
 7736        "
 7737        .unindent(),
 7738    );
 7739
 7740    cx.update_editor(|editor, window, cx| {
 7741        editor.backspace(&Default::default(), window, cx);
 7742        editor.backspace(&Default::default(), window, cx);
 7743    });
 7744
 7745    cx.assert_editor_state(
 7746        &"
 7747            ˇ
 7748            ˇ]]
 7749            ˇ
 7750        "
 7751        .unindent(),
 7752    );
 7753
 7754    cx.update_editor(|editor, window, cx| {
 7755        editor.handle_input("{", window, cx);
 7756        editor.handle_input("{", window, cx);
 7757        editor.move_right(&MoveRight, window, cx);
 7758        editor.move_right(&MoveRight, window, cx);
 7759        editor.move_left(&MoveLeft, window, cx);
 7760        editor.move_left(&MoveLeft, window, cx);
 7761        editor.backspace(&Default::default(), window, cx);
 7762    });
 7763
 7764    cx.assert_editor_state(
 7765        &"
 7766            {ˇ}
 7767            {ˇ}]]
 7768            {ˇ}
 7769        "
 7770        .unindent(),
 7771    );
 7772
 7773    cx.update_editor(|editor, window, cx| {
 7774        editor.backspace(&Default::default(), window, cx);
 7775    });
 7776
 7777    cx.assert_editor_state(
 7778        &"
 7779            ˇ
 7780            ˇ]]
 7781            ˇ
 7782        "
 7783        .unindent(),
 7784    );
 7785}
 7786
 7787#[gpui::test]
 7788async fn test_auto_replace_emoji_shortcode(cx: &mut TestAppContext) {
 7789    init_test(cx, |_| {});
 7790
 7791    let language = Arc::new(Language::new(
 7792        LanguageConfig::default(),
 7793        Some(tree_sitter_rust::LANGUAGE.into()),
 7794    ));
 7795
 7796    let buffer = cx.new(|cx| Buffer::local("", cx).with_language(language, cx));
 7797    let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 7798    let (editor, cx) = cx.add_window_view(|window, cx| build_editor(buffer, window, cx));
 7799    editor
 7800        .condition::<crate::EditorEvent>(cx, |editor, cx| !editor.buffer.read(cx).is_parsing(cx))
 7801        .await;
 7802
 7803    editor.update_in(cx, |editor, window, cx| {
 7804        editor.set_auto_replace_emoji_shortcode(true);
 7805
 7806        editor.handle_input("Hello ", window, cx);
 7807        editor.handle_input(":wave", window, cx);
 7808        assert_eq!(editor.text(cx), "Hello :wave".unindent());
 7809
 7810        editor.handle_input(":", window, cx);
 7811        assert_eq!(editor.text(cx), "Hello 👋".unindent());
 7812
 7813        editor.handle_input(" :smile", window, cx);
 7814        assert_eq!(editor.text(cx), "Hello 👋 :smile".unindent());
 7815
 7816        editor.handle_input(":", window, cx);
 7817        assert_eq!(editor.text(cx), "Hello 👋 😄".unindent());
 7818
 7819        // Ensure shortcode gets replaced when it is part of a word that only consists of emojis
 7820        editor.handle_input(":wave", window, cx);
 7821        assert_eq!(editor.text(cx), "Hello 👋 😄:wave".unindent());
 7822
 7823        editor.handle_input(":", window, cx);
 7824        assert_eq!(editor.text(cx), "Hello 👋 😄👋".unindent());
 7825
 7826        editor.handle_input(":1", window, cx);
 7827        assert_eq!(editor.text(cx), "Hello 👋 😄👋:1".unindent());
 7828
 7829        editor.handle_input(":", window, cx);
 7830        assert_eq!(editor.text(cx), "Hello 👋 😄👋:1:".unindent());
 7831
 7832        // Ensure shortcode does not get replaced when it is part of a word
 7833        editor.handle_input(" Test:wave", window, cx);
 7834        assert_eq!(editor.text(cx), "Hello 👋 😄👋:1: Test:wave".unindent());
 7835
 7836        editor.handle_input(":", window, cx);
 7837        assert_eq!(editor.text(cx), "Hello 👋 😄👋:1: Test:wave:".unindent());
 7838
 7839        editor.set_auto_replace_emoji_shortcode(false);
 7840
 7841        // Ensure shortcode does not get replaced when auto replace is off
 7842        editor.handle_input(" :wave", window, cx);
 7843        assert_eq!(
 7844            editor.text(cx),
 7845            "Hello 👋 😄👋:1: Test:wave: :wave".unindent()
 7846        );
 7847
 7848        editor.handle_input(":", window, cx);
 7849        assert_eq!(
 7850            editor.text(cx),
 7851            "Hello 👋 😄👋:1: Test:wave: :wave:".unindent()
 7852        );
 7853    });
 7854}
 7855
 7856#[gpui::test]
 7857async fn test_snippet_placeholder_choices(cx: &mut TestAppContext) {
 7858    init_test(cx, |_| {});
 7859
 7860    let (text, insertion_ranges) = marked_text_ranges(
 7861        indoc! {"
 7862            ˇ
 7863        "},
 7864        false,
 7865    );
 7866
 7867    let buffer = cx.update(|cx| MultiBuffer::build_simple(&text, cx));
 7868    let (editor, cx) = cx.add_window_view(|window, cx| build_editor(buffer, window, cx));
 7869
 7870    _ = editor.update_in(cx, |editor, window, cx| {
 7871        let snippet = Snippet::parse("type ${1|,i32,u32|} = $2").unwrap();
 7872
 7873        editor
 7874            .insert_snippet(&insertion_ranges, snippet, window, cx)
 7875            .unwrap();
 7876
 7877        fn assert(editor: &mut Editor, cx: &mut Context<Editor>, marked_text: &str) {
 7878            let (expected_text, selection_ranges) = marked_text_ranges(marked_text, false);
 7879            assert_eq!(editor.text(cx), expected_text);
 7880            assert_eq!(editor.selections.ranges::<usize>(cx), selection_ranges);
 7881        }
 7882
 7883        assert(
 7884            editor,
 7885            cx,
 7886            indoc! {"
 7887            type «» =•
 7888            "},
 7889        );
 7890
 7891        assert!(editor.context_menu_visible(), "There should be a matches");
 7892    });
 7893}
 7894
 7895#[gpui::test]
 7896async fn test_snippets(cx: &mut TestAppContext) {
 7897    init_test(cx, |_| {});
 7898
 7899    let (text, insertion_ranges) = marked_text_ranges(
 7900        indoc! {"
 7901            a.ˇ b
 7902            a.ˇ b
 7903            a.ˇ b
 7904        "},
 7905        false,
 7906    );
 7907
 7908    let buffer = cx.update(|cx| MultiBuffer::build_simple(&text, cx));
 7909    let (editor, cx) = cx.add_window_view(|window, cx| build_editor(buffer, window, cx));
 7910
 7911    editor.update_in(cx, |editor, window, cx| {
 7912        let snippet = Snippet::parse("f(${1:one}, ${2:two}, ${1:three})$0").unwrap();
 7913
 7914        editor
 7915            .insert_snippet(&insertion_ranges, snippet, window, cx)
 7916            .unwrap();
 7917
 7918        fn assert(editor: &mut Editor, cx: &mut Context<Editor>, marked_text: &str) {
 7919            let (expected_text, selection_ranges) = marked_text_ranges(marked_text, false);
 7920            assert_eq!(editor.text(cx), expected_text);
 7921            assert_eq!(editor.selections.ranges::<usize>(cx), selection_ranges);
 7922        }
 7923
 7924        assert(
 7925            editor,
 7926            cx,
 7927            indoc! {"
 7928                a.f(«one», two, «three») b
 7929                a.f(«one», two, «three») b
 7930                a.f(«one», two, «three») b
 7931            "},
 7932        );
 7933
 7934        // Can't move earlier than the first tab stop
 7935        assert!(!editor.move_to_prev_snippet_tabstop(window, cx));
 7936        assert(
 7937            editor,
 7938            cx,
 7939            indoc! {"
 7940                a.f(«one», two, «three») b
 7941                a.f(«one», two, «three») b
 7942                a.f(«one», two, «three») b
 7943            "},
 7944        );
 7945
 7946        assert!(editor.move_to_next_snippet_tabstop(window, cx));
 7947        assert(
 7948            editor,
 7949            cx,
 7950            indoc! {"
 7951                a.f(one, «two», three) b
 7952                a.f(one, «two», three) b
 7953                a.f(one, «two», three) b
 7954            "},
 7955        );
 7956
 7957        editor.move_to_prev_snippet_tabstop(window, cx);
 7958        assert(
 7959            editor,
 7960            cx,
 7961            indoc! {"
 7962                a.f(«one», two, «three») b
 7963                a.f(«one», two, «three») b
 7964                a.f(«one», two, «three») b
 7965            "},
 7966        );
 7967
 7968        assert!(editor.move_to_next_snippet_tabstop(window, cx));
 7969        assert(
 7970            editor,
 7971            cx,
 7972            indoc! {"
 7973                a.f(one, «two», three) b
 7974                a.f(one, «two», three) b
 7975                a.f(one, «two», three) b
 7976            "},
 7977        );
 7978        assert!(editor.move_to_next_snippet_tabstop(window, cx));
 7979        assert(
 7980            editor,
 7981            cx,
 7982            indoc! {"
 7983                a.f(one, two, three)ˇ b
 7984                a.f(one, two, three)ˇ b
 7985                a.f(one, two, three)ˇ b
 7986            "},
 7987        );
 7988
 7989        // As soon as the last tab stop is reached, snippet state is gone
 7990        editor.move_to_prev_snippet_tabstop(window, cx);
 7991        assert(
 7992            editor,
 7993            cx,
 7994            indoc! {"
 7995                a.f(one, two, three)ˇ b
 7996                a.f(one, two, three)ˇ b
 7997                a.f(one, two, three)ˇ b
 7998            "},
 7999        );
 8000    });
 8001}
 8002
 8003#[gpui::test]
 8004async fn test_document_format_during_save(cx: &mut TestAppContext) {
 8005    init_test(cx, |_| {});
 8006
 8007    let fs = FakeFs::new(cx.executor());
 8008    fs.insert_file(path!("/file.rs"), Default::default()).await;
 8009
 8010    let project = Project::test(fs, [path!("/file.rs").as_ref()], cx).await;
 8011
 8012    let language_registry = project.read_with(cx, |project, _| project.languages().clone());
 8013    language_registry.add(rust_lang());
 8014    let mut fake_servers = language_registry.register_fake_lsp(
 8015        "Rust",
 8016        FakeLspAdapter {
 8017            capabilities: lsp::ServerCapabilities {
 8018                document_formatting_provider: Some(lsp::OneOf::Left(true)),
 8019                ..Default::default()
 8020            },
 8021            ..Default::default()
 8022        },
 8023    );
 8024
 8025    let buffer = project
 8026        .update(cx, |project, cx| {
 8027            project.open_local_buffer(path!("/file.rs"), cx)
 8028        })
 8029        .await
 8030        .unwrap();
 8031
 8032    let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 8033    let (editor, cx) = cx.add_window_view(|window, cx| {
 8034        build_editor_with_project(project.clone(), buffer, window, cx)
 8035    });
 8036    editor.update_in(cx, |editor, window, cx| {
 8037        editor.set_text("one\ntwo\nthree\n", window, cx)
 8038    });
 8039    assert!(cx.read(|cx| editor.is_dirty(cx)));
 8040
 8041    cx.executor().start_waiting();
 8042    let fake_server = fake_servers.next().await.unwrap();
 8043
 8044    {
 8045        fake_server.set_request_handler::<lsp::request::Formatting, _, _>(
 8046            move |params, _| async move {
 8047                assert_eq!(
 8048                    params.text_document.uri,
 8049                    lsp::Url::from_file_path(path!("/file.rs")).unwrap()
 8050                );
 8051                assert_eq!(params.options.tab_size, 4);
 8052                Ok(Some(vec![lsp::TextEdit::new(
 8053                    lsp::Range::new(lsp::Position::new(0, 3), lsp::Position::new(1, 0)),
 8054                    ", ".to_string(),
 8055                )]))
 8056            },
 8057        );
 8058        let save = editor
 8059            .update_in(cx, |editor, window, cx| {
 8060                editor.save(true, project.clone(), window, cx)
 8061            })
 8062            .unwrap();
 8063        cx.executor().start_waiting();
 8064        save.await;
 8065
 8066        assert_eq!(
 8067            editor.update(cx, |editor, cx| editor.text(cx)),
 8068            "one, two\nthree\n"
 8069        );
 8070        assert!(!cx.read(|cx| editor.is_dirty(cx)));
 8071    }
 8072
 8073    {
 8074        editor.update_in(cx, |editor, window, cx| {
 8075            editor.set_text("one\ntwo\nthree\n", window, cx)
 8076        });
 8077        assert!(cx.read(|cx| editor.is_dirty(cx)));
 8078
 8079        // Ensure we can still save even if formatting hangs.
 8080        fake_server.set_request_handler::<lsp::request::Formatting, _, _>(
 8081            move |params, _| async move {
 8082                assert_eq!(
 8083                    params.text_document.uri,
 8084                    lsp::Url::from_file_path(path!("/file.rs")).unwrap()
 8085                );
 8086                futures::future::pending::<()>().await;
 8087                unreachable!()
 8088            },
 8089        );
 8090        let save = editor
 8091            .update_in(cx, |editor, window, cx| {
 8092                editor.save(true, project.clone(), window, cx)
 8093            })
 8094            .unwrap();
 8095        cx.executor().advance_clock(super::FORMAT_TIMEOUT);
 8096        cx.executor().start_waiting();
 8097        save.await;
 8098        assert_eq!(
 8099            editor.update(cx, |editor, cx| editor.text(cx)),
 8100            "one\ntwo\nthree\n"
 8101        );
 8102    }
 8103
 8104    // For non-dirty buffer, no formatting request should be sent
 8105    {
 8106        assert!(!cx.read(|cx| editor.is_dirty(cx)));
 8107
 8108        fake_server.set_request_handler::<lsp::request::Formatting, _, _>(move |_, _| async move {
 8109            panic!("Should not be invoked on non-dirty buffer");
 8110        });
 8111        let save = editor
 8112            .update_in(cx, |editor, window, cx| {
 8113                editor.save(true, project.clone(), window, cx)
 8114            })
 8115            .unwrap();
 8116        cx.executor().start_waiting();
 8117        save.await;
 8118    }
 8119
 8120    // Set rust language override and assert overridden tabsize is sent to language server
 8121    update_test_language_settings(cx, |settings| {
 8122        settings.languages.insert(
 8123            "Rust".into(),
 8124            LanguageSettingsContent {
 8125                tab_size: NonZeroU32::new(8),
 8126                ..Default::default()
 8127            },
 8128        );
 8129    });
 8130
 8131    {
 8132        editor.update_in(cx, |editor, window, cx| {
 8133            editor.set_text("somehting_new\n", window, cx)
 8134        });
 8135        assert!(cx.read(|cx| editor.is_dirty(cx)));
 8136        let _formatting_request_signal = fake_server
 8137            .set_request_handler::<lsp::request::Formatting, _, _>(move |params, _| async move {
 8138                assert_eq!(
 8139                    params.text_document.uri,
 8140                    lsp::Url::from_file_path(path!("/file.rs")).unwrap()
 8141                );
 8142                assert_eq!(params.options.tab_size, 8);
 8143                Ok(Some(vec![]))
 8144            });
 8145        let save = editor
 8146            .update_in(cx, |editor, window, cx| {
 8147                editor.save(true, project.clone(), window, cx)
 8148            })
 8149            .unwrap();
 8150        cx.executor().start_waiting();
 8151        save.await;
 8152    }
 8153}
 8154
 8155#[gpui::test]
 8156async fn test_multibuffer_format_during_save(cx: &mut TestAppContext) {
 8157    init_test(cx, |_| {});
 8158
 8159    let cols = 4;
 8160    let rows = 10;
 8161    let sample_text_1 = sample_text(rows, cols, 'a');
 8162    assert_eq!(
 8163        sample_text_1,
 8164        "aaaa\nbbbb\ncccc\ndddd\neeee\nffff\ngggg\nhhhh\niiii\njjjj"
 8165    );
 8166    let sample_text_2 = sample_text(rows, cols, 'l');
 8167    assert_eq!(
 8168        sample_text_2,
 8169        "llll\nmmmm\nnnnn\noooo\npppp\nqqqq\nrrrr\nssss\ntttt\nuuuu"
 8170    );
 8171    let sample_text_3 = sample_text(rows, cols, 'v');
 8172    assert_eq!(
 8173        sample_text_3,
 8174        "vvvv\nwwww\nxxxx\nyyyy\nzzzz\n{{{{\n||||\n}}}}\n~~~~\n\u{7f}\u{7f}\u{7f}\u{7f}"
 8175    );
 8176
 8177    let fs = FakeFs::new(cx.executor());
 8178    fs.insert_tree(
 8179        path!("/a"),
 8180        json!({
 8181            "main.rs": sample_text_1,
 8182            "other.rs": sample_text_2,
 8183            "lib.rs": sample_text_3,
 8184        }),
 8185    )
 8186    .await;
 8187
 8188    let project = Project::test(fs, [path!("/a").as_ref()], cx).await;
 8189    let workspace = cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
 8190    let cx = &mut VisualTestContext::from_window(*workspace.deref(), cx);
 8191
 8192    let language_registry = project.read_with(cx, |project, _| project.languages().clone());
 8193    language_registry.add(rust_lang());
 8194    let mut fake_servers = language_registry.register_fake_lsp(
 8195        "Rust",
 8196        FakeLspAdapter {
 8197            capabilities: lsp::ServerCapabilities {
 8198                document_formatting_provider: Some(lsp::OneOf::Left(true)),
 8199                ..Default::default()
 8200            },
 8201            ..Default::default()
 8202        },
 8203    );
 8204
 8205    let worktree = project.update(cx, |project, cx| {
 8206        let mut worktrees = project.worktrees(cx).collect::<Vec<_>>();
 8207        assert_eq!(worktrees.len(), 1);
 8208        worktrees.pop().unwrap()
 8209    });
 8210    let worktree_id = worktree.update(cx, |worktree, _| worktree.id());
 8211
 8212    let buffer_1 = project
 8213        .update(cx, |project, cx| {
 8214            project.open_buffer((worktree_id, "main.rs"), cx)
 8215        })
 8216        .await
 8217        .unwrap();
 8218    let buffer_2 = project
 8219        .update(cx, |project, cx| {
 8220            project.open_buffer((worktree_id, "other.rs"), cx)
 8221        })
 8222        .await
 8223        .unwrap();
 8224    let buffer_3 = project
 8225        .update(cx, |project, cx| {
 8226            project.open_buffer((worktree_id, "lib.rs"), cx)
 8227        })
 8228        .await
 8229        .unwrap();
 8230
 8231    let multi_buffer = cx.new(|cx| {
 8232        let mut multi_buffer = MultiBuffer::new(ReadWrite);
 8233        multi_buffer.push_excerpts(
 8234            buffer_1.clone(),
 8235            [
 8236                ExcerptRange::new(Point::new(0, 0)..Point::new(3, 0)),
 8237                ExcerptRange::new(Point::new(5, 0)..Point::new(7, 0)),
 8238                ExcerptRange::new(Point::new(9, 0)..Point::new(10, 4)),
 8239            ],
 8240            cx,
 8241        );
 8242        multi_buffer.push_excerpts(
 8243            buffer_2.clone(),
 8244            [
 8245                ExcerptRange::new(Point::new(0, 0)..Point::new(3, 0)),
 8246                ExcerptRange::new(Point::new(5, 0)..Point::new(7, 0)),
 8247                ExcerptRange::new(Point::new(9, 0)..Point::new(10, 4)),
 8248            ],
 8249            cx,
 8250        );
 8251        multi_buffer.push_excerpts(
 8252            buffer_3.clone(),
 8253            [
 8254                ExcerptRange::new(Point::new(0, 0)..Point::new(3, 0)),
 8255                ExcerptRange::new(Point::new(5, 0)..Point::new(7, 0)),
 8256                ExcerptRange::new(Point::new(9, 0)..Point::new(10, 4)),
 8257            ],
 8258            cx,
 8259        );
 8260        multi_buffer
 8261    });
 8262    let multi_buffer_editor = cx.new_window_entity(|window, cx| {
 8263        Editor::new(
 8264            EditorMode::full(),
 8265            multi_buffer,
 8266            Some(project.clone()),
 8267            window,
 8268            cx,
 8269        )
 8270    });
 8271
 8272    multi_buffer_editor.update_in(cx, |editor, window, cx| {
 8273        editor.change_selections(Some(Autoscroll::Next), window, cx, |s| {
 8274            s.select_ranges(Some(1..2))
 8275        });
 8276        editor.insert("|one|two|three|", window, cx);
 8277    });
 8278    assert!(cx.read(|cx| multi_buffer_editor.is_dirty(cx)));
 8279    multi_buffer_editor.update_in(cx, |editor, window, cx| {
 8280        editor.change_selections(Some(Autoscroll::Next), window, cx, |s| {
 8281            s.select_ranges(Some(60..70))
 8282        });
 8283        editor.insert("|four|five|six|", window, cx);
 8284    });
 8285    assert!(cx.read(|cx| multi_buffer_editor.is_dirty(cx)));
 8286
 8287    // First two buffers should be edited, but not the third one.
 8288    assert_eq!(
 8289        multi_buffer_editor.update(cx, |editor, cx| editor.text(cx)),
 8290        "a|one|two|three|aa\nbbbb\ncccc\n\nffff\ngggg\n\njjjj\nllll\nmmmm\nnnnn|four|five|six|\nr\n\nuuuu\nvvvv\nwwww\nxxxx\n\n{{{{\n||||\n\n\u{7f}\u{7f}\u{7f}\u{7f}",
 8291    );
 8292    buffer_1.update(cx, |buffer, _| {
 8293        assert!(buffer.is_dirty());
 8294        assert_eq!(
 8295            buffer.text(),
 8296            "a|one|two|three|aa\nbbbb\ncccc\ndddd\neeee\nffff\ngggg\nhhhh\niiii\njjjj",
 8297        )
 8298    });
 8299    buffer_2.update(cx, |buffer, _| {
 8300        assert!(buffer.is_dirty());
 8301        assert_eq!(
 8302            buffer.text(),
 8303            "llll\nmmmm\nnnnn|four|five|six|oooo\npppp\nr\nssss\ntttt\nuuuu",
 8304        )
 8305    });
 8306    buffer_3.update(cx, |buffer, _| {
 8307        assert!(!buffer.is_dirty());
 8308        assert_eq!(buffer.text(), sample_text_3,)
 8309    });
 8310    cx.executor().run_until_parked();
 8311
 8312    cx.executor().start_waiting();
 8313    let save = multi_buffer_editor
 8314        .update_in(cx, |editor, window, cx| {
 8315            editor.save(true, project.clone(), window, cx)
 8316        })
 8317        .unwrap();
 8318
 8319    let fake_server = fake_servers.next().await.unwrap();
 8320    fake_server
 8321        .server
 8322        .on_request::<lsp::request::Formatting, _, _>(move |params, _| async move {
 8323            Ok(Some(vec![lsp::TextEdit::new(
 8324                lsp::Range::new(lsp::Position::new(0, 3), lsp::Position::new(1, 0)),
 8325                format!("[{} formatted]", params.text_document.uri),
 8326            )]))
 8327        })
 8328        .detach();
 8329    save.await;
 8330
 8331    // After multibuffer saving, only first two buffers should be reformatted, but not the third one (as it was not dirty).
 8332    assert!(cx.read(|cx| !multi_buffer_editor.is_dirty(cx)));
 8333    assert_eq!(
 8334        multi_buffer_editor.update(cx, |editor, cx| editor.text(cx)),
 8335        uri!(
 8336            "a|o[file:///a/main.rs formatted]bbbb\ncccc\n\nffff\ngggg\n\njjjj\n\nlll[file:///a/other.rs formatted]mmmm\nnnnn|four|five|six|\nr\n\nuuuu\n\nvvvv\nwwww\nxxxx\n\n{{{{\n||||\n\n\u{7f}\u{7f}\u{7f}\u{7f}"
 8337        ),
 8338    );
 8339    buffer_1.update(cx, |buffer, _| {
 8340        assert!(!buffer.is_dirty());
 8341        assert_eq!(
 8342            buffer.text(),
 8343            uri!("a|o[file:///a/main.rs formatted]bbbb\ncccc\ndddd\neeee\nffff\ngggg\nhhhh\niiii\njjjj\n"),
 8344        )
 8345    });
 8346    buffer_2.update(cx, |buffer, _| {
 8347        assert!(!buffer.is_dirty());
 8348        assert_eq!(
 8349            buffer.text(),
 8350            uri!("lll[file:///a/other.rs formatted]mmmm\nnnnn|four|five|six|oooo\npppp\nr\nssss\ntttt\nuuuu\n"),
 8351        )
 8352    });
 8353    buffer_3.update(cx, |buffer, _| {
 8354        assert!(!buffer.is_dirty());
 8355        assert_eq!(buffer.text(), sample_text_3,)
 8356    });
 8357}
 8358
 8359#[gpui::test]
 8360async fn test_range_format_during_save(cx: &mut TestAppContext) {
 8361    init_test(cx, |_| {});
 8362
 8363    let fs = FakeFs::new(cx.executor());
 8364    fs.insert_file(path!("/file.rs"), Default::default()).await;
 8365
 8366    let project = Project::test(fs, [path!("/").as_ref()], cx).await;
 8367
 8368    let language_registry = project.read_with(cx, |project, _| project.languages().clone());
 8369    language_registry.add(rust_lang());
 8370    let mut fake_servers = language_registry.register_fake_lsp(
 8371        "Rust",
 8372        FakeLspAdapter {
 8373            capabilities: lsp::ServerCapabilities {
 8374                document_range_formatting_provider: Some(lsp::OneOf::Left(true)),
 8375                ..Default::default()
 8376            },
 8377            ..Default::default()
 8378        },
 8379    );
 8380
 8381    let buffer = project
 8382        .update(cx, |project, cx| {
 8383            project.open_local_buffer(path!("/file.rs"), cx)
 8384        })
 8385        .await
 8386        .unwrap();
 8387
 8388    let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 8389    let (editor, cx) = cx.add_window_view(|window, cx| {
 8390        build_editor_with_project(project.clone(), buffer, window, cx)
 8391    });
 8392    editor.update_in(cx, |editor, window, cx| {
 8393        editor.set_text("one\ntwo\nthree\n", window, cx)
 8394    });
 8395    assert!(cx.read(|cx| editor.is_dirty(cx)));
 8396
 8397    cx.executor().start_waiting();
 8398    let fake_server = fake_servers.next().await.unwrap();
 8399
 8400    let save = editor
 8401        .update_in(cx, |editor, window, cx| {
 8402            editor.save(true, project.clone(), window, cx)
 8403        })
 8404        .unwrap();
 8405    fake_server
 8406        .set_request_handler::<lsp::request::RangeFormatting, _, _>(move |params, _| async move {
 8407            assert_eq!(
 8408                params.text_document.uri,
 8409                lsp::Url::from_file_path(path!("/file.rs")).unwrap()
 8410            );
 8411            assert_eq!(params.options.tab_size, 4);
 8412            Ok(Some(vec![lsp::TextEdit::new(
 8413                lsp::Range::new(lsp::Position::new(0, 3), lsp::Position::new(1, 0)),
 8414                ", ".to_string(),
 8415            )]))
 8416        })
 8417        .next()
 8418        .await;
 8419    cx.executor().start_waiting();
 8420    save.await;
 8421    assert_eq!(
 8422        editor.update(cx, |editor, cx| editor.text(cx)),
 8423        "one, two\nthree\n"
 8424    );
 8425    assert!(!cx.read(|cx| editor.is_dirty(cx)));
 8426
 8427    editor.update_in(cx, |editor, window, cx| {
 8428        editor.set_text("one\ntwo\nthree\n", window, cx)
 8429    });
 8430    assert!(cx.read(|cx| editor.is_dirty(cx)));
 8431
 8432    // Ensure we can still save even if formatting hangs.
 8433    fake_server.set_request_handler::<lsp::request::RangeFormatting, _, _>(
 8434        move |params, _| async move {
 8435            assert_eq!(
 8436                params.text_document.uri,
 8437                lsp::Url::from_file_path(path!("/file.rs")).unwrap()
 8438            );
 8439            futures::future::pending::<()>().await;
 8440            unreachable!()
 8441        },
 8442    );
 8443    let save = editor
 8444        .update_in(cx, |editor, window, cx| {
 8445            editor.save(true, project.clone(), window, cx)
 8446        })
 8447        .unwrap();
 8448    cx.executor().advance_clock(super::FORMAT_TIMEOUT);
 8449    cx.executor().start_waiting();
 8450    save.await;
 8451    assert_eq!(
 8452        editor.update(cx, |editor, cx| editor.text(cx)),
 8453        "one\ntwo\nthree\n"
 8454    );
 8455    assert!(!cx.read(|cx| editor.is_dirty(cx)));
 8456
 8457    // For non-dirty buffer, no formatting request should be sent
 8458    let save = editor
 8459        .update_in(cx, |editor, window, cx| {
 8460            editor.save(true, project.clone(), window, cx)
 8461        })
 8462        .unwrap();
 8463    let _pending_format_request = fake_server
 8464        .set_request_handler::<lsp::request::RangeFormatting, _, _>(move |_, _| async move {
 8465            panic!("Should not be invoked on non-dirty buffer");
 8466        })
 8467        .next();
 8468    cx.executor().start_waiting();
 8469    save.await;
 8470
 8471    // Set Rust language override and assert overridden tabsize is sent to language server
 8472    update_test_language_settings(cx, |settings| {
 8473        settings.languages.insert(
 8474            "Rust".into(),
 8475            LanguageSettingsContent {
 8476                tab_size: NonZeroU32::new(8),
 8477                ..Default::default()
 8478            },
 8479        );
 8480    });
 8481
 8482    editor.update_in(cx, |editor, window, cx| {
 8483        editor.set_text("somehting_new\n", window, cx)
 8484    });
 8485    assert!(cx.read(|cx| editor.is_dirty(cx)));
 8486    let save = editor
 8487        .update_in(cx, |editor, window, cx| {
 8488            editor.save(true, project.clone(), window, cx)
 8489        })
 8490        .unwrap();
 8491    fake_server
 8492        .set_request_handler::<lsp::request::RangeFormatting, _, _>(move |params, _| async move {
 8493            assert_eq!(
 8494                params.text_document.uri,
 8495                lsp::Url::from_file_path(path!("/file.rs")).unwrap()
 8496            );
 8497            assert_eq!(params.options.tab_size, 8);
 8498            Ok(Some(vec![]))
 8499        })
 8500        .next()
 8501        .await;
 8502    cx.executor().start_waiting();
 8503    save.await;
 8504}
 8505
 8506#[gpui::test]
 8507async fn test_document_format_manual_trigger(cx: &mut TestAppContext) {
 8508    init_test(cx, |settings| {
 8509        settings.defaults.formatter = Some(language_settings::SelectedFormatter::List(
 8510            FormatterList(vec![Formatter::LanguageServer { name: None }].into()),
 8511        ))
 8512    });
 8513
 8514    let fs = FakeFs::new(cx.executor());
 8515    fs.insert_file(path!("/file.rs"), Default::default()).await;
 8516
 8517    let project = Project::test(fs, [path!("/").as_ref()], cx).await;
 8518
 8519    let language_registry = project.read_with(cx, |project, _| project.languages().clone());
 8520    language_registry.add(Arc::new(Language::new(
 8521        LanguageConfig {
 8522            name: "Rust".into(),
 8523            matcher: LanguageMatcher {
 8524                path_suffixes: vec!["rs".to_string()],
 8525                ..Default::default()
 8526            },
 8527            ..LanguageConfig::default()
 8528        },
 8529        Some(tree_sitter_rust::LANGUAGE.into()),
 8530    )));
 8531    update_test_language_settings(cx, |settings| {
 8532        // Enable Prettier formatting for the same buffer, and ensure
 8533        // LSP is called instead of Prettier.
 8534        settings.defaults.prettier = Some(PrettierSettings {
 8535            allowed: true,
 8536            ..PrettierSettings::default()
 8537        });
 8538    });
 8539    let mut fake_servers = language_registry.register_fake_lsp(
 8540        "Rust",
 8541        FakeLspAdapter {
 8542            capabilities: lsp::ServerCapabilities {
 8543                document_formatting_provider: Some(lsp::OneOf::Left(true)),
 8544                ..Default::default()
 8545            },
 8546            ..Default::default()
 8547        },
 8548    );
 8549
 8550    let buffer = project
 8551        .update(cx, |project, cx| {
 8552            project.open_local_buffer(path!("/file.rs"), cx)
 8553        })
 8554        .await
 8555        .unwrap();
 8556
 8557    let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 8558    let (editor, cx) = cx.add_window_view(|window, cx| {
 8559        build_editor_with_project(project.clone(), buffer, window, cx)
 8560    });
 8561    editor.update_in(cx, |editor, window, cx| {
 8562        editor.set_text("one\ntwo\nthree\n", window, cx)
 8563    });
 8564
 8565    cx.executor().start_waiting();
 8566    let fake_server = fake_servers.next().await.unwrap();
 8567
 8568    let format = editor
 8569        .update_in(cx, |editor, window, cx| {
 8570            editor.perform_format(
 8571                project.clone(),
 8572                FormatTrigger::Manual,
 8573                FormatTarget::Buffers,
 8574                window,
 8575                cx,
 8576            )
 8577        })
 8578        .unwrap();
 8579    fake_server
 8580        .set_request_handler::<lsp::request::Formatting, _, _>(move |params, _| async move {
 8581            assert_eq!(
 8582                params.text_document.uri,
 8583                lsp::Url::from_file_path(path!("/file.rs")).unwrap()
 8584            );
 8585            assert_eq!(params.options.tab_size, 4);
 8586            Ok(Some(vec![lsp::TextEdit::new(
 8587                lsp::Range::new(lsp::Position::new(0, 3), lsp::Position::new(1, 0)),
 8588                ", ".to_string(),
 8589            )]))
 8590        })
 8591        .next()
 8592        .await;
 8593    cx.executor().start_waiting();
 8594    format.await;
 8595    assert_eq!(
 8596        editor.update(cx, |editor, cx| editor.text(cx)),
 8597        "one, two\nthree\n"
 8598    );
 8599
 8600    editor.update_in(cx, |editor, window, cx| {
 8601        editor.set_text("one\ntwo\nthree\n", window, cx)
 8602    });
 8603    // Ensure we don't lock if formatting hangs.
 8604    fake_server.set_request_handler::<lsp::request::Formatting, _, _>(
 8605        move |params, _| async move {
 8606            assert_eq!(
 8607                params.text_document.uri,
 8608                lsp::Url::from_file_path(path!("/file.rs")).unwrap()
 8609            );
 8610            futures::future::pending::<()>().await;
 8611            unreachable!()
 8612        },
 8613    );
 8614    let format = editor
 8615        .update_in(cx, |editor, window, cx| {
 8616            editor.perform_format(
 8617                project,
 8618                FormatTrigger::Manual,
 8619                FormatTarget::Buffers,
 8620                window,
 8621                cx,
 8622            )
 8623        })
 8624        .unwrap();
 8625    cx.executor().advance_clock(super::FORMAT_TIMEOUT);
 8626    cx.executor().start_waiting();
 8627    format.await;
 8628    assert_eq!(
 8629        editor.update(cx, |editor, cx| editor.text(cx)),
 8630        "one\ntwo\nthree\n"
 8631    );
 8632}
 8633
 8634#[gpui::test]
 8635async fn test_multiple_formatters(cx: &mut TestAppContext) {
 8636    init_test(cx, |settings| {
 8637        settings.defaults.remove_trailing_whitespace_on_save = Some(true);
 8638        settings.defaults.formatter =
 8639            Some(language_settings::SelectedFormatter::List(FormatterList(
 8640                vec![
 8641                    Formatter::LanguageServer { name: None },
 8642                    Formatter::CodeActions(
 8643                        [
 8644                            ("code-action-1".into(), true),
 8645                            ("code-action-2".into(), true),
 8646                        ]
 8647                        .into_iter()
 8648                        .collect(),
 8649                    ),
 8650                ]
 8651                .into(),
 8652            )))
 8653    });
 8654
 8655    let fs = FakeFs::new(cx.executor());
 8656    fs.insert_file(path!("/file.rs"), "one  \ntwo   \nthree".into())
 8657        .await;
 8658
 8659    let project = Project::test(fs, [path!("/").as_ref()], cx).await;
 8660    let language_registry = project.read_with(cx, |project, _| project.languages().clone());
 8661    language_registry.add(rust_lang());
 8662
 8663    let mut fake_servers = language_registry.register_fake_lsp(
 8664        "Rust",
 8665        FakeLspAdapter {
 8666            capabilities: lsp::ServerCapabilities {
 8667                document_formatting_provider: Some(lsp::OneOf::Left(true)),
 8668                execute_command_provider: Some(lsp::ExecuteCommandOptions {
 8669                    commands: vec!["the-command-for-code-action-1".into()],
 8670                    ..Default::default()
 8671                }),
 8672                code_action_provider: Some(lsp::CodeActionProviderCapability::Simple(true)),
 8673                ..Default::default()
 8674            },
 8675            ..Default::default()
 8676        },
 8677    );
 8678
 8679    let buffer = project
 8680        .update(cx, |project, cx| {
 8681            project.open_local_buffer(path!("/file.rs"), cx)
 8682        })
 8683        .await
 8684        .unwrap();
 8685
 8686    let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 8687    let (editor, cx) = cx.add_window_view(|window, cx| {
 8688        build_editor_with_project(project.clone(), buffer, window, cx)
 8689    });
 8690
 8691    cx.executor().start_waiting();
 8692
 8693    let fake_server = fake_servers.next().await.unwrap();
 8694    fake_server.set_request_handler::<lsp::request::Formatting, _, _>(
 8695        move |_params, _| async move {
 8696            Ok(Some(vec![lsp::TextEdit::new(
 8697                lsp::Range::new(lsp::Position::new(0, 0), lsp::Position::new(0, 0)),
 8698                "applied-formatting\n".to_string(),
 8699            )]))
 8700        },
 8701    );
 8702    fake_server.set_request_handler::<lsp::request::CodeActionRequest, _, _>(
 8703        move |params, _| async move {
 8704            assert_eq!(
 8705                params.context.only,
 8706                Some(vec!["code-action-1".into(), "code-action-2".into()])
 8707            );
 8708            let uri = lsp::Url::from_file_path(path!("/file.rs")).unwrap();
 8709            Ok(Some(vec![
 8710                lsp::CodeActionOrCommand::CodeAction(lsp::CodeAction {
 8711                    kind: Some("code-action-1".into()),
 8712                    edit: Some(lsp::WorkspaceEdit::new(
 8713                        [(
 8714                            uri.clone(),
 8715                            vec![lsp::TextEdit::new(
 8716                                lsp::Range::new(lsp::Position::new(0, 0), lsp::Position::new(0, 0)),
 8717                                "applied-code-action-1-edit\n".to_string(),
 8718                            )],
 8719                        )]
 8720                        .into_iter()
 8721                        .collect(),
 8722                    )),
 8723                    command: Some(lsp::Command {
 8724                        command: "the-command-for-code-action-1".into(),
 8725                        ..Default::default()
 8726                    }),
 8727                    ..Default::default()
 8728                }),
 8729                lsp::CodeActionOrCommand::CodeAction(lsp::CodeAction {
 8730                    kind: Some("code-action-2".into()),
 8731                    edit: Some(lsp::WorkspaceEdit::new(
 8732                        [(
 8733                            uri.clone(),
 8734                            vec![lsp::TextEdit::new(
 8735                                lsp::Range::new(lsp::Position::new(0, 0), lsp::Position::new(0, 0)),
 8736                                "applied-code-action-2-edit\n".to_string(),
 8737                            )],
 8738                        )]
 8739                        .into_iter()
 8740                        .collect(),
 8741                    )),
 8742                    ..Default::default()
 8743                }),
 8744            ]))
 8745        },
 8746    );
 8747
 8748    fake_server.set_request_handler::<lsp::request::CodeActionResolveRequest, _, _>({
 8749        move |params, _| async move { Ok(params) }
 8750    });
 8751
 8752    let command_lock = Arc::new(futures::lock::Mutex::new(()));
 8753    fake_server.set_request_handler::<lsp::request::ExecuteCommand, _, _>({
 8754        let fake = fake_server.clone();
 8755        let lock = command_lock.clone();
 8756        move |params, _| {
 8757            assert_eq!(params.command, "the-command-for-code-action-1");
 8758            let fake = fake.clone();
 8759            let lock = lock.clone();
 8760            async move {
 8761                lock.lock().await;
 8762                fake.server
 8763                    .request::<lsp::request::ApplyWorkspaceEdit>(lsp::ApplyWorkspaceEditParams {
 8764                        label: None,
 8765                        edit: lsp::WorkspaceEdit {
 8766                            changes: Some(
 8767                                [(
 8768                                    lsp::Url::from_file_path(path!("/file.rs")).unwrap(),
 8769                                    vec![lsp::TextEdit {
 8770                                        range: lsp::Range::new(
 8771                                            lsp::Position::new(0, 0),
 8772                                            lsp::Position::new(0, 0),
 8773                                        ),
 8774                                        new_text: "applied-code-action-1-command\n".into(),
 8775                                    }],
 8776                                )]
 8777                                .into_iter()
 8778                                .collect(),
 8779                            ),
 8780                            ..Default::default()
 8781                        },
 8782                    })
 8783                    .await
 8784                    .unwrap();
 8785                Ok(Some(json!(null)))
 8786            }
 8787        }
 8788    });
 8789
 8790    cx.executor().start_waiting();
 8791    editor
 8792        .update_in(cx, |editor, window, cx| {
 8793            editor.perform_format(
 8794                project.clone(),
 8795                FormatTrigger::Manual,
 8796                FormatTarget::Buffers,
 8797                window,
 8798                cx,
 8799            )
 8800        })
 8801        .unwrap()
 8802        .await;
 8803    editor.update(cx, |editor, cx| {
 8804        assert_eq!(
 8805            editor.text(cx),
 8806            r#"
 8807                applied-code-action-2-edit
 8808                applied-code-action-1-command
 8809                applied-code-action-1-edit
 8810                applied-formatting
 8811                one
 8812                two
 8813                three
 8814            "#
 8815            .unindent()
 8816        );
 8817    });
 8818
 8819    editor.update_in(cx, |editor, window, cx| {
 8820        editor.undo(&Default::default(), window, cx);
 8821        assert_eq!(editor.text(cx), "one  \ntwo   \nthree");
 8822    });
 8823
 8824    // Perform a manual edit while waiting for an LSP command
 8825    // that's being run as part of a formatting code action.
 8826    let lock_guard = command_lock.lock().await;
 8827    let format = editor
 8828        .update_in(cx, |editor, window, cx| {
 8829            editor.perform_format(
 8830                project.clone(),
 8831                FormatTrigger::Manual,
 8832                FormatTarget::Buffers,
 8833                window,
 8834                cx,
 8835            )
 8836        })
 8837        .unwrap();
 8838    cx.run_until_parked();
 8839    editor.update(cx, |editor, cx| {
 8840        assert_eq!(
 8841            editor.text(cx),
 8842            r#"
 8843                applied-code-action-1-edit
 8844                applied-formatting
 8845                one
 8846                two
 8847                three
 8848            "#
 8849            .unindent()
 8850        );
 8851
 8852        editor.buffer.update(cx, |buffer, cx| {
 8853            let ix = buffer.len(cx);
 8854            buffer.edit([(ix..ix, "edited\n")], None, cx);
 8855        });
 8856    });
 8857
 8858    // Allow the LSP command to proceed. Because the buffer was edited,
 8859    // the second code action will not be run.
 8860    drop(lock_guard);
 8861    format.await;
 8862    editor.update_in(cx, |editor, window, cx| {
 8863        assert_eq!(
 8864            editor.text(cx),
 8865            r#"
 8866                applied-code-action-1-command
 8867                applied-code-action-1-edit
 8868                applied-formatting
 8869                one
 8870                two
 8871                three
 8872                edited
 8873            "#
 8874            .unindent()
 8875        );
 8876
 8877        // The manual edit is undone first, because it is the last thing the user did
 8878        // (even though the command completed afterwards).
 8879        editor.undo(&Default::default(), window, cx);
 8880        assert_eq!(
 8881            editor.text(cx),
 8882            r#"
 8883                applied-code-action-1-command
 8884                applied-code-action-1-edit
 8885                applied-formatting
 8886                one
 8887                two
 8888                three
 8889            "#
 8890            .unindent()
 8891        );
 8892
 8893        // All the formatting (including the command, which completed after the manual edit)
 8894        // is undone together.
 8895        editor.undo(&Default::default(), window, cx);
 8896        assert_eq!(editor.text(cx), "one  \ntwo   \nthree");
 8897    });
 8898}
 8899
 8900#[gpui::test]
 8901async fn test_organize_imports_manual_trigger(cx: &mut TestAppContext) {
 8902    init_test(cx, |settings| {
 8903        settings.defaults.formatter = Some(language_settings::SelectedFormatter::List(
 8904            FormatterList(vec![Formatter::LanguageServer { name: None }].into()),
 8905        ))
 8906    });
 8907
 8908    let fs = FakeFs::new(cx.executor());
 8909    fs.insert_file(path!("/file.ts"), Default::default()).await;
 8910
 8911    let project = Project::test(fs, [path!("/").as_ref()], cx).await;
 8912
 8913    let language_registry = project.read_with(cx, |project, _| project.languages().clone());
 8914    language_registry.add(Arc::new(Language::new(
 8915        LanguageConfig {
 8916            name: "TypeScript".into(),
 8917            matcher: LanguageMatcher {
 8918                path_suffixes: vec!["ts".to_string()],
 8919                ..Default::default()
 8920            },
 8921            ..LanguageConfig::default()
 8922        },
 8923        Some(tree_sitter_typescript::LANGUAGE_TYPESCRIPT.into()),
 8924    )));
 8925    update_test_language_settings(cx, |settings| {
 8926        settings.defaults.prettier = Some(PrettierSettings {
 8927            allowed: true,
 8928            ..PrettierSettings::default()
 8929        });
 8930    });
 8931    let mut fake_servers = language_registry.register_fake_lsp(
 8932        "TypeScript",
 8933        FakeLspAdapter {
 8934            capabilities: lsp::ServerCapabilities {
 8935                code_action_provider: Some(lsp::CodeActionProviderCapability::Simple(true)),
 8936                ..Default::default()
 8937            },
 8938            ..Default::default()
 8939        },
 8940    );
 8941
 8942    let buffer = project
 8943        .update(cx, |project, cx| {
 8944            project.open_local_buffer(path!("/file.ts"), cx)
 8945        })
 8946        .await
 8947        .unwrap();
 8948
 8949    let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 8950    let (editor, cx) = cx.add_window_view(|window, cx| {
 8951        build_editor_with_project(project.clone(), buffer, window, cx)
 8952    });
 8953    editor.update_in(cx, |editor, window, cx| {
 8954        editor.set_text(
 8955            "import { a } from 'module';\nimport { b } from 'module';\n\nconst x = a;\n",
 8956            window,
 8957            cx,
 8958        )
 8959    });
 8960
 8961    cx.executor().start_waiting();
 8962    let fake_server = fake_servers.next().await.unwrap();
 8963
 8964    let format = editor
 8965        .update_in(cx, |editor, window, cx| {
 8966            editor.perform_code_action_kind(
 8967                project.clone(),
 8968                CodeActionKind::SOURCE_ORGANIZE_IMPORTS,
 8969                window,
 8970                cx,
 8971            )
 8972        })
 8973        .unwrap();
 8974    fake_server
 8975        .set_request_handler::<lsp::request::CodeActionRequest, _, _>(move |params, _| async move {
 8976            assert_eq!(
 8977                params.text_document.uri,
 8978                lsp::Url::from_file_path(path!("/file.ts")).unwrap()
 8979            );
 8980            Ok(Some(vec![lsp::CodeActionOrCommand::CodeAction(
 8981                lsp::CodeAction {
 8982                    title: "Organize Imports".to_string(),
 8983                    kind: Some(lsp::CodeActionKind::SOURCE_ORGANIZE_IMPORTS),
 8984                    edit: Some(lsp::WorkspaceEdit {
 8985                        changes: Some(
 8986                            [(
 8987                                params.text_document.uri.clone(),
 8988                                vec![lsp::TextEdit::new(
 8989                                    lsp::Range::new(
 8990                                        lsp::Position::new(1, 0),
 8991                                        lsp::Position::new(2, 0),
 8992                                    ),
 8993                                    "".to_string(),
 8994                                )],
 8995                            )]
 8996                            .into_iter()
 8997                            .collect(),
 8998                        ),
 8999                        ..Default::default()
 9000                    }),
 9001                    ..Default::default()
 9002                },
 9003            )]))
 9004        })
 9005        .next()
 9006        .await;
 9007    cx.executor().start_waiting();
 9008    format.await;
 9009    assert_eq!(
 9010        editor.update(cx, |editor, cx| editor.text(cx)),
 9011        "import { a } from 'module';\n\nconst x = a;\n"
 9012    );
 9013
 9014    editor.update_in(cx, |editor, window, cx| {
 9015        editor.set_text(
 9016            "import { a } from 'module';\nimport { b } from 'module';\n\nconst x = a;\n",
 9017            window,
 9018            cx,
 9019        )
 9020    });
 9021    // Ensure we don't lock if code action hangs.
 9022    fake_server.set_request_handler::<lsp::request::CodeActionRequest, _, _>(
 9023        move |params, _| async move {
 9024            assert_eq!(
 9025                params.text_document.uri,
 9026                lsp::Url::from_file_path(path!("/file.ts")).unwrap()
 9027            );
 9028            futures::future::pending::<()>().await;
 9029            unreachable!()
 9030        },
 9031    );
 9032    let format = editor
 9033        .update_in(cx, |editor, window, cx| {
 9034            editor.perform_code_action_kind(
 9035                project,
 9036                CodeActionKind::SOURCE_ORGANIZE_IMPORTS,
 9037                window,
 9038                cx,
 9039            )
 9040        })
 9041        .unwrap();
 9042    cx.executor().advance_clock(super::CODE_ACTION_TIMEOUT);
 9043    cx.executor().start_waiting();
 9044    format.await;
 9045    assert_eq!(
 9046        editor.update(cx, |editor, cx| editor.text(cx)),
 9047        "import { a } from 'module';\nimport { b } from 'module';\n\nconst x = a;\n"
 9048    );
 9049}
 9050
 9051#[gpui::test]
 9052async fn test_concurrent_format_requests(cx: &mut TestAppContext) {
 9053    init_test(cx, |_| {});
 9054
 9055    let mut cx = EditorLspTestContext::new_rust(
 9056        lsp::ServerCapabilities {
 9057            document_formatting_provider: Some(lsp::OneOf::Left(true)),
 9058            ..Default::default()
 9059        },
 9060        cx,
 9061    )
 9062    .await;
 9063
 9064    cx.set_state(indoc! {"
 9065        one.twoˇ
 9066    "});
 9067
 9068    // The format request takes a long time. When it completes, it inserts
 9069    // a newline and an indent before the `.`
 9070    cx.lsp
 9071        .set_request_handler::<lsp::request::Formatting, _, _>(move |_, cx| {
 9072            let executor = cx.background_executor().clone();
 9073            async move {
 9074                executor.timer(Duration::from_millis(100)).await;
 9075                Ok(Some(vec![lsp::TextEdit {
 9076                    range: lsp::Range::new(lsp::Position::new(0, 3), lsp::Position::new(0, 3)),
 9077                    new_text: "\n    ".into(),
 9078                }]))
 9079            }
 9080        });
 9081
 9082    // Submit a format request.
 9083    let format_1 = cx
 9084        .update_editor(|editor, window, cx| editor.format(&Format, window, cx))
 9085        .unwrap();
 9086    cx.executor().run_until_parked();
 9087
 9088    // Submit a second format request.
 9089    let format_2 = cx
 9090        .update_editor(|editor, window, cx| editor.format(&Format, window, cx))
 9091        .unwrap();
 9092    cx.executor().run_until_parked();
 9093
 9094    // Wait for both format requests to complete
 9095    cx.executor().advance_clock(Duration::from_millis(200));
 9096    cx.executor().start_waiting();
 9097    format_1.await.unwrap();
 9098    cx.executor().start_waiting();
 9099    format_2.await.unwrap();
 9100
 9101    // The formatting edits only happens once.
 9102    cx.assert_editor_state(indoc! {"
 9103        one
 9104            .twoˇ
 9105    "});
 9106}
 9107
 9108#[gpui::test]
 9109async fn test_strip_whitespace_and_format_via_lsp(cx: &mut TestAppContext) {
 9110    init_test(cx, |settings| {
 9111        settings.defaults.formatter = Some(language_settings::SelectedFormatter::Auto)
 9112    });
 9113
 9114    let mut cx = EditorLspTestContext::new_rust(
 9115        lsp::ServerCapabilities {
 9116            document_formatting_provider: Some(lsp::OneOf::Left(true)),
 9117            ..Default::default()
 9118        },
 9119        cx,
 9120    )
 9121    .await;
 9122
 9123    // Set up a buffer white some trailing whitespace and no trailing newline.
 9124    cx.set_state(
 9125        &[
 9126            "one ",   //
 9127            "twoˇ",   //
 9128            "three ", //
 9129            "four",   //
 9130        ]
 9131        .join("\n"),
 9132    );
 9133
 9134    // Submit a format request.
 9135    let format = cx
 9136        .update_editor(|editor, window, cx| editor.format(&Format, window, cx))
 9137        .unwrap();
 9138
 9139    // Record which buffer changes have been sent to the language server
 9140    let buffer_changes = Arc::new(Mutex::new(Vec::new()));
 9141    cx.lsp
 9142        .handle_notification::<lsp::notification::DidChangeTextDocument, _>({
 9143            let buffer_changes = buffer_changes.clone();
 9144            move |params, _| {
 9145                buffer_changes.lock().extend(
 9146                    params
 9147                        .content_changes
 9148                        .into_iter()
 9149                        .map(|e| (e.range.unwrap(), e.text)),
 9150                );
 9151            }
 9152        });
 9153
 9154    // Handle formatting requests to the language server.
 9155    cx.lsp
 9156        .set_request_handler::<lsp::request::Formatting, _, _>({
 9157            let buffer_changes = buffer_changes.clone();
 9158            move |_, _| {
 9159                // When formatting is requested, trailing whitespace has already been stripped,
 9160                // and the trailing newline has already been added.
 9161                assert_eq!(
 9162                    &buffer_changes.lock()[1..],
 9163                    &[
 9164                        (
 9165                            lsp::Range::new(lsp::Position::new(0, 3), lsp::Position::new(0, 4)),
 9166                            "".into()
 9167                        ),
 9168                        (
 9169                            lsp::Range::new(lsp::Position::new(2, 5), lsp::Position::new(2, 6)),
 9170                            "".into()
 9171                        ),
 9172                        (
 9173                            lsp::Range::new(lsp::Position::new(3, 4), lsp::Position::new(3, 4)),
 9174                            "\n".into()
 9175                        ),
 9176                    ]
 9177                );
 9178
 9179                // Insert blank lines between each line of the buffer.
 9180                async move {
 9181                    Ok(Some(vec![
 9182                        lsp::TextEdit {
 9183                            range: lsp::Range::new(
 9184                                lsp::Position::new(1, 0),
 9185                                lsp::Position::new(1, 0),
 9186                            ),
 9187                            new_text: "\n".into(),
 9188                        },
 9189                        lsp::TextEdit {
 9190                            range: lsp::Range::new(
 9191                                lsp::Position::new(2, 0),
 9192                                lsp::Position::new(2, 0),
 9193                            ),
 9194                            new_text: "\n".into(),
 9195                        },
 9196                    ]))
 9197                }
 9198            }
 9199        });
 9200
 9201    // After formatting the buffer, the trailing whitespace is stripped,
 9202    // a newline is appended, and the edits provided by the language server
 9203    // have been applied.
 9204    format.await.unwrap();
 9205    cx.assert_editor_state(
 9206        &[
 9207            "one",   //
 9208            "",      //
 9209            "twoˇ",  //
 9210            "",      //
 9211            "three", //
 9212            "four",  //
 9213            "",      //
 9214        ]
 9215        .join("\n"),
 9216    );
 9217
 9218    // Undoing the formatting undoes the trailing whitespace removal, the
 9219    // trailing newline, and the LSP edits.
 9220    cx.update_buffer(|buffer, cx| buffer.undo(cx));
 9221    cx.assert_editor_state(
 9222        &[
 9223            "one ",   //
 9224            "twoˇ",   //
 9225            "three ", //
 9226            "four",   //
 9227        ]
 9228        .join("\n"),
 9229    );
 9230}
 9231
 9232#[gpui::test]
 9233async fn test_handle_input_for_show_signature_help_auto_signature_help_true(
 9234    cx: &mut TestAppContext,
 9235) {
 9236    init_test(cx, |_| {});
 9237
 9238    cx.update(|cx| {
 9239        cx.update_global::<SettingsStore, _>(|settings, cx| {
 9240            settings.update_user_settings::<EditorSettings>(cx, |settings| {
 9241                settings.auto_signature_help = Some(true);
 9242            });
 9243        });
 9244    });
 9245
 9246    let mut cx = EditorLspTestContext::new_rust(
 9247        lsp::ServerCapabilities {
 9248            signature_help_provider: Some(lsp::SignatureHelpOptions {
 9249                ..Default::default()
 9250            }),
 9251            ..Default::default()
 9252        },
 9253        cx,
 9254    )
 9255    .await;
 9256
 9257    let language = Language::new(
 9258        LanguageConfig {
 9259            name: "Rust".into(),
 9260            brackets: BracketPairConfig {
 9261                pairs: vec![
 9262                    BracketPair {
 9263                        start: "{".to_string(),
 9264                        end: "}".to_string(),
 9265                        close: true,
 9266                        surround: true,
 9267                        newline: true,
 9268                    },
 9269                    BracketPair {
 9270                        start: "(".to_string(),
 9271                        end: ")".to_string(),
 9272                        close: true,
 9273                        surround: true,
 9274                        newline: true,
 9275                    },
 9276                    BracketPair {
 9277                        start: "/*".to_string(),
 9278                        end: " */".to_string(),
 9279                        close: true,
 9280                        surround: true,
 9281                        newline: true,
 9282                    },
 9283                    BracketPair {
 9284                        start: "[".to_string(),
 9285                        end: "]".to_string(),
 9286                        close: false,
 9287                        surround: false,
 9288                        newline: true,
 9289                    },
 9290                    BracketPair {
 9291                        start: "\"".to_string(),
 9292                        end: "\"".to_string(),
 9293                        close: true,
 9294                        surround: true,
 9295                        newline: false,
 9296                    },
 9297                    BracketPair {
 9298                        start: "<".to_string(),
 9299                        end: ">".to_string(),
 9300                        close: false,
 9301                        surround: true,
 9302                        newline: true,
 9303                    },
 9304                ],
 9305                ..Default::default()
 9306            },
 9307            autoclose_before: "})]".to_string(),
 9308            ..Default::default()
 9309        },
 9310        Some(tree_sitter_rust::LANGUAGE.into()),
 9311    );
 9312    let language = Arc::new(language);
 9313
 9314    cx.language_registry().add(language.clone());
 9315    cx.update_buffer(|buffer, cx| {
 9316        buffer.set_language(Some(language), cx);
 9317    });
 9318
 9319    cx.set_state(
 9320        &r#"
 9321            fn main() {
 9322                sampleˇ
 9323            }
 9324        "#
 9325        .unindent(),
 9326    );
 9327
 9328    cx.update_editor(|editor, window, cx| {
 9329        editor.handle_input("(", window, cx);
 9330    });
 9331    cx.assert_editor_state(
 9332        &"
 9333            fn main() {
 9334                sample(ˇ)
 9335            }
 9336        "
 9337        .unindent(),
 9338    );
 9339
 9340    let mocked_response = lsp::SignatureHelp {
 9341        signatures: vec![lsp::SignatureInformation {
 9342            label: "fn sample(param1: u8, param2: u8)".to_string(),
 9343            documentation: None,
 9344            parameters: Some(vec![
 9345                lsp::ParameterInformation {
 9346                    label: lsp::ParameterLabel::Simple("param1: u8".to_string()),
 9347                    documentation: None,
 9348                },
 9349                lsp::ParameterInformation {
 9350                    label: lsp::ParameterLabel::Simple("param2: u8".to_string()),
 9351                    documentation: None,
 9352                },
 9353            ]),
 9354            active_parameter: None,
 9355        }],
 9356        active_signature: Some(0),
 9357        active_parameter: Some(0),
 9358    };
 9359    handle_signature_help_request(&mut cx, mocked_response).await;
 9360
 9361    cx.condition(|editor, _| editor.signature_help_state.is_shown())
 9362        .await;
 9363
 9364    cx.editor(|editor, _, _| {
 9365        let signature_help_state = editor.signature_help_state.popover().cloned();
 9366        assert_eq!(
 9367            signature_help_state.unwrap().label,
 9368            "param1: u8, param2: u8"
 9369        );
 9370    });
 9371}
 9372
 9373#[gpui::test]
 9374async fn test_handle_input_with_different_show_signature_settings(cx: &mut TestAppContext) {
 9375    init_test(cx, |_| {});
 9376
 9377    cx.update(|cx| {
 9378        cx.update_global::<SettingsStore, _>(|settings, cx| {
 9379            settings.update_user_settings::<EditorSettings>(cx, |settings| {
 9380                settings.auto_signature_help = Some(false);
 9381                settings.show_signature_help_after_edits = Some(false);
 9382            });
 9383        });
 9384    });
 9385
 9386    let mut cx = EditorLspTestContext::new_rust(
 9387        lsp::ServerCapabilities {
 9388            signature_help_provider: Some(lsp::SignatureHelpOptions {
 9389                ..Default::default()
 9390            }),
 9391            ..Default::default()
 9392        },
 9393        cx,
 9394    )
 9395    .await;
 9396
 9397    let language = Language::new(
 9398        LanguageConfig {
 9399            name: "Rust".into(),
 9400            brackets: BracketPairConfig {
 9401                pairs: vec![
 9402                    BracketPair {
 9403                        start: "{".to_string(),
 9404                        end: "}".to_string(),
 9405                        close: true,
 9406                        surround: true,
 9407                        newline: true,
 9408                    },
 9409                    BracketPair {
 9410                        start: "(".to_string(),
 9411                        end: ")".to_string(),
 9412                        close: true,
 9413                        surround: true,
 9414                        newline: true,
 9415                    },
 9416                    BracketPair {
 9417                        start: "/*".to_string(),
 9418                        end: " */".to_string(),
 9419                        close: true,
 9420                        surround: true,
 9421                        newline: true,
 9422                    },
 9423                    BracketPair {
 9424                        start: "[".to_string(),
 9425                        end: "]".to_string(),
 9426                        close: false,
 9427                        surround: false,
 9428                        newline: true,
 9429                    },
 9430                    BracketPair {
 9431                        start: "\"".to_string(),
 9432                        end: "\"".to_string(),
 9433                        close: true,
 9434                        surround: true,
 9435                        newline: false,
 9436                    },
 9437                    BracketPair {
 9438                        start: "<".to_string(),
 9439                        end: ">".to_string(),
 9440                        close: false,
 9441                        surround: true,
 9442                        newline: true,
 9443                    },
 9444                ],
 9445                ..Default::default()
 9446            },
 9447            autoclose_before: "})]".to_string(),
 9448            ..Default::default()
 9449        },
 9450        Some(tree_sitter_rust::LANGUAGE.into()),
 9451    );
 9452    let language = Arc::new(language);
 9453
 9454    cx.language_registry().add(language.clone());
 9455    cx.update_buffer(|buffer, cx| {
 9456        buffer.set_language(Some(language), cx);
 9457    });
 9458
 9459    // Ensure that signature_help is not called when no signature help is enabled.
 9460    cx.set_state(
 9461        &r#"
 9462            fn main() {
 9463                sampleˇ
 9464            }
 9465        "#
 9466        .unindent(),
 9467    );
 9468    cx.update_editor(|editor, window, cx| {
 9469        editor.handle_input("(", window, cx);
 9470    });
 9471    cx.assert_editor_state(
 9472        &"
 9473            fn main() {
 9474                sample(ˇ)
 9475            }
 9476        "
 9477        .unindent(),
 9478    );
 9479    cx.editor(|editor, _, _| {
 9480        assert!(editor.signature_help_state.task().is_none());
 9481    });
 9482
 9483    let mocked_response = lsp::SignatureHelp {
 9484        signatures: vec![lsp::SignatureInformation {
 9485            label: "fn sample(param1: u8, param2: u8)".to_string(),
 9486            documentation: None,
 9487            parameters: Some(vec![
 9488                lsp::ParameterInformation {
 9489                    label: lsp::ParameterLabel::Simple("param1: u8".to_string()),
 9490                    documentation: None,
 9491                },
 9492                lsp::ParameterInformation {
 9493                    label: lsp::ParameterLabel::Simple("param2: u8".to_string()),
 9494                    documentation: None,
 9495                },
 9496            ]),
 9497            active_parameter: None,
 9498        }],
 9499        active_signature: Some(0),
 9500        active_parameter: Some(0),
 9501    };
 9502
 9503    // Ensure that signature_help is called when enabled afte edits
 9504    cx.update(|_, cx| {
 9505        cx.update_global::<SettingsStore, _>(|settings, cx| {
 9506            settings.update_user_settings::<EditorSettings>(cx, |settings| {
 9507                settings.auto_signature_help = Some(false);
 9508                settings.show_signature_help_after_edits = Some(true);
 9509            });
 9510        });
 9511    });
 9512    cx.set_state(
 9513        &r#"
 9514            fn main() {
 9515                sampleˇ
 9516            }
 9517        "#
 9518        .unindent(),
 9519    );
 9520    cx.update_editor(|editor, window, cx| {
 9521        editor.handle_input("(", window, cx);
 9522    });
 9523    cx.assert_editor_state(
 9524        &"
 9525            fn main() {
 9526                sample(ˇ)
 9527            }
 9528        "
 9529        .unindent(),
 9530    );
 9531    handle_signature_help_request(&mut cx, mocked_response.clone()).await;
 9532    cx.condition(|editor, _| editor.signature_help_state.is_shown())
 9533        .await;
 9534    cx.update_editor(|editor, _, _| {
 9535        let signature_help_state = editor.signature_help_state.popover().cloned();
 9536        assert!(signature_help_state.is_some());
 9537        assert_eq!(
 9538            signature_help_state.unwrap().label,
 9539            "param1: u8, param2: u8"
 9540        );
 9541        editor.signature_help_state = SignatureHelpState::default();
 9542    });
 9543
 9544    // Ensure that signature_help is called when auto signature help override is enabled
 9545    cx.update(|_, cx| {
 9546        cx.update_global::<SettingsStore, _>(|settings, cx| {
 9547            settings.update_user_settings::<EditorSettings>(cx, |settings| {
 9548                settings.auto_signature_help = Some(true);
 9549                settings.show_signature_help_after_edits = Some(false);
 9550            });
 9551        });
 9552    });
 9553    cx.set_state(
 9554        &r#"
 9555            fn main() {
 9556                sampleˇ
 9557            }
 9558        "#
 9559        .unindent(),
 9560    );
 9561    cx.update_editor(|editor, window, cx| {
 9562        editor.handle_input("(", window, cx);
 9563    });
 9564    cx.assert_editor_state(
 9565        &"
 9566            fn main() {
 9567                sample(ˇ)
 9568            }
 9569        "
 9570        .unindent(),
 9571    );
 9572    handle_signature_help_request(&mut cx, mocked_response).await;
 9573    cx.condition(|editor, _| editor.signature_help_state.is_shown())
 9574        .await;
 9575    cx.editor(|editor, _, _| {
 9576        let signature_help_state = editor.signature_help_state.popover().cloned();
 9577        assert!(signature_help_state.is_some());
 9578        assert_eq!(
 9579            signature_help_state.unwrap().label,
 9580            "param1: u8, param2: u8"
 9581        );
 9582    });
 9583}
 9584
 9585#[gpui::test]
 9586async fn test_signature_help(cx: &mut TestAppContext) {
 9587    init_test(cx, |_| {});
 9588    cx.update(|cx| {
 9589        cx.update_global::<SettingsStore, _>(|settings, cx| {
 9590            settings.update_user_settings::<EditorSettings>(cx, |settings| {
 9591                settings.auto_signature_help = Some(true);
 9592            });
 9593        });
 9594    });
 9595
 9596    let mut cx = EditorLspTestContext::new_rust(
 9597        lsp::ServerCapabilities {
 9598            signature_help_provider: Some(lsp::SignatureHelpOptions {
 9599                ..Default::default()
 9600            }),
 9601            ..Default::default()
 9602        },
 9603        cx,
 9604    )
 9605    .await;
 9606
 9607    // A test that directly calls `show_signature_help`
 9608    cx.update_editor(|editor, window, cx| {
 9609        editor.show_signature_help(&ShowSignatureHelp, window, cx);
 9610    });
 9611
 9612    let mocked_response = lsp::SignatureHelp {
 9613        signatures: vec![lsp::SignatureInformation {
 9614            label: "fn sample(param1: u8, param2: u8)".to_string(),
 9615            documentation: None,
 9616            parameters: Some(vec![
 9617                lsp::ParameterInformation {
 9618                    label: lsp::ParameterLabel::Simple("param1: u8".to_string()),
 9619                    documentation: None,
 9620                },
 9621                lsp::ParameterInformation {
 9622                    label: lsp::ParameterLabel::Simple("param2: u8".to_string()),
 9623                    documentation: None,
 9624                },
 9625            ]),
 9626            active_parameter: None,
 9627        }],
 9628        active_signature: Some(0),
 9629        active_parameter: Some(0),
 9630    };
 9631    handle_signature_help_request(&mut cx, mocked_response).await;
 9632
 9633    cx.condition(|editor, _| editor.signature_help_state.is_shown())
 9634        .await;
 9635
 9636    cx.editor(|editor, _, _| {
 9637        let signature_help_state = editor.signature_help_state.popover().cloned();
 9638        assert!(signature_help_state.is_some());
 9639        assert_eq!(
 9640            signature_help_state.unwrap().label,
 9641            "param1: u8, param2: u8"
 9642        );
 9643    });
 9644
 9645    // When exiting outside from inside the brackets, `signature_help` is closed.
 9646    cx.set_state(indoc! {"
 9647        fn main() {
 9648            sample(ˇ);
 9649        }
 9650
 9651        fn sample(param1: u8, param2: u8) {}
 9652    "});
 9653
 9654    cx.update_editor(|editor, window, cx| {
 9655        editor.change_selections(None, window, cx, |s| s.select_ranges([0..0]));
 9656    });
 9657
 9658    let mocked_response = lsp::SignatureHelp {
 9659        signatures: Vec::new(),
 9660        active_signature: None,
 9661        active_parameter: None,
 9662    };
 9663    handle_signature_help_request(&mut cx, mocked_response).await;
 9664
 9665    cx.condition(|editor, _| !editor.signature_help_state.is_shown())
 9666        .await;
 9667
 9668    cx.editor(|editor, _, _| {
 9669        assert!(!editor.signature_help_state.is_shown());
 9670    });
 9671
 9672    // When entering inside the brackets from outside, `show_signature_help` is automatically called.
 9673    cx.set_state(indoc! {"
 9674        fn main() {
 9675            sample(ˇ);
 9676        }
 9677
 9678        fn sample(param1: u8, param2: u8) {}
 9679    "});
 9680
 9681    let mocked_response = lsp::SignatureHelp {
 9682        signatures: vec![lsp::SignatureInformation {
 9683            label: "fn sample(param1: u8, param2: u8)".to_string(),
 9684            documentation: None,
 9685            parameters: Some(vec![
 9686                lsp::ParameterInformation {
 9687                    label: lsp::ParameterLabel::Simple("param1: u8".to_string()),
 9688                    documentation: None,
 9689                },
 9690                lsp::ParameterInformation {
 9691                    label: lsp::ParameterLabel::Simple("param2: u8".to_string()),
 9692                    documentation: None,
 9693                },
 9694            ]),
 9695            active_parameter: None,
 9696        }],
 9697        active_signature: Some(0),
 9698        active_parameter: Some(0),
 9699    };
 9700    handle_signature_help_request(&mut cx, mocked_response.clone()).await;
 9701    cx.condition(|editor, _| editor.signature_help_state.is_shown())
 9702        .await;
 9703    cx.editor(|editor, _, _| {
 9704        assert!(editor.signature_help_state.is_shown());
 9705    });
 9706
 9707    // Restore the popover with more parameter input
 9708    cx.set_state(indoc! {"
 9709        fn main() {
 9710            sample(param1, param2ˇ);
 9711        }
 9712
 9713        fn sample(param1: u8, param2: u8) {}
 9714    "});
 9715
 9716    let mocked_response = lsp::SignatureHelp {
 9717        signatures: vec![lsp::SignatureInformation {
 9718            label: "fn sample(param1: u8, param2: u8)".to_string(),
 9719            documentation: None,
 9720            parameters: Some(vec![
 9721                lsp::ParameterInformation {
 9722                    label: lsp::ParameterLabel::Simple("param1: u8".to_string()),
 9723                    documentation: None,
 9724                },
 9725                lsp::ParameterInformation {
 9726                    label: lsp::ParameterLabel::Simple("param2: u8".to_string()),
 9727                    documentation: None,
 9728                },
 9729            ]),
 9730            active_parameter: None,
 9731        }],
 9732        active_signature: Some(0),
 9733        active_parameter: Some(1),
 9734    };
 9735    handle_signature_help_request(&mut cx, mocked_response.clone()).await;
 9736    cx.condition(|editor, _| editor.signature_help_state.is_shown())
 9737        .await;
 9738
 9739    // When selecting a range, the popover is gone.
 9740    // Avoid using `cx.set_state` to not actually edit the document, just change its selections.
 9741    cx.update_editor(|editor, window, cx| {
 9742        editor.change_selections(None, window, cx, |s| {
 9743            s.select_ranges(Some(Point::new(1, 25)..Point::new(1, 19)));
 9744        })
 9745    });
 9746    cx.assert_editor_state(indoc! {"
 9747        fn main() {
 9748            sample(param1, «ˇparam2»);
 9749        }
 9750
 9751        fn sample(param1: u8, param2: u8) {}
 9752    "});
 9753    cx.editor(|editor, _, _| {
 9754        assert!(!editor.signature_help_state.is_shown());
 9755    });
 9756
 9757    // When unselecting again, the popover is back if within the brackets.
 9758    cx.update_editor(|editor, window, cx| {
 9759        editor.change_selections(None, window, cx, |s| {
 9760            s.select_ranges(Some(Point::new(1, 19)..Point::new(1, 19)));
 9761        })
 9762    });
 9763    cx.assert_editor_state(indoc! {"
 9764        fn main() {
 9765            sample(param1, ˇparam2);
 9766        }
 9767
 9768        fn sample(param1: u8, param2: u8) {}
 9769    "});
 9770    handle_signature_help_request(&mut cx, mocked_response).await;
 9771    cx.condition(|editor, _| editor.signature_help_state.is_shown())
 9772        .await;
 9773    cx.editor(|editor, _, _| {
 9774        assert!(editor.signature_help_state.is_shown());
 9775    });
 9776
 9777    // Test to confirm that SignatureHelp does not appear after deselecting multiple ranges when it was hidden by pressing Escape.
 9778    cx.update_editor(|editor, window, cx| {
 9779        editor.change_selections(None, window, cx, |s| {
 9780            s.select_ranges(Some(Point::new(0, 0)..Point::new(0, 0)));
 9781            s.select_ranges(Some(Point::new(1, 19)..Point::new(1, 19)));
 9782        })
 9783    });
 9784    cx.assert_editor_state(indoc! {"
 9785        fn main() {
 9786            sample(param1, ˇparam2);
 9787        }
 9788
 9789        fn sample(param1: u8, param2: u8) {}
 9790    "});
 9791
 9792    let mocked_response = lsp::SignatureHelp {
 9793        signatures: vec![lsp::SignatureInformation {
 9794            label: "fn sample(param1: u8, param2: u8)".to_string(),
 9795            documentation: None,
 9796            parameters: Some(vec![
 9797                lsp::ParameterInformation {
 9798                    label: lsp::ParameterLabel::Simple("param1: u8".to_string()),
 9799                    documentation: None,
 9800                },
 9801                lsp::ParameterInformation {
 9802                    label: lsp::ParameterLabel::Simple("param2: u8".to_string()),
 9803                    documentation: None,
 9804                },
 9805            ]),
 9806            active_parameter: None,
 9807        }],
 9808        active_signature: Some(0),
 9809        active_parameter: Some(1),
 9810    };
 9811    handle_signature_help_request(&mut cx, mocked_response.clone()).await;
 9812    cx.condition(|editor, _| editor.signature_help_state.is_shown())
 9813        .await;
 9814    cx.update_editor(|editor, _, cx| {
 9815        editor.hide_signature_help(cx, SignatureHelpHiddenBy::Escape);
 9816    });
 9817    cx.condition(|editor, _| !editor.signature_help_state.is_shown())
 9818        .await;
 9819    cx.update_editor(|editor, window, cx| {
 9820        editor.change_selections(None, window, cx, |s| {
 9821            s.select_ranges(Some(Point::new(1, 25)..Point::new(1, 19)));
 9822        })
 9823    });
 9824    cx.assert_editor_state(indoc! {"
 9825        fn main() {
 9826            sample(param1, «ˇparam2»);
 9827        }
 9828
 9829        fn sample(param1: u8, param2: u8) {}
 9830    "});
 9831    cx.update_editor(|editor, window, cx| {
 9832        editor.change_selections(None, window, cx, |s| {
 9833            s.select_ranges(Some(Point::new(1, 19)..Point::new(1, 19)));
 9834        })
 9835    });
 9836    cx.assert_editor_state(indoc! {"
 9837        fn main() {
 9838            sample(param1, ˇparam2);
 9839        }
 9840
 9841        fn sample(param1: u8, param2: u8) {}
 9842    "});
 9843    cx.condition(|editor, _| !editor.signature_help_state.is_shown()) // because hidden by escape
 9844        .await;
 9845}
 9846
 9847#[gpui::test]
 9848async fn test_completion_mode(cx: &mut TestAppContext) {
 9849    init_test(cx, |_| {});
 9850    let mut cx = EditorLspTestContext::new_rust(
 9851        lsp::ServerCapabilities {
 9852            completion_provider: Some(lsp::CompletionOptions {
 9853                resolve_provider: Some(true),
 9854                ..Default::default()
 9855            }),
 9856            ..Default::default()
 9857        },
 9858        cx,
 9859    )
 9860    .await;
 9861
 9862    struct Run {
 9863        run_description: &'static str,
 9864        initial_state: String,
 9865        buffer_marked_text: String,
 9866        completion_text: &'static str,
 9867        expected_with_insert_mode: String,
 9868        expected_with_replace_mode: String,
 9869        expected_with_replace_subsequence_mode: String,
 9870        expected_with_replace_suffix_mode: String,
 9871    }
 9872
 9873    let runs = [
 9874        Run {
 9875            run_description: "Start of word matches completion text",
 9876            initial_state: "before ediˇ after".into(),
 9877            buffer_marked_text: "before <edi|> after".into(),
 9878            completion_text: "editor",
 9879            expected_with_insert_mode: "before editorˇ after".into(),
 9880            expected_with_replace_mode: "before editorˇ after".into(),
 9881            expected_with_replace_subsequence_mode: "before editorˇ after".into(),
 9882            expected_with_replace_suffix_mode: "before editorˇ after".into(),
 9883        },
 9884        Run {
 9885            run_description: "Accept same text at the middle of the word",
 9886            initial_state: "before ediˇtor after".into(),
 9887            buffer_marked_text: "before <edi|tor> after".into(),
 9888            completion_text: "editor",
 9889            expected_with_insert_mode: "before editorˇtor after".into(),
 9890            expected_with_replace_mode: "before editorˇ after".into(),
 9891            expected_with_replace_subsequence_mode: "before editorˇ after".into(),
 9892            expected_with_replace_suffix_mode: "before editorˇ after".into(),
 9893        },
 9894        Run {
 9895            run_description: "End of word matches completion text -- cursor at end",
 9896            initial_state: "before torˇ after".into(),
 9897            buffer_marked_text: "before <tor|> after".into(),
 9898            completion_text: "editor",
 9899            expected_with_insert_mode: "before editorˇ after".into(),
 9900            expected_with_replace_mode: "before editorˇ after".into(),
 9901            expected_with_replace_subsequence_mode: "before editorˇ after".into(),
 9902            expected_with_replace_suffix_mode: "before editorˇ after".into(),
 9903        },
 9904        Run {
 9905            run_description: "End of word matches completion text -- cursor at start",
 9906            initial_state: "before ˇtor after".into(),
 9907            buffer_marked_text: "before <|tor> after".into(),
 9908            completion_text: "editor",
 9909            expected_with_insert_mode: "before editorˇtor after".into(),
 9910            expected_with_replace_mode: "before editorˇ after".into(),
 9911            expected_with_replace_subsequence_mode: "before editorˇ after".into(),
 9912            expected_with_replace_suffix_mode: "before editorˇ after".into(),
 9913        },
 9914        Run {
 9915            run_description: "Prepend text containing whitespace",
 9916            initial_state: "pˇfield: bool".into(),
 9917            buffer_marked_text: "<p|field>: bool".into(),
 9918            completion_text: "pub ",
 9919            expected_with_insert_mode: "pub ˇfield: bool".into(),
 9920            expected_with_replace_mode: "pub ˇ: bool".into(),
 9921            expected_with_replace_subsequence_mode: "pub ˇfield: bool".into(),
 9922            expected_with_replace_suffix_mode: "pub ˇfield: bool".into(),
 9923        },
 9924        Run {
 9925            run_description: "Add element to start of list",
 9926            initial_state: "[element_ˇelement_2]".into(),
 9927            buffer_marked_text: "[<element_|element_2>]".into(),
 9928            completion_text: "element_1",
 9929            expected_with_insert_mode: "[element_1ˇelement_2]".into(),
 9930            expected_with_replace_mode: "[element_1ˇ]".into(),
 9931            expected_with_replace_subsequence_mode: "[element_1ˇelement_2]".into(),
 9932            expected_with_replace_suffix_mode: "[element_1ˇelement_2]".into(),
 9933        },
 9934        Run {
 9935            run_description: "Add element to start of list -- first and second elements are equal",
 9936            initial_state: "[elˇelement]".into(),
 9937            buffer_marked_text: "[<el|element>]".into(),
 9938            completion_text: "element",
 9939            expected_with_insert_mode: "[elementˇelement]".into(),
 9940            expected_with_replace_mode: "[elementˇ]".into(),
 9941            expected_with_replace_subsequence_mode: "[elementˇelement]".into(),
 9942            expected_with_replace_suffix_mode: "[elementˇ]".into(),
 9943        },
 9944        Run {
 9945            run_description: "Ends with matching suffix",
 9946            initial_state: "SubˇError".into(),
 9947            buffer_marked_text: "<Sub|Error>".into(),
 9948            completion_text: "SubscriptionError",
 9949            expected_with_insert_mode: "SubscriptionErrorˇError".into(),
 9950            expected_with_replace_mode: "SubscriptionErrorˇ".into(),
 9951            expected_with_replace_subsequence_mode: "SubscriptionErrorˇ".into(),
 9952            expected_with_replace_suffix_mode: "SubscriptionErrorˇ".into(),
 9953        },
 9954        Run {
 9955            run_description: "Suffix is a subsequence -- contiguous",
 9956            initial_state: "SubˇErr".into(),
 9957            buffer_marked_text: "<Sub|Err>".into(),
 9958            completion_text: "SubscriptionError",
 9959            expected_with_insert_mode: "SubscriptionErrorˇErr".into(),
 9960            expected_with_replace_mode: "SubscriptionErrorˇ".into(),
 9961            expected_with_replace_subsequence_mode: "SubscriptionErrorˇ".into(),
 9962            expected_with_replace_suffix_mode: "SubscriptionErrorˇErr".into(),
 9963        },
 9964        Run {
 9965            run_description: "Suffix is a subsequence -- non-contiguous -- replace intended",
 9966            initial_state: "Suˇscrirr".into(),
 9967            buffer_marked_text: "<Su|scrirr>".into(),
 9968            completion_text: "SubscriptionError",
 9969            expected_with_insert_mode: "SubscriptionErrorˇscrirr".into(),
 9970            expected_with_replace_mode: "SubscriptionErrorˇ".into(),
 9971            expected_with_replace_subsequence_mode: "SubscriptionErrorˇ".into(),
 9972            expected_with_replace_suffix_mode: "SubscriptionErrorˇscrirr".into(),
 9973        },
 9974        Run {
 9975            run_description: "Suffix is a subsequence -- non-contiguous -- replace unintended",
 9976            initial_state: "foo(indˇix)".into(),
 9977            buffer_marked_text: "foo(<ind|ix>)".into(),
 9978            completion_text: "node_index",
 9979            expected_with_insert_mode: "foo(node_indexˇix)".into(),
 9980            expected_with_replace_mode: "foo(node_indexˇ)".into(),
 9981            expected_with_replace_subsequence_mode: "foo(node_indexˇix)".into(),
 9982            expected_with_replace_suffix_mode: "foo(node_indexˇix)".into(),
 9983        },
 9984    ];
 9985
 9986    for run in runs {
 9987        let run_variations = [
 9988            (LspInsertMode::Insert, run.expected_with_insert_mode),
 9989            (LspInsertMode::Replace, run.expected_with_replace_mode),
 9990            (
 9991                LspInsertMode::ReplaceSubsequence,
 9992                run.expected_with_replace_subsequence_mode,
 9993            ),
 9994            (
 9995                LspInsertMode::ReplaceSuffix,
 9996                run.expected_with_replace_suffix_mode,
 9997            ),
 9998        ];
 9999
10000        for (lsp_insert_mode, expected_text) in run_variations {
10001            eprintln!(
10002                "run = {:?}, mode = {lsp_insert_mode:.?}",
10003                run.run_description,
10004            );
10005
10006            update_test_language_settings(&mut cx, |settings| {
10007                settings.defaults.completions = Some(CompletionSettings {
10008                    lsp_insert_mode,
10009                    words: WordsCompletionMode::Disabled,
10010                    lsp: true,
10011                    lsp_fetch_timeout_ms: 0,
10012                });
10013            });
10014
10015            cx.set_state(&run.initial_state);
10016            cx.update_editor(|editor, window, cx| {
10017                editor.show_completions(&ShowCompletions { trigger: None }, window, cx);
10018            });
10019
10020            let counter = Arc::new(AtomicUsize::new(0));
10021            handle_completion_request_with_insert_and_replace(
10022                &mut cx,
10023                &run.buffer_marked_text,
10024                vec![run.completion_text],
10025                counter.clone(),
10026            )
10027            .await;
10028            cx.condition(|editor, _| editor.context_menu_visible())
10029                .await;
10030            assert_eq!(counter.load(atomic::Ordering::Acquire), 1);
10031
10032            let apply_additional_edits = cx.update_editor(|editor, window, cx| {
10033                editor
10034                    .confirm_completion(&ConfirmCompletion::default(), window, cx)
10035                    .unwrap()
10036            });
10037            cx.assert_editor_state(&expected_text);
10038            handle_resolve_completion_request(&mut cx, None).await;
10039            apply_additional_edits.await.unwrap();
10040        }
10041    }
10042}
10043
10044#[gpui::test]
10045async fn test_completion_with_mode_specified_by_action(cx: &mut TestAppContext) {
10046    init_test(cx, |_| {});
10047    let mut cx = EditorLspTestContext::new_rust(
10048        lsp::ServerCapabilities {
10049            completion_provider: Some(lsp::CompletionOptions {
10050                resolve_provider: Some(true),
10051                ..Default::default()
10052            }),
10053            ..Default::default()
10054        },
10055        cx,
10056    )
10057    .await;
10058
10059    let initial_state = "SubˇError";
10060    let buffer_marked_text = "<Sub|Error>";
10061    let completion_text = "SubscriptionError";
10062    let expected_with_insert_mode = "SubscriptionErrorˇError";
10063    let expected_with_replace_mode = "SubscriptionErrorˇ";
10064
10065    update_test_language_settings(&mut cx, |settings| {
10066        settings.defaults.completions = Some(CompletionSettings {
10067            words: WordsCompletionMode::Disabled,
10068            // set the opposite here to ensure that the action is overriding the default behavior
10069            lsp_insert_mode: LspInsertMode::Insert,
10070            lsp: true,
10071            lsp_fetch_timeout_ms: 0,
10072        });
10073    });
10074
10075    cx.set_state(initial_state);
10076    cx.update_editor(|editor, window, cx| {
10077        editor.show_completions(&ShowCompletions { trigger: None }, window, cx);
10078    });
10079
10080    let counter = Arc::new(AtomicUsize::new(0));
10081    handle_completion_request_with_insert_and_replace(
10082        &mut cx,
10083        &buffer_marked_text,
10084        vec![completion_text],
10085        counter.clone(),
10086    )
10087    .await;
10088    cx.condition(|editor, _| editor.context_menu_visible())
10089        .await;
10090    assert_eq!(counter.load(atomic::Ordering::Acquire), 1);
10091
10092    let apply_additional_edits = cx.update_editor(|editor, window, cx| {
10093        editor
10094            .confirm_completion_replace(&ConfirmCompletionReplace, window, cx)
10095            .unwrap()
10096    });
10097    cx.assert_editor_state(&expected_with_replace_mode);
10098    handle_resolve_completion_request(&mut cx, None).await;
10099    apply_additional_edits.await.unwrap();
10100
10101    update_test_language_settings(&mut cx, |settings| {
10102        settings.defaults.completions = Some(CompletionSettings {
10103            words: WordsCompletionMode::Disabled,
10104            // set the opposite here to ensure that the action is overriding the default behavior
10105            lsp_insert_mode: LspInsertMode::Replace,
10106            lsp: true,
10107            lsp_fetch_timeout_ms: 0,
10108        });
10109    });
10110
10111    cx.set_state(initial_state);
10112    cx.update_editor(|editor, window, cx| {
10113        editor.show_completions(&ShowCompletions { trigger: None }, window, cx);
10114    });
10115    handle_completion_request_with_insert_and_replace(
10116        &mut cx,
10117        &buffer_marked_text,
10118        vec![completion_text],
10119        counter.clone(),
10120    )
10121    .await;
10122    cx.condition(|editor, _| editor.context_menu_visible())
10123        .await;
10124    assert_eq!(counter.load(atomic::Ordering::Acquire), 2);
10125
10126    let apply_additional_edits = cx.update_editor(|editor, window, cx| {
10127        editor
10128            .confirm_completion_insert(&ConfirmCompletionInsert, window, cx)
10129            .unwrap()
10130    });
10131    cx.assert_editor_state(&expected_with_insert_mode);
10132    handle_resolve_completion_request(&mut cx, None).await;
10133    apply_additional_edits.await.unwrap();
10134}
10135
10136#[gpui::test]
10137async fn test_completion_replacing_surrounding_text_with_multicursors(cx: &mut TestAppContext) {
10138    init_test(cx, |_| {});
10139    let mut cx = EditorLspTestContext::new_rust(
10140        lsp::ServerCapabilities {
10141            completion_provider: Some(lsp::CompletionOptions {
10142                resolve_provider: Some(true),
10143                ..Default::default()
10144            }),
10145            ..Default::default()
10146        },
10147        cx,
10148    )
10149    .await;
10150
10151    // scenario: surrounding text matches completion text
10152    let completion_text = "to_offset";
10153    let initial_state = indoc! {"
10154        1. buf.to_offˇsuffix
10155        2. buf.to_offˇsuf
10156        3. buf.to_offˇfix
10157        4. buf.to_offˇ
10158        5. into_offˇensive
10159        6. ˇsuffix
10160        7. let ˇ //
10161        8. aaˇzz
10162        9. buf.to_off«zzzzzˇ»suffix
10163        10. buf.«ˇzzzzz»suffix
10164        11. to_off«ˇzzzzz»
10165
10166        buf.to_offˇsuffix  // newest cursor
10167    "};
10168    let completion_marked_buffer = indoc! {"
10169        1. buf.to_offsuffix
10170        2. buf.to_offsuf
10171        3. buf.to_offfix
10172        4. buf.to_off
10173        5. into_offensive
10174        6. suffix
10175        7. let  //
10176        8. aazz
10177        9. buf.to_offzzzzzsuffix
10178        10. buf.zzzzzsuffix
10179        11. to_offzzzzz
10180
10181        buf.<to_off|suffix>  // newest cursor
10182    "};
10183    let expected = indoc! {"
10184        1. buf.to_offsetˇ
10185        2. buf.to_offsetˇsuf
10186        3. buf.to_offsetˇfix
10187        4. buf.to_offsetˇ
10188        5. into_offsetˇensive
10189        6. to_offsetˇsuffix
10190        7. let to_offsetˇ //
10191        8. aato_offsetˇzz
10192        9. buf.to_offsetˇ
10193        10. buf.to_offsetˇsuffix
10194        11. to_offsetˇ
10195
10196        buf.to_offsetˇ  // newest cursor
10197    "};
10198    cx.set_state(initial_state);
10199    cx.update_editor(|editor, window, cx| {
10200        editor.show_completions(&ShowCompletions { trigger: None }, window, cx);
10201    });
10202    handle_completion_request_with_insert_and_replace(
10203        &mut cx,
10204        completion_marked_buffer,
10205        vec![completion_text],
10206        Arc::new(AtomicUsize::new(0)),
10207    )
10208    .await;
10209    cx.condition(|editor, _| editor.context_menu_visible())
10210        .await;
10211    let apply_additional_edits = cx.update_editor(|editor, window, cx| {
10212        editor
10213            .confirm_completion_replace(&ConfirmCompletionReplace, window, cx)
10214            .unwrap()
10215    });
10216    cx.assert_editor_state(expected);
10217    handle_resolve_completion_request(&mut cx, None).await;
10218    apply_additional_edits.await.unwrap();
10219
10220    // scenario: surrounding text matches surroundings of newest cursor, inserting at the end
10221    let completion_text = "foo_and_bar";
10222    let initial_state = indoc! {"
10223        1. ooanbˇ
10224        2. zooanbˇ
10225        3. ooanbˇz
10226        4. zooanbˇz
10227        5. ooanˇ
10228        6. oanbˇ
10229
10230        ooanbˇ
10231    "};
10232    let completion_marked_buffer = indoc! {"
10233        1. ooanb
10234        2. zooanb
10235        3. ooanbz
10236        4. zooanbz
10237        5. ooan
10238        6. oanb
10239
10240        <ooanb|>
10241    "};
10242    let expected = indoc! {"
10243        1. foo_and_barˇ
10244        2. zfoo_and_barˇ
10245        3. foo_and_barˇz
10246        4. zfoo_and_barˇz
10247        5. ooanfoo_and_barˇ
10248        6. oanbfoo_and_barˇ
10249
10250        foo_and_barˇ
10251    "};
10252    cx.set_state(initial_state);
10253    cx.update_editor(|editor, window, cx| {
10254        editor.show_completions(&ShowCompletions { trigger: None }, window, cx);
10255    });
10256    handle_completion_request_with_insert_and_replace(
10257        &mut cx,
10258        completion_marked_buffer,
10259        vec![completion_text],
10260        Arc::new(AtomicUsize::new(0)),
10261    )
10262    .await;
10263    cx.condition(|editor, _| editor.context_menu_visible())
10264        .await;
10265    let apply_additional_edits = cx.update_editor(|editor, window, cx| {
10266        editor
10267            .confirm_completion_replace(&ConfirmCompletionReplace, window, cx)
10268            .unwrap()
10269    });
10270    cx.assert_editor_state(expected);
10271    handle_resolve_completion_request(&mut cx, None).await;
10272    apply_additional_edits.await.unwrap();
10273
10274    // scenario: surrounding text matches surroundings of newest cursor, inserted at the middle
10275    // (expects the same as if it was inserted at the end)
10276    let completion_text = "foo_and_bar";
10277    let initial_state = indoc! {"
10278        1. ooˇanb
10279        2. zooˇanb
10280        3. ooˇanbz
10281        4. zooˇanbz
10282
10283        ooˇanb
10284    "};
10285    let completion_marked_buffer = indoc! {"
10286        1. ooanb
10287        2. zooanb
10288        3. ooanbz
10289        4. zooanbz
10290
10291        <oo|anb>
10292    "};
10293    let expected = indoc! {"
10294        1. foo_and_barˇ
10295        2. zfoo_and_barˇ
10296        3. foo_and_barˇz
10297        4. zfoo_and_barˇz
10298
10299        foo_and_barˇ
10300    "};
10301    cx.set_state(initial_state);
10302    cx.update_editor(|editor, window, cx| {
10303        editor.show_completions(&ShowCompletions { trigger: None }, window, cx);
10304    });
10305    handle_completion_request_with_insert_and_replace(
10306        &mut cx,
10307        completion_marked_buffer,
10308        vec![completion_text],
10309        Arc::new(AtomicUsize::new(0)),
10310    )
10311    .await;
10312    cx.condition(|editor, _| editor.context_menu_visible())
10313        .await;
10314    let apply_additional_edits = cx.update_editor(|editor, window, cx| {
10315        editor
10316            .confirm_completion_replace(&ConfirmCompletionReplace, window, cx)
10317            .unwrap()
10318    });
10319    cx.assert_editor_state(expected);
10320    handle_resolve_completion_request(&mut cx, None).await;
10321    apply_additional_edits.await.unwrap();
10322}
10323
10324// This used to crash
10325#[gpui::test]
10326async fn test_completion_in_multibuffer_with_replace_range(cx: &mut TestAppContext) {
10327    init_test(cx, |_| {});
10328
10329    let buffer_text = indoc! {"
10330        fn main() {
10331            10.satu;
10332
10333            //
10334            // separate cursors so they open in different excerpts (manually reproducible)
10335            //
10336
10337            10.satu20;
10338        }
10339    "};
10340    let multibuffer_text_with_selections = indoc! {"
10341        fn main() {
10342            10.satuˇ;
10343
10344            //
10345
10346            //
10347
10348            10.satuˇ20;
10349        }
10350    "};
10351    let expected_multibuffer = indoc! {"
10352        fn main() {
10353            10.saturating_sub()ˇ;
10354
10355            //
10356
10357            //
10358
10359            10.saturating_sub()ˇ;
10360        }
10361    "};
10362
10363    let first_excerpt_end = buffer_text.find("//").unwrap() + 3;
10364    let second_excerpt_end = buffer_text.rfind("//").unwrap() - 4;
10365
10366    let fs = FakeFs::new(cx.executor());
10367    fs.insert_tree(
10368        path!("/a"),
10369        json!({
10370            "main.rs": buffer_text,
10371        }),
10372    )
10373    .await;
10374
10375    let project = Project::test(fs, [path!("/a").as_ref()], cx).await;
10376    let language_registry = project.read_with(cx, |project, _| project.languages().clone());
10377    language_registry.add(rust_lang());
10378    let mut fake_servers = language_registry.register_fake_lsp(
10379        "Rust",
10380        FakeLspAdapter {
10381            capabilities: lsp::ServerCapabilities {
10382                completion_provider: Some(lsp::CompletionOptions {
10383                    resolve_provider: None,
10384                    ..lsp::CompletionOptions::default()
10385                }),
10386                ..lsp::ServerCapabilities::default()
10387            },
10388            ..FakeLspAdapter::default()
10389        },
10390    );
10391    let workspace = cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
10392    let cx = &mut VisualTestContext::from_window(*workspace, cx);
10393    let buffer = project
10394        .update(cx, |project, cx| {
10395            project.open_local_buffer(path!("/a/main.rs"), cx)
10396        })
10397        .await
10398        .unwrap();
10399
10400    let multi_buffer = cx.new(|cx| {
10401        let mut multi_buffer = MultiBuffer::new(Capability::ReadWrite);
10402        multi_buffer.push_excerpts(
10403            buffer.clone(),
10404            [ExcerptRange::new(0..first_excerpt_end)],
10405            cx,
10406        );
10407        multi_buffer.push_excerpts(
10408            buffer.clone(),
10409            [ExcerptRange::new(second_excerpt_end..buffer_text.len())],
10410            cx,
10411        );
10412        multi_buffer
10413    });
10414
10415    let editor = workspace
10416        .update(cx, |_, window, cx| {
10417            cx.new(|cx| {
10418                Editor::new(
10419                    EditorMode::Full {
10420                        scale_ui_elements_with_buffer_font_size: false,
10421                        show_active_line_background: false,
10422                    },
10423                    multi_buffer.clone(),
10424                    Some(project.clone()),
10425                    window,
10426                    cx,
10427                )
10428            })
10429        })
10430        .unwrap();
10431
10432    let pane = workspace
10433        .update(cx, |workspace, _, _| workspace.active_pane().clone())
10434        .unwrap();
10435    pane.update_in(cx, |pane, window, cx| {
10436        pane.add_item(Box::new(editor.clone()), true, true, None, window, cx);
10437    });
10438
10439    let fake_server = fake_servers.next().await.unwrap();
10440
10441    editor.update_in(cx, |editor, window, cx| {
10442        editor.change_selections(None, window, cx, |s| {
10443            s.select_ranges([
10444                Point::new(1, 11)..Point::new(1, 11),
10445                Point::new(7, 11)..Point::new(7, 11),
10446            ])
10447        });
10448
10449        assert_text_with_selections(editor, multibuffer_text_with_selections, cx);
10450    });
10451
10452    editor.update_in(cx, |editor, window, cx| {
10453        editor.show_completions(&ShowCompletions { trigger: None }, window, cx);
10454    });
10455
10456    fake_server
10457        .set_request_handler::<lsp::request::Completion, _, _>(move |_, _| async move {
10458            let completion_item = lsp::CompletionItem {
10459                label: "saturating_sub()".into(),
10460                text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
10461                    lsp::InsertReplaceEdit {
10462                        new_text: "saturating_sub()".to_owned(),
10463                        insert: lsp::Range::new(
10464                            lsp::Position::new(7, 7),
10465                            lsp::Position::new(7, 11),
10466                        ),
10467                        replace: lsp::Range::new(
10468                            lsp::Position::new(7, 7),
10469                            lsp::Position::new(7, 13),
10470                        ),
10471                    },
10472                )),
10473                ..lsp::CompletionItem::default()
10474            };
10475
10476            Ok(Some(lsp::CompletionResponse::Array(vec![completion_item])))
10477        })
10478        .next()
10479        .await
10480        .unwrap();
10481
10482    cx.condition(&editor, |editor, _| editor.context_menu_visible())
10483        .await;
10484
10485    editor
10486        .update_in(cx, |editor, window, cx| {
10487            editor
10488                .confirm_completion_replace(&ConfirmCompletionReplace, window, cx)
10489                .unwrap()
10490        })
10491        .await
10492        .unwrap();
10493
10494    editor.update(cx, |editor, cx| {
10495        assert_text_with_selections(editor, expected_multibuffer, cx);
10496    })
10497}
10498
10499#[gpui::test]
10500async fn test_completion(cx: &mut TestAppContext) {
10501    init_test(cx, |_| {});
10502
10503    let mut cx = EditorLspTestContext::new_rust(
10504        lsp::ServerCapabilities {
10505            completion_provider: Some(lsp::CompletionOptions {
10506                trigger_characters: Some(vec![".".to_string(), ":".to_string()]),
10507                resolve_provider: Some(true),
10508                ..Default::default()
10509            }),
10510            signature_help_provider: Some(lsp::SignatureHelpOptions::default()),
10511            ..Default::default()
10512        },
10513        cx,
10514    )
10515    .await;
10516    let counter = Arc::new(AtomicUsize::new(0));
10517
10518    cx.set_state(indoc! {"
10519        oneˇ
10520        two
10521        three
10522    "});
10523    cx.simulate_keystroke(".");
10524    handle_completion_request(
10525        &mut cx,
10526        indoc! {"
10527            one.|<>
10528            two
10529            three
10530        "},
10531        vec!["first_completion", "second_completion"],
10532        counter.clone(),
10533    )
10534    .await;
10535    cx.condition(|editor, _| editor.context_menu_visible())
10536        .await;
10537    assert_eq!(counter.load(atomic::Ordering::Acquire), 1);
10538
10539    let _handler = handle_signature_help_request(
10540        &mut cx,
10541        lsp::SignatureHelp {
10542            signatures: vec![lsp::SignatureInformation {
10543                label: "test signature".to_string(),
10544                documentation: None,
10545                parameters: Some(vec![lsp::ParameterInformation {
10546                    label: lsp::ParameterLabel::Simple("foo: u8".to_string()),
10547                    documentation: None,
10548                }]),
10549                active_parameter: None,
10550            }],
10551            active_signature: None,
10552            active_parameter: None,
10553        },
10554    );
10555    cx.update_editor(|editor, window, cx| {
10556        assert!(
10557            !editor.signature_help_state.is_shown(),
10558            "No signature help was called for"
10559        );
10560        editor.show_signature_help(&ShowSignatureHelp, window, cx);
10561    });
10562    cx.run_until_parked();
10563    cx.update_editor(|editor, _, _| {
10564        assert!(
10565            !editor.signature_help_state.is_shown(),
10566            "No signature help should be shown when completions menu is open"
10567        );
10568    });
10569
10570    let apply_additional_edits = cx.update_editor(|editor, window, cx| {
10571        editor.context_menu_next(&Default::default(), window, cx);
10572        editor
10573            .confirm_completion(&ConfirmCompletion::default(), window, cx)
10574            .unwrap()
10575    });
10576    cx.assert_editor_state(indoc! {"
10577        one.second_completionˇ
10578        two
10579        three
10580    "});
10581
10582    handle_resolve_completion_request(
10583        &mut cx,
10584        Some(vec![
10585            (
10586                //This overlaps with the primary completion edit which is
10587                //misbehavior from the LSP spec, test that we filter it out
10588                indoc! {"
10589                    one.second_ˇcompletion
10590                    two
10591                    threeˇ
10592                "},
10593                "overlapping additional edit",
10594            ),
10595            (
10596                indoc! {"
10597                    one.second_completion
10598                    two
10599                    threeˇ
10600                "},
10601                "\nadditional edit",
10602            ),
10603        ]),
10604    )
10605    .await;
10606    apply_additional_edits.await.unwrap();
10607    cx.assert_editor_state(indoc! {"
10608        one.second_completionˇ
10609        two
10610        three
10611        additional edit
10612    "});
10613
10614    cx.set_state(indoc! {"
10615        one.second_completion
10616        twoˇ
10617        threeˇ
10618        additional edit
10619    "});
10620    cx.simulate_keystroke(" ");
10621    assert!(cx.editor(|e, _, _| e.context_menu.borrow_mut().is_none()));
10622    cx.simulate_keystroke("s");
10623    assert!(cx.editor(|e, _, _| e.context_menu.borrow_mut().is_none()));
10624
10625    cx.assert_editor_state(indoc! {"
10626        one.second_completion
10627        two sˇ
10628        three sˇ
10629        additional edit
10630    "});
10631    handle_completion_request(
10632        &mut cx,
10633        indoc! {"
10634            one.second_completion
10635            two s
10636            three <s|>
10637            additional edit
10638        "},
10639        vec!["fourth_completion", "fifth_completion", "sixth_completion"],
10640        counter.clone(),
10641    )
10642    .await;
10643    cx.condition(|editor, _| editor.context_menu_visible())
10644        .await;
10645    assert_eq!(counter.load(atomic::Ordering::Acquire), 2);
10646
10647    cx.simulate_keystroke("i");
10648
10649    handle_completion_request(
10650        &mut cx,
10651        indoc! {"
10652            one.second_completion
10653            two si
10654            three <si|>
10655            additional edit
10656        "},
10657        vec!["fourth_completion", "fifth_completion", "sixth_completion"],
10658        counter.clone(),
10659    )
10660    .await;
10661    cx.condition(|editor, _| editor.context_menu_visible())
10662        .await;
10663    assert_eq!(counter.load(atomic::Ordering::Acquire), 3);
10664
10665    let apply_additional_edits = cx.update_editor(|editor, window, cx| {
10666        editor
10667            .confirm_completion(&ConfirmCompletion::default(), window, cx)
10668            .unwrap()
10669    });
10670    cx.assert_editor_state(indoc! {"
10671        one.second_completion
10672        two sixth_completionˇ
10673        three sixth_completionˇ
10674        additional edit
10675    "});
10676
10677    apply_additional_edits.await.unwrap();
10678
10679    update_test_language_settings(&mut cx, |settings| {
10680        settings.defaults.show_completions_on_input = Some(false);
10681    });
10682    cx.set_state("editorˇ");
10683    cx.simulate_keystroke(".");
10684    assert!(cx.editor(|e, _, _| e.context_menu.borrow_mut().is_none()));
10685    cx.simulate_keystrokes("c l o");
10686    cx.assert_editor_state("editor.cloˇ");
10687    assert!(cx.editor(|e, _, _| e.context_menu.borrow_mut().is_none()));
10688    cx.update_editor(|editor, window, cx| {
10689        editor.show_completions(&ShowCompletions { trigger: None }, window, cx);
10690    });
10691    handle_completion_request(
10692        &mut cx,
10693        "editor.<clo|>",
10694        vec!["close", "clobber"],
10695        counter.clone(),
10696    )
10697    .await;
10698    cx.condition(|editor, _| editor.context_menu_visible())
10699        .await;
10700    assert_eq!(counter.load(atomic::Ordering::Acquire), 4);
10701
10702    let apply_additional_edits = cx.update_editor(|editor, window, cx| {
10703        editor
10704            .confirm_completion(&ConfirmCompletion::default(), window, cx)
10705            .unwrap()
10706    });
10707    cx.assert_editor_state("editor.clobberˇ");
10708    handle_resolve_completion_request(&mut cx, None).await;
10709    apply_additional_edits.await.unwrap();
10710}
10711
10712#[gpui::test]
10713async fn test_word_completion(cx: &mut TestAppContext) {
10714    let lsp_fetch_timeout_ms = 10;
10715    init_test(cx, |language_settings| {
10716        language_settings.defaults.completions = Some(CompletionSettings {
10717            words: WordsCompletionMode::Fallback,
10718            lsp: true,
10719            lsp_fetch_timeout_ms: 10,
10720            lsp_insert_mode: LspInsertMode::Insert,
10721        });
10722    });
10723
10724    let mut cx = EditorLspTestContext::new_rust(
10725        lsp::ServerCapabilities {
10726            completion_provider: Some(lsp::CompletionOptions {
10727                trigger_characters: Some(vec![".".to_string(), ":".to_string()]),
10728                ..lsp::CompletionOptions::default()
10729            }),
10730            signature_help_provider: Some(lsp::SignatureHelpOptions::default()),
10731            ..lsp::ServerCapabilities::default()
10732        },
10733        cx,
10734    )
10735    .await;
10736
10737    let throttle_completions = Arc::new(AtomicBool::new(false));
10738
10739    let lsp_throttle_completions = throttle_completions.clone();
10740    let _completion_requests_handler =
10741        cx.lsp
10742            .server
10743            .on_request::<lsp::request::Completion, _, _>(move |_, cx| {
10744                let lsp_throttle_completions = lsp_throttle_completions.clone();
10745                let cx = cx.clone();
10746                async move {
10747                    if lsp_throttle_completions.load(atomic::Ordering::Acquire) {
10748                        cx.background_executor()
10749                            .timer(Duration::from_millis(lsp_fetch_timeout_ms * 10))
10750                            .await;
10751                    }
10752                    Ok(Some(lsp::CompletionResponse::Array(vec![
10753                        lsp::CompletionItem {
10754                            label: "first".into(),
10755                            ..lsp::CompletionItem::default()
10756                        },
10757                        lsp::CompletionItem {
10758                            label: "last".into(),
10759                            ..lsp::CompletionItem::default()
10760                        },
10761                    ])))
10762                }
10763            });
10764
10765    cx.set_state(indoc! {"
10766        oneˇ
10767        two
10768        three
10769    "});
10770    cx.simulate_keystroke(".");
10771    cx.executor().run_until_parked();
10772    cx.condition(|editor, _| editor.context_menu_visible())
10773        .await;
10774    cx.update_editor(|editor, window, cx| {
10775        if let Some(CodeContextMenu::Completions(menu)) = editor.context_menu.borrow_mut().as_ref()
10776        {
10777            assert_eq!(
10778                completion_menu_entries(&menu),
10779                &["first", "last"],
10780                "When LSP server is fast to reply, no fallback word completions are used"
10781            );
10782        } else {
10783            panic!("expected completion menu to be open");
10784        }
10785        editor.cancel(&Cancel, window, cx);
10786    });
10787    cx.executor().run_until_parked();
10788    cx.condition(|editor, _| !editor.context_menu_visible())
10789        .await;
10790
10791    throttle_completions.store(true, atomic::Ordering::Release);
10792    cx.simulate_keystroke(".");
10793    cx.executor()
10794        .advance_clock(Duration::from_millis(lsp_fetch_timeout_ms * 2));
10795    cx.executor().run_until_parked();
10796    cx.condition(|editor, _| editor.context_menu_visible())
10797        .await;
10798    cx.update_editor(|editor, _, _| {
10799        if let Some(CodeContextMenu::Completions(menu)) = editor.context_menu.borrow_mut().as_ref()
10800        {
10801            assert_eq!(completion_menu_entries(&menu), &["one", "three", "two"],
10802                "When LSP server is slow, document words can be shown instead, if configured accordingly");
10803        } else {
10804            panic!("expected completion menu to be open");
10805        }
10806    });
10807}
10808
10809#[gpui::test]
10810async fn test_word_completions_do_not_duplicate_lsp_ones(cx: &mut TestAppContext) {
10811    init_test(cx, |language_settings| {
10812        language_settings.defaults.completions = Some(CompletionSettings {
10813            words: WordsCompletionMode::Enabled,
10814            lsp: true,
10815            lsp_fetch_timeout_ms: 0,
10816            lsp_insert_mode: LspInsertMode::Insert,
10817        });
10818    });
10819
10820    let mut cx = EditorLspTestContext::new_rust(
10821        lsp::ServerCapabilities {
10822            completion_provider: Some(lsp::CompletionOptions {
10823                trigger_characters: Some(vec![".".to_string(), ":".to_string()]),
10824                ..lsp::CompletionOptions::default()
10825            }),
10826            signature_help_provider: Some(lsp::SignatureHelpOptions::default()),
10827            ..lsp::ServerCapabilities::default()
10828        },
10829        cx,
10830    )
10831    .await;
10832
10833    let _completion_requests_handler =
10834        cx.lsp
10835            .server
10836            .on_request::<lsp::request::Completion, _, _>(move |_, _| async move {
10837                Ok(Some(lsp::CompletionResponse::Array(vec![
10838                    lsp::CompletionItem {
10839                        label: "first".into(),
10840                        ..lsp::CompletionItem::default()
10841                    },
10842                    lsp::CompletionItem {
10843                        label: "last".into(),
10844                        ..lsp::CompletionItem::default()
10845                    },
10846                ])))
10847            });
10848
10849    cx.set_state(indoc! {"ˇ
10850        first
10851        last
10852        second
10853    "});
10854    cx.simulate_keystroke(".");
10855    cx.executor().run_until_parked();
10856    cx.condition(|editor, _| editor.context_menu_visible())
10857        .await;
10858    cx.update_editor(|editor, _, _| {
10859        if let Some(CodeContextMenu::Completions(menu)) = editor.context_menu.borrow_mut().as_ref()
10860        {
10861            assert_eq!(
10862                completion_menu_entries(&menu),
10863                &["first", "last", "second"],
10864                "Word completions that has the same edit as the any of the LSP ones, should not be proposed"
10865            );
10866        } else {
10867            panic!("expected completion menu to be open");
10868        }
10869    });
10870}
10871
10872#[gpui::test]
10873async fn test_word_completions_continue_on_typing(cx: &mut TestAppContext) {
10874    init_test(cx, |language_settings| {
10875        language_settings.defaults.completions = Some(CompletionSettings {
10876            words: WordsCompletionMode::Disabled,
10877            lsp: true,
10878            lsp_fetch_timeout_ms: 0,
10879            lsp_insert_mode: LspInsertMode::Insert,
10880        });
10881    });
10882
10883    let mut cx = EditorLspTestContext::new_rust(
10884        lsp::ServerCapabilities {
10885            completion_provider: Some(lsp::CompletionOptions {
10886                trigger_characters: Some(vec![".".to_string(), ":".to_string()]),
10887                ..lsp::CompletionOptions::default()
10888            }),
10889            signature_help_provider: Some(lsp::SignatureHelpOptions::default()),
10890            ..lsp::ServerCapabilities::default()
10891        },
10892        cx,
10893    )
10894    .await;
10895
10896    let _completion_requests_handler =
10897        cx.lsp
10898            .server
10899            .on_request::<lsp::request::Completion, _, _>(move |_, _| async move {
10900                panic!("LSP completions should not be queried when dealing with word completions")
10901            });
10902
10903    cx.set_state(indoc! {"ˇ
10904        first
10905        last
10906        second
10907    "});
10908    cx.update_editor(|editor, window, cx| {
10909        editor.show_word_completions(&ShowWordCompletions, window, cx);
10910    });
10911    cx.executor().run_until_parked();
10912    cx.condition(|editor, _| editor.context_menu_visible())
10913        .await;
10914    cx.update_editor(|editor, _, _| {
10915        if let Some(CodeContextMenu::Completions(menu)) = editor.context_menu.borrow_mut().as_ref()
10916        {
10917            assert_eq!(
10918                completion_menu_entries(&menu),
10919                &["first", "last", "second"],
10920                "`ShowWordCompletions` action should show word completions"
10921            );
10922        } else {
10923            panic!("expected completion menu to be open");
10924        }
10925    });
10926
10927    cx.simulate_keystroke("l");
10928    cx.executor().run_until_parked();
10929    cx.condition(|editor, _| editor.context_menu_visible())
10930        .await;
10931    cx.update_editor(|editor, _, _| {
10932        if let Some(CodeContextMenu::Completions(menu)) = editor.context_menu.borrow_mut().as_ref()
10933        {
10934            assert_eq!(
10935                completion_menu_entries(&menu),
10936                &["last"],
10937                "After showing word completions, further editing should filter them and not query the LSP"
10938            );
10939        } else {
10940            panic!("expected completion menu to be open");
10941        }
10942    });
10943}
10944
10945#[gpui::test]
10946async fn test_word_completions_usually_skip_digits(cx: &mut TestAppContext) {
10947    init_test(cx, |language_settings| {
10948        language_settings.defaults.completions = Some(CompletionSettings {
10949            words: WordsCompletionMode::Fallback,
10950            lsp: false,
10951            lsp_fetch_timeout_ms: 0,
10952            lsp_insert_mode: LspInsertMode::Insert,
10953        });
10954    });
10955
10956    let mut cx = EditorLspTestContext::new_rust(lsp::ServerCapabilities::default(), cx).await;
10957
10958    cx.set_state(indoc! {"ˇ
10959        0_usize
10960        let
10961        33
10962        4.5f32
10963    "});
10964    cx.update_editor(|editor, window, cx| {
10965        editor.show_completions(&ShowCompletions::default(), window, cx);
10966    });
10967    cx.executor().run_until_parked();
10968    cx.condition(|editor, _| editor.context_menu_visible())
10969        .await;
10970    cx.update_editor(|editor, window, cx| {
10971        if let Some(CodeContextMenu::Completions(menu)) = editor.context_menu.borrow_mut().as_ref()
10972        {
10973            assert_eq!(
10974                completion_menu_entries(&menu),
10975                &["let"],
10976                "With no digits in the completion query, no digits should be in the word completions"
10977            );
10978        } else {
10979            panic!("expected completion menu to be open");
10980        }
10981        editor.cancel(&Cancel, window, cx);
10982    });
10983
10984    cx.set_state(indoc! {"10985        0_usize
10986        let
10987        3
10988        33.35f32
10989    "});
10990    cx.update_editor(|editor, window, cx| {
10991        editor.show_completions(&ShowCompletions::default(), window, cx);
10992    });
10993    cx.executor().run_until_parked();
10994    cx.condition(|editor, _| editor.context_menu_visible())
10995        .await;
10996    cx.update_editor(|editor, _, _| {
10997        if let Some(CodeContextMenu::Completions(menu)) = editor.context_menu.borrow_mut().as_ref()
10998        {
10999            assert_eq!(completion_menu_entries(&menu), &["33", "35f32"], "The digit is in the completion query, \
11000                return matching words with digits (`33`, `35f32`) but exclude query duplicates (`3`)");
11001        } else {
11002            panic!("expected completion menu to be open");
11003        }
11004    });
11005}
11006
11007fn gen_text_edit(params: &CompletionParams, text: &str) -> Option<lsp::CompletionTextEdit> {
11008    let position = || lsp::Position {
11009        line: params.text_document_position.position.line,
11010        character: params.text_document_position.position.character,
11011    };
11012    Some(lsp::CompletionTextEdit::Edit(lsp::TextEdit {
11013        range: lsp::Range {
11014            start: position(),
11015            end: position(),
11016        },
11017        new_text: text.to_string(),
11018    }))
11019}
11020
11021#[gpui::test]
11022async fn test_multiline_completion(cx: &mut TestAppContext) {
11023    init_test(cx, |_| {});
11024
11025    let fs = FakeFs::new(cx.executor());
11026    fs.insert_tree(
11027        path!("/a"),
11028        json!({
11029            "main.ts": "a",
11030        }),
11031    )
11032    .await;
11033
11034    let project = Project::test(fs, [path!("/a").as_ref()], cx).await;
11035    let language_registry = project.read_with(cx, |project, _| project.languages().clone());
11036    let typescript_language = Arc::new(Language::new(
11037        LanguageConfig {
11038            name: "TypeScript".into(),
11039            matcher: LanguageMatcher {
11040                path_suffixes: vec!["ts".to_string()],
11041                ..LanguageMatcher::default()
11042            },
11043            line_comments: vec!["// ".into()],
11044            ..LanguageConfig::default()
11045        },
11046        Some(tree_sitter_typescript::LANGUAGE_TYPESCRIPT.into()),
11047    ));
11048    language_registry.add(typescript_language.clone());
11049    let mut fake_servers = language_registry.register_fake_lsp(
11050        "TypeScript",
11051        FakeLspAdapter {
11052            capabilities: lsp::ServerCapabilities {
11053                completion_provider: Some(lsp::CompletionOptions {
11054                    trigger_characters: Some(vec![".".to_string(), ":".to_string()]),
11055                    ..lsp::CompletionOptions::default()
11056                }),
11057                signature_help_provider: Some(lsp::SignatureHelpOptions::default()),
11058                ..lsp::ServerCapabilities::default()
11059            },
11060            // Emulate vtsls label generation
11061            label_for_completion: Some(Box::new(|item, _| {
11062                let text = if let Some(description) = item
11063                    .label_details
11064                    .as_ref()
11065                    .and_then(|label_details| label_details.description.as_ref())
11066                {
11067                    format!("{} {}", item.label, description)
11068                } else if let Some(detail) = &item.detail {
11069                    format!("{} {}", item.label, detail)
11070                } else {
11071                    item.label.clone()
11072                };
11073                let len = text.len();
11074                Some(language::CodeLabel {
11075                    text,
11076                    runs: Vec::new(),
11077                    filter_range: 0..len,
11078                })
11079            })),
11080            ..FakeLspAdapter::default()
11081        },
11082    );
11083    let workspace = cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
11084    let cx = &mut VisualTestContext::from_window(*workspace, cx);
11085    let worktree_id = workspace
11086        .update(cx, |workspace, _window, cx| {
11087            workspace.project().update(cx, |project, cx| {
11088                project.worktrees(cx).next().unwrap().read(cx).id()
11089            })
11090        })
11091        .unwrap();
11092    let _buffer = project
11093        .update(cx, |project, cx| {
11094            project.open_local_buffer_with_lsp(path!("/a/main.ts"), cx)
11095        })
11096        .await
11097        .unwrap();
11098    let editor = workspace
11099        .update(cx, |workspace, window, cx| {
11100            workspace.open_path((worktree_id, "main.ts"), None, true, window, cx)
11101        })
11102        .unwrap()
11103        .await
11104        .unwrap()
11105        .downcast::<Editor>()
11106        .unwrap();
11107    let fake_server = fake_servers.next().await.unwrap();
11108
11109    let multiline_label = "StickyHeaderExcerpt {\n            excerpt,\n            next_excerpt_controls_present,\n            next_buffer_row,\n        }: StickyHeaderExcerpt<'_>,";
11110    let multiline_label_2 = "a\nb\nc\n";
11111    let multiline_detail = "[]struct {\n\tSignerId\tstruct {\n\t\tIssuer\t\t\tstring\t`json:\"issuer\"`\n\t\tSubjectSerialNumber\"`\n}}";
11112    let multiline_description = "d\ne\nf\n";
11113    let multiline_detail_2 = "g\nh\ni\n";
11114
11115    let mut completion_handle = fake_server.set_request_handler::<lsp::request::Completion, _, _>(
11116        move |params, _| async move {
11117            Ok(Some(lsp::CompletionResponse::Array(vec![
11118                lsp::CompletionItem {
11119                    label: multiline_label.to_string(),
11120                    text_edit: gen_text_edit(&params, "new_text_1"),
11121                    ..lsp::CompletionItem::default()
11122                },
11123                lsp::CompletionItem {
11124                    label: "single line label 1".to_string(),
11125                    detail: Some(multiline_detail.to_string()),
11126                    text_edit: gen_text_edit(&params, "new_text_2"),
11127                    ..lsp::CompletionItem::default()
11128                },
11129                lsp::CompletionItem {
11130                    label: "single line label 2".to_string(),
11131                    label_details: Some(lsp::CompletionItemLabelDetails {
11132                        description: Some(multiline_description.to_string()),
11133                        detail: None,
11134                    }),
11135                    text_edit: gen_text_edit(&params, "new_text_2"),
11136                    ..lsp::CompletionItem::default()
11137                },
11138                lsp::CompletionItem {
11139                    label: multiline_label_2.to_string(),
11140                    detail: Some(multiline_detail_2.to_string()),
11141                    text_edit: gen_text_edit(&params, "new_text_3"),
11142                    ..lsp::CompletionItem::default()
11143                },
11144                lsp::CompletionItem {
11145                    label: "Label with many     spaces and \t but without newlines".to_string(),
11146                    detail: Some(
11147                        "Details with many     spaces and \t but without newlines".to_string(),
11148                    ),
11149                    text_edit: gen_text_edit(&params, "new_text_4"),
11150                    ..lsp::CompletionItem::default()
11151                },
11152            ])))
11153        },
11154    );
11155
11156    editor.update_in(cx, |editor, window, cx| {
11157        cx.focus_self(window);
11158        editor.move_to_end(&MoveToEnd, window, cx);
11159        editor.handle_input(".", window, cx);
11160    });
11161    cx.run_until_parked();
11162    completion_handle.next().await.unwrap();
11163
11164    editor.update(cx, |editor, _| {
11165        assert!(editor.context_menu_visible());
11166        if let Some(CodeContextMenu::Completions(menu)) = editor.context_menu.borrow_mut().as_ref()
11167        {
11168            let completion_labels = menu
11169                .completions
11170                .borrow()
11171                .iter()
11172                .map(|c| c.label.text.clone())
11173                .collect::<Vec<_>>();
11174            assert_eq!(
11175                completion_labels,
11176                &[
11177                    "StickyHeaderExcerpt { excerpt, next_excerpt_controls_present, next_buffer_row, }: StickyHeaderExcerpt<'_>,",
11178                    "single line label 1 []struct { SignerId struct { Issuer string `json:\"issuer\"` SubjectSerialNumber\"` }}",
11179                    "single line label 2 d e f ",
11180                    "a b c g h i ",
11181                    "Label with many     spaces and \t but without newlines Details with many     spaces and \t but without newlines",
11182                ],
11183                "Completion items should have their labels without newlines, also replacing excessive whitespaces. Completion items without newlines should not be altered.",
11184            );
11185
11186            for completion in menu
11187                .completions
11188                .borrow()
11189                .iter() {
11190                    assert_eq!(
11191                        completion.label.filter_range,
11192                        0..completion.label.text.len(),
11193                        "Adjusted completion items should still keep their filter ranges for the entire label. Item: {completion:?}"
11194                    );
11195                }
11196        } else {
11197            panic!("expected completion menu to be open");
11198        }
11199    });
11200}
11201
11202#[gpui::test]
11203async fn test_completion_page_up_down_keys(cx: &mut TestAppContext) {
11204    init_test(cx, |_| {});
11205    let mut cx = EditorLspTestContext::new_rust(
11206        lsp::ServerCapabilities {
11207            completion_provider: Some(lsp::CompletionOptions {
11208                trigger_characters: Some(vec![".".to_string()]),
11209                ..Default::default()
11210            }),
11211            ..Default::default()
11212        },
11213        cx,
11214    )
11215    .await;
11216    cx.lsp
11217        .set_request_handler::<lsp::request::Completion, _, _>(move |_, _| async move {
11218            Ok(Some(lsp::CompletionResponse::Array(vec![
11219                lsp::CompletionItem {
11220                    label: "first".into(),
11221                    ..Default::default()
11222                },
11223                lsp::CompletionItem {
11224                    label: "last".into(),
11225                    ..Default::default()
11226                },
11227            ])))
11228        });
11229    cx.set_state("variableˇ");
11230    cx.simulate_keystroke(".");
11231    cx.executor().run_until_parked();
11232
11233    cx.update_editor(|editor, _, _| {
11234        if let Some(CodeContextMenu::Completions(menu)) = editor.context_menu.borrow_mut().as_ref()
11235        {
11236            assert_eq!(completion_menu_entries(&menu), &["first", "last"]);
11237        } else {
11238            panic!("expected completion menu to be open");
11239        }
11240    });
11241
11242    cx.update_editor(|editor, window, cx| {
11243        editor.move_page_down(&MovePageDown::default(), window, cx);
11244        if let Some(CodeContextMenu::Completions(menu)) = editor.context_menu.borrow_mut().as_ref()
11245        {
11246            assert!(
11247                menu.selected_item == 1,
11248                "expected PageDown to select the last item from the context menu"
11249            );
11250        } else {
11251            panic!("expected completion menu to stay open after PageDown");
11252        }
11253    });
11254
11255    cx.update_editor(|editor, window, cx| {
11256        editor.move_page_up(&MovePageUp::default(), window, cx);
11257        if let Some(CodeContextMenu::Completions(menu)) = editor.context_menu.borrow_mut().as_ref()
11258        {
11259            assert!(
11260                menu.selected_item == 0,
11261                "expected PageUp to select the first item from the context menu"
11262            );
11263        } else {
11264            panic!("expected completion menu to stay open after PageUp");
11265        }
11266    });
11267}
11268
11269#[gpui::test]
11270async fn test_as_is_completions(cx: &mut TestAppContext) {
11271    init_test(cx, |_| {});
11272    let mut cx = EditorLspTestContext::new_rust(
11273        lsp::ServerCapabilities {
11274            completion_provider: Some(lsp::CompletionOptions {
11275                ..Default::default()
11276            }),
11277            ..Default::default()
11278        },
11279        cx,
11280    )
11281    .await;
11282    cx.lsp
11283        .set_request_handler::<lsp::request::Completion, _, _>(move |_, _| async move {
11284            Ok(Some(lsp::CompletionResponse::Array(vec![
11285                lsp::CompletionItem {
11286                    label: "unsafe".into(),
11287                    text_edit: Some(lsp::CompletionTextEdit::Edit(lsp::TextEdit {
11288                        range: lsp::Range {
11289                            start: lsp::Position {
11290                                line: 1,
11291                                character: 2,
11292                            },
11293                            end: lsp::Position {
11294                                line: 1,
11295                                character: 3,
11296                            },
11297                        },
11298                        new_text: "unsafe".to_string(),
11299                    })),
11300                    insert_text_mode: Some(lsp::InsertTextMode::AS_IS),
11301                    ..Default::default()
11302                },
11303            ])))
11304        });
11305    cx.set_state("fn a() {}\n");
11306    cx.executor().run_until_parked();
11307    cx.update_editor(|editor, window, cx| {
11308        editor.show_completions(
11309            &ShowCompletions {
11310                trigger: Some("\n".into()),
11311            },
11312            window,
11313            cx,
11314        );
11315    });
11316    cx.executor().run_until_parked();
11317
11318    cx.update_editor(|editor, window, cx| {
11319        editor.confirm_completion(&Default::default(), window, cx)
11320    });
11321    cx.executor().run_until_parked();
11322    cx.assert_editor_state("fn a() {}\n  unsafeˇ");
11323}
11324
11325#[gpui::test]
11326async fn test_no_duplicated_completion_requests(cx: &mut TestAppContext) {
11327    init_test(cx, |_| {});
11328
11329    let mut cx = EditorLspTestContext::new_rust(
11330        lsp::ServerCapabilities {
11331            completion_provider: Some(lsp::CompletionOptions {
11332                trigger_characters: Some(vec![".".to_string()]),
11333                resolve_provider: Some(true),
11334                ..Default::default()
11335            }),
11336            ..Default::default()
11337        },
11338        cx,
11339    )
11340    .await;
11341
11342    cx.set_state("fn main() { let a = 2ˇ; }");
11343    cx.simulate_keystroke(".");
11344    let completion_item = lsp::CompletionItem {
11345        label: "Some".into(),
11346        kind: Some(lsp::CompletionItemKind::SNIPPET),
11347        detail: Some("Wrap the expression in an `Option::Some`".to_string()),
11348        documentation: Some(lsp::Documentation::MarkupContent(lsp::MarkupContent {
11349            kind: lsp::MarkupKind::Markdown,
11350            value: "```rust\nSome(2)\n```".to_string(),
11351        })),
11352        deprecated: Some(false),
11353        sort_text: Some("Some".to_string()),
11354        filter_text: Some("Some".to_string()),
11355        insert_text_format: Some(lsp::InsertTextFormat::SNIPPET),
11356        text_edit: Some(lsp::CompletionTextEdit::Edit(lsp::TextEdit {
11357            range: lsp::Range {
11358                start: lsp::Position {
11359                    line: 0,
11360                    character: 22,
11361                },
11362                end: lsp::Position {
11363                    line: 0,
11364                    character: 22,
11365                },
11366            },
11367            new_text: "Some(2)".to_string(),
11368        })),
11369        additional_text_edits: Some(vec![lsp::TextEdit {
11370            range: lsp::Range {
11371                start: lsp::Position {
11372                    line: 0,
11373                    character: 20,
11374                },
11375                end: lsp::Position {
11376                    line: 0,
11377                    character: 22,
11378                },
11379            },
11380            new_text: "".to_string(),
11381        }]),
11382        ..Default::default()
11383    };
11384
11385    let closure_completion_item = completion_item.clone();
11386    let counter = Arc::new(AtomicUsize::new(0));
11387    let counter_clone = counter.clone();
11388    let mut request = cx.set_request_handler::<lsp::request::Completion, _, _>(move |_, _, _| {
11389        let task_completion_item = closure_completion_item.clone();
11390        counter_clone.fetch_add(1, atomic::Ordering::Release);
11391        async move {
11392            Ok(Some(lsp::CompletionResponse::Array(vec![
11393                task_completion_item,
11394            ])))
11395        }
11396    });
11397
11398    cx.condition(|editor, _| editor.context_menu_visible())
11399        .await;
11400    cx.assert_editor_state("fn main() { let a = 2.ˇ; }");
11401    assert!(request.next().await.is_some());
11402    assert_eq!(counter.load(atomic::Ordering::Acquire), 1);
11403
11404    cx.simulate_keystrokes("S o m");
11405    cx.condition(|editor, _| editor.context_menu_visible())
11406        .await;
11407    cx.assert_editor_state("fn main() { let a = 2.Somˇ; }");
11408    assert!(request.next().await.is_some());
11409    assert!(request.next().await.is_some());
11410    assert!(request.next().await.is_some());
11411    request.close();
11412    assert!(request.next().await.is_none());
11413    assert_eq!(
11414        counter.load(atomic::Ordering::Acquire),
11415        4,
11416        "With the completions menu open, only one LSP request should happen per input"
11417    );
11418}
11419
11420#[gpui::test]
11421async fn test_toggle_comment(cx: &mut TestAppContext) {
11422    init_test(cx, |_| {});
11423    let mut cx = EditorTestContext::new(cx).await;
11424    let language = Arc::new(Language::new(
11425        LanguageConfig {
11426            line_comments: vec!["// ".into(), "//! ".into(), "/// ".into()],
11427            ..Default::default()
11428        },
11429        Some(tree_sitter_rust::LANGUAGE.into()),
11430    ));
11431    cx.update_buffer(|buffer, cx| buffer.set_language(Some(language), cx));
11432
11433    // If multiple selections intersect a line, the line is only toggled once.
11434    cx.set_state(indoc! {"
11435        fn a() {
11436            «//b();
11437            ˇ»// «c();
11438            //ˇ»  d();
11439        }
11440    "});
11441
11442    cx.update_editor(|e, window, cx| e.toggle_comments(&ToggleComments::default(), window, cx));
11443
11444    cx.assert_editor_state(indoc! {"
11445        fn a() {
11446            «b();
11447            c();
11448            ˇ» d();
11449        }
11450    "});
11451
11452    // The comment prefix is inserted at the same column for every line in a
11453    // selection.
11454    cx.update_editor(|e, window, cx| e.toggle_comments(&ToggleComments::default(), window, cx));
11455
11456    cx.assert_editor_state(indoc! {"
11457        fn a() {
11458            // «b();
11459            // c();
11460            ˇ»//  d();
11461        }
11462    "});
11463
11464    // If a selection ends at the beginning of a line, that line is not toggled.
11465    cx.set_selections_state(indoc! {"
11466        fn a() {
11467            // b();
11468            «// c();
11469        ˇ»    //  d();
11470        }
11471    "});
11472
11473    cx.update_editor(|e, window, cx| e.toggle_comments(&ToggleComments::default(), window, cx));
11474
11475    cx.assert_editor_state(indoc! {"
11476        fn a() {
11477            // b();
11478            «c();
11479        ˇ»    //  d();
11480        }
11481    "});
11482
11483    // If a selection span a single line and is empty, the line is toggled.
11484    cx.set_state(indoc! {"
11485        fn a() {
11486            a();
11487            b();
11488        ˇ
11489        }
11490    "});
11491
11492    cx.update_editor(|e, window, cx| e.toggle_comments(&ToggleComments::default(), window, cx));
11493
11494    cx.assert_editor_state(indoc! {"
11495        fn a() {
11496            a();
11497            b();
11498        //•ˇ
11499        }
11500    "});
11501
11502    // If a selection span multiple lines, empty lines are not toggled.
11503    cx.set_state(indoc! {"
11504        fn a() {
11505            «a();
11506
11507            c();ˇ»
11508        }
11509    "});
11510
11511    cx.update_editor(|e, window, cx| e.toggle_comments(&ToggleComments::default(), window, cx));
11512
11513    cx.assert_editor_state(indoc! {"
11514        fn a() {
11515            // «a();
11516
11517            // c();ˇ»
11518        }
11519    "});
11520
11521    // If a selection includes multiple comment prefixes, all lines are uncommented.
11522    cx.set_state(indoc! {"
11523        fn a() {
11524            «// a();
11525            /// b();
11526            //! c();ˇ»
11527        }
11528    "});
11529
11530    cx.update_editor(|e, window, cx| e.toggle_comments(&ToggleComments::default(), window, cx));
11531
11532    cx.assert_editor_state(indoc! {"
11533        fn a() {
11534            «a();
11535            b();
11536            c();ˇ»
11537        }
11538    "});
11539}
11540
11541#[gpui::test]
11542async fn test_toggle_comment_ignore_indent(cx: &mut TestAppContext) {
11543    init_test(cx, |_| {});
11544    let mut cx = EditorTestContext::new(cx).await;
11545    let language = Arc::new(Language::new(
11546        LanguageConfig {
11547            line_comments: vec!["// ".into(), "//! ".into(), "/// ".into()],
11548            ..Default::default()
11549        },
11550        Some(tree_sitter_rust::LANGUAGE.into()),
11551    ));
11552    cx.update_buffer(|buffer, cx| buffer.set_language(Some(language), cx));
11553
11554    let toggle_comments = &ToggleComments {
11555        advance_downwards: false,
11556        ignore_indent: true,
11557    };
11558
11559    // If multiple selections intersect a line, the line is only toggled once.
11560    cx.set_state(indoc! {"
11561        fn a() {
11562        //    «b();
11563        //    c();
11564        //    ˇ» d();
11565        }
11566    "});
11567
11568    cx.update_editor(|e, window, cx| e.toggle_comments(toggle_comments, window, cx));
11569
11570    cx.assert_editor_state(indoc! {"
11571        fn a() {
11572            «b();
11573            c();
11574            ˇ» d();
11575        }
11576    "});
11577
11578    // The comment prefix is inserted at the beginning of each line
11579    cx.update_editor(|e, window, cx| e.toggle_comments(toggle_comments, window, cx));
11580
11581    cx.assert_editor_state(indoc! {"
11582        fn a() {
11583        //    «b();
11584        //    c();
11585        //    ˇ» d();
11586        }
11587    "});
11588
11589    // If a selection ends at the beginning of a line, that line is not toggled.
11590    cx.set_selections_state(indoc! {"
11591        fn a() {
11592        //    b();
11593        //    «c();
11594        ˇ»//     d();
11595        }
11596    "});
11597
11598    cx.update_editor(|e, window, cx| e.toggle_comments(toggle_comments, window, cx));
11599
11600    cx.assert_editor_state(indoc! {"
11601        fn a() {
11602        //    b();
11603            «c();
11604        ˇ»//     d();
11605        }
11606    "});
11607
11608    // If a selection span a single line and is empty, the line is toggled.
11609    cx.set_state(indoc! {"
11610        fn a() {
11611            a();
11612            b();
11613        ˇ
11614        }
11615    "});
11616
11617    cx.update_editor(|e, window, cx| e.toggle_comments(toggle_comments, window, cx));
11618
11619    cx.assert_editor_state(indoc! {"
11620        fn a() {
11621            a();
11622            b();
11623        //ˇ
11624        }
11625    "});
11626
11627    // If a selection span multiple lines, empty lines are not toggled.
11628    cx.set_state(indoc! {"
11629        fn a() {
11630            «a();
11631
11632            c();ˇ»
11633        }
11634    "});
11635
11636    cx.update_editor(|e, window, cx| e.toggle_comments(toggle_comments, window, cx));
11637
11638    cx.assert_editor_state(indoc! {"
11639        fn a() {
11640        //    «a();
11641
11642        //    c();ˇ»
11643        }
11644    "});
11645
11646    // If a selection includes multiple comment prefixes, all lines are uncommented.
11647    cx.set_state(indoc! {"
11648        fn a() {
11649        //    «a();
11650        ///    b();
11651        //!    c();ˇ»
11652        }
11653    "});
11654
11655    cx.update_editor(|e, window, cx| e.toggle_comments(toggle_comments, window, cx));
11656
11657    cx.assert_editor_state(indoc! {"
11658        fn a() {
11659            «a();
11660            b();
11661            c();ˇ»
11662        }
11663    "});
11664}
11665
11666#[gpui::test]
11667async fn test_advance_downward_on_toggle_comment(cx: &mut TestAppContext) {
11668    init_test(cx, |_| {});
11669
11670    let language = Arc::new(Language::new(
11671        LanguageConfig {
11672            line_comments: vec!["// ".into()],
11673            ..Default::default()
11674        },
11675        Some(tree_sitter_rust::LANGUAGE.into()),
11676    ));
11677
11678    let mut cx = EditorTestContext::new(cx).await;
11679
11680    cx.language_registry().add(language.clone());
11681    cx.update_buffer(|buffer, cx| {
11682        buffer.set_language(Some(language), cx);
11683    });
11684
11685    let toggle_comments = &ToggleComments {
11686        advance_downwards: true,
11687        ignore_indent: false,
11688    };
11689
11690    // Single cursor on one line -> advance
11691    // Cursor moves horizontally 3 characters as well on non-blank line
11692    cx.set_state(indoc!(
11693        "fn a() {
11694             ˇdog();
11695             cat();
11696        }"
11697    ));
11698    cx.update_editor(|editor, window, cx| {
11699        editor.toggle_comments(toggle_comments, window, cx);
11700    });
11701    cx.assert_editor_state(indoc!(
11702        "fn a() {
11703             // dog();
11704             catˇ();
11705        }"
11706    ));
11707
11708    // Single selection on one line -> don't advance
11709    cx.set_state(indoc!(
11710        "fn a() {
11711             «dog()ˇ»;
11712             cat();
11713        }"
11714    ));
11715    cx.update_editor(|editor, window, cx| {
11716        editor.toggle_comments(toggle_comments, window, cx);
11717    });
11718    cx.assert_editor_state(indoc!(
11719        "fn a() {
11720             // «dog()ˇ»;
11721             cat();
11722        }"
11723    ));
11724
11725    // Multiple cursors on one line -> advance
11726    cx.set_state(indoc!(
11727        "fn a() {
11728             ˇdˇog();
11729             cat();
11730        }"
11731    ));
11732    cx.update_editor(|editor, window, cx| {
11733        editor.toggle_comments(toggle_comments, window, cx);
11734    });
11735    cx.assert_editor_state(indoc!(
11736        "fn a() {
11737             // dog();
11738             catˇ(ˇ);
11739        }"
11740    ));
11741
11742    // Multiple cursors on one line, with selection -> don't advance
11743    cx.set_state(indoc!(
11744        "fn a() {
11745             ˇdˇog«()ˇ»;
11746             cat();
11747        }"
11748    ));
11749    cx.update_editor(|editor, window, cx| {
11750        editor.toggle_comments(toggle_comments, window, cx);
11751    });
11752    cx.assert_editor_state(indoc!(
11753        "fn a() {
11754             // ˇdˇog«()ˇ»;
11755             cat();
11756        }"
11757    ));
11758
11759    // Single cursor on one line -> advance
11760    // Cursor moves to column 0 on blank line
11761    cx.set_state(indoc!(
11762        "fn a() {
11763             ˇdog();
11764
11765             cat();
11766        }"
11767    ));
11768    cx.update_editor(|editor, window, cx| {
11769        editor.toggle_comments(toggle_comments, window, cx);
11770    });
11771    cx.assert_editor_state(indoc!(
11772        "fn a() {
11773             // dog();
11774        ˇ
11775             cat();
11776        }"
11777    ));
11778
11779    // Single cursor on one line -> advance
11780    // Cursor starts and ends at column 0
11781    cx.set_state(indoc!(
11782        "fn a() {
11783         ˇ    dog();
11784             cat();
11785        }"
11786    ));
11787    cx.update_editor(|editor, window, cx| {
11788        editor.toggle_comments(toggle_comments, window, cx);
11789    });
11790    cx.assert_editor_state(indoc!(
11791        "fn a() {
11792             // dog();
11793         ˇ    cat();
11794        }"
11795    ));
11796}
11797
11798#[gpui::test]
11799async fn test_toggle_block_comment(cx: &mut TestAppContext) {
11800    init_test(cx, |_| {});
11801
11802    let mut cx = EditorTestContext::new(cx).await;
11803
11804    let html_language = Arc::new(
11805        Language::new(
11806            LanguageConfig {
11807                name: "HTML".into(),
11808                block_comment: Some(("<!-- ".into(), " -->".into())),
11809                ..Default::default()
11810            },
11811            Some(tree_sitter_html::LANGUAGE.into()),
11812        )
11813        .with_injection_query(
11814            r#"
11815            (script_element
11816                (raw_text) @injection.content
11817                (#set! injection.language "javascript"))
11818            "#,
11819        )
11820        .unwrap(),
11821    );
11822
11823    let javascript_language = Arc::new(Language::new(
11824        LanguageConfig {
11825            name: "JavaScript".into(),
11826            line_comments: vec!["// ".into()],
11827            ..Default::default()
11828        },
11829        Some(tree_sitter_typescript::LANGUAGE_TSX.into()),
11830    ));
11831
11832    cx.language_registry().add(html_language.clone());
11833    cx.language_registry().add(javascript_language.clone());
11834    cx.update_buffer(|buffer, cx| {
11835        buffer.set_language(Some(html_language), cx);
11836    });
11837
11838    // Toggle comments for empty selections
11839    cx.set_state(
11840        &r#"
11841            <p>A</p>ˇ
11842            <p>B</p>ˇ
11843            <p>C</p>ˇ
11844        "#
11845        .unindent(),
11846    );
11847    cx.update_editor(|editor, window, cx| {
11848        editor.toggle_comments(&ToggleComments::default(), window, cx)
11849    });
11850    cx.assert_editor_state(
11851        &r#"
11852            <!-- <p>A</p>ˇ -->
11853            <!-- <p>B</p>ˇ -->
11854            <!-- <p>C</p>ˇ -->
11855        "#
11856        .unindent(),
11857    );
11858    cx.update_editor(|editor, window, cx| {
11859        editor.toggle_comments(&ToggleComments::default(), window, cx)
11860    });
11861    cx.assert_editor_state(
11862        &r#"
11863            <p>A</p>ˇ
11864            <p>B</p>ˇ
11865            <p>C</p>ˇ
11866        "#
11867        .unindent(),
11868    );
11869
11870    // Toggle comments for mixture of empty and non-empty selections, where
11871    // multiple selections occupy a given line.
11872    cx.set_state(
11873        &r#"
11874            <p>A«</p>
11875            <p>ˇ»B</p>ˇ
11876            <p>C«</p>
11877            <p>ˇ»D</p>ˇ
11878        "#
11879        .unindent(),
11880    );
11881
11882    cx.update_editor(|editor, window, cx| {
11883        editor.toggle_comments(&ToggleComments::default(), window, cx)
11884    });
11885    cx.assert_editor_state(
11886        &r#"
11887            <!-- <p>A«</p>
11888            <p>ˇ»B</p>ˇ -->
11889            <!-- <p>C«</p>
11890            <p>ˇ»D</p>ˇ -->
11891        "#
11892        .unindent(),
11893    );
11894    cx.update_editor(|editor, window, cx| {
11895        editor.toggle_comments(&ToggleComments::default(), window, cx)
11896    });
11897    cx.assert_editor_state(
11898        &r#"
11899            <p>A«</p>
11900            <p>ˇ»B</p>ˇ
11901            <p>C«</p>
11902            <p>ˇ»D</p>ˇ
11903        "#
11904        .unindent(),
11905    );
11906
11907    // Toggle comments when different languages are active for different
11908    // selections.
11909    cx.set_state(
11910        &r#"
11911            ˇ<script>
11912                ˇvar x = new Y();
11913            ˇ</script>
11914        "#
11915        .unindent(),
11916    );
11917    cx.executor().run_until_parked();
11918    cx.update_editor(|editor, window, cx| {
11919        editor.toggle_comments(&ToggleComments::default(), window, cx)
11920    });
11921    // TODO this is how it actually worked in Zed Stable, which is not very ergonomic.
11922    // Uncommenting and commenting from this position brings in even more wrong artifacts.
11923    cx.assert_editor_state(
11924        &r#"
11925            <!-- ˇ<script> -->
11926                // ˇvar x = new Y();
11927            <!-- ˇ</script> -->
11928        "#
11929        .unindent(),
11930    );
11931}
11932
11933#[gpui::test]
11934fn test_editing_disjoint_excerpts(cx: &mut TestAppContext) {
11935    init_test(cx, |_| {});
11936
11937    let buffer = cx.new(|cx| Buffer::local(sample_text(3, 4, 'a'), cx));
11938    let multibuffer = cx.new(|cx| {
11939        let mut multibuffer = MultiBuffer::new(ReadWrite);
11940        multibuffer.push_excerpts(
11941            buffer.clone(),
11942            [
11943                ExcerptRange::new(Point::new(0, 0)..Point::new(0, 4)),
11944                ExcerptRange::new(Point::new(1, 0)..Point::new(1, 4)),
11945            ],
11946            cx,
11947        );
11948        assert_eq!(multibuffer.read(cx).text(), "aaaa\nbbbb");
11949        multibuffer
11950    });
11951
11952    let (editor, cx) = cx.add_window_view(|window, cx| build_editor(multibuffer, window, cx));
11953    editor.update_in(cx, |editor, window, cx| {
11954        assert_eq!(editor.text(cx), "aaaa\nbbbb");
11955        editor.change_selections(None, window, cx, |s| {
11956            s.select_ranges([
11957                Point::new(0, 0)..Point::new(0, 0),
11958                Point::new(1, 0)..Point::new(1, 0),
11959            ])
11960        });
11961
11962        editor.handle_input("X", window, cx);
11963        assert_eq!(editor.text(cx), "Xaaaa\nXbbbb");
11964        assert_eq!(
11965            editor.selections.ranges(cx),
11966            [
11967                Point::new(0, 1)..Point::new(0, 1),
11968                Point::new(1, 1)..Point::new(1, 1),
11969            ]
11970        );
11971
11972        // Ensure the cursor's head is respected when deleting across an excerpt boundary.
11973        editor.change_selections(None, window, cx, |s| {
11974            s.select_ranges([Point::new(0, 2)..Point::new(1, 2)])
11975        });
11976        editor.backspace(&Default::default(), window, cx);
11977        assert_eq!(editor.text(cx), "Xa\nbbb");
11978        assert_eq!(
11979            editor.selections.ranges(cx),
11980            [Point::new(1, 0)..Point::new(1, 0)]
11981        );
11982
11983        editor.change_selections(None, window, cx, |s| {
11984            s.select_ranges([Point::new(1, 1)..Point::new(0, 1)])
11985        });
11986        editor.backspace(&Default::default(), window, cx);
11987        assert_eq!(editor.text(cx), "X\nbb");
11988        assert_eq!(
11989            editor.selections.ranges(cx),
11990            [Point::new(0, 1)..Point::new(0, 1)]
11991        );
11992    });
11993}
11994
11995#[gpui::test]
11996fn test_editing_overlapping_excerpts(cx: &mut TestAppContext) {
11997    init_test(cx, |_| {});
11998
11999    let markers = vec![('[', ']').into(), ('(', ')').into()];
12000    let (initial_text, mut excerpt_ranges) = marked_text_ranges_by(
12001        indoc! {"
12002            [aaaa
12003            (bbbb]
12004            cccc)",
12005        },
12006        markers.clone(),
12007    );
12008    let excerpt_ranges = markers.into_iter().map(|marker| {
12009        let context = excerpt_ranges.remove(&marker).unwrap()[0].clone();
12010        ExcerptRange::new(context.clone())
12011    });
12012    let buffer = cx.new(|cx| Buffer::local(initial_text, cx));
12013    let multibuffer = cx.new(|cx| {
12014        let mut multibuffer = MultiBuffer::new(ReadWrite);
12015        multibuffer.push_excerpts(buffer, excerpt_ranges, cx);
12016        multibuffer
12017    });
12018
12019    let (editor, cx) = cx.add_window_view(|window, cx| build_editor(multibuffer, window, cx));
12020    editor.update_in(cx, |editor, window, cx| {
12021        let (expected_text, selection_ranges) = marked_text_ranges(
12022            indoc! {"
12023                aaaa
12024                bˇbbb
12025                bˇbbˇb
12026                cccc"
12027            },
12028            true,
12029        );
12030        assert_eq!(editor.text(cx), expected_text);
12031        editor.change_selections(None, window, cx, |s| s.select_ranges(selection_ranges));
12032
12033        editor.handle_input("X", window, cx);
12034
12035        let (expected_text, expected_selections) = marked_text_ranges(
12036            indoc! {"
12037                aaaa
12038                bXˇbbXb
12039                bXˇbbXˇb
12040                cccc"
12041            },
12042            false,
12043        );
12044        assert_eq!(editor.text(cx), expected_text);
12045        assert_eq!(editor.selections.ranges(cx), expected_selections);
12046
12047        editor.newline(&Newline, window, cx);
12048        let (expected_text, expected_selections) = marked_text_ranges(
12049            indoc! {"
12050                aaaa
12051                bX
12052                ˇbbX
12053                b
12054                bX
12055                ˇbbX
12056                ˇb
12057                cccc"
12058            },
12059            false,
12060        );
12061        assert_eq!(editor.text(cx), expected_text);
12062        assert_eq!(editor.selections.ranges(cx), expected_selections);
12063    });
12064}
12065
12066#[gpui::test]
12067fn test_refresh_selections(cx: &mut TestAppContext) {
12068    init_test(cx, |_| {});
12069
12070    let buffer = cx.new(|cx| Buffer::local(sample_text(3, 4, 'a'), cx));
12071    let mut excerpt1_id = None;
12072    let multibuffer = cx.new(|cx| {
12073        let mut multibuffer = MultiBuffer::new(ReadWrite);
12074        excerpt1_id = multibuffer
12075            .push_excerpts(
12076                buffer.clone(),
12077                [
12078                    ExcerptRange::new(Point::new(0, 0)..Point::new(1, 4)),
12079                    ExcerptRange::new(Point::new(1, 0)..Point::new(2, 4)),
12080                ],
12081                cx,
12082            )
12083            .into_iter()
12084            .next();
12085        assert_eq!(multibuffer.read(cx).text(), "aaaa\nbbbb\nbbbb\ncccc");
12086        multibuffer
12087    });
12088
12089    let editor = cx.add_window(|window, cx| {
12090        let mut editor = build_editor(multibuffer.clone(), window, cx);
12091        let snapshot = editor.snapshot(window, cx);
12092        editor.change_selections(None, window, cx, |s| {
12093            s.select_ranges([Point::new(1, 3)..Point::new(1, 3)])
12094        });
12095        editor.begin_selection(
12096            Point::new(2, 1).to_display_point(&snapshot),
12097            true,
12098            1,
12099            window,
12100            cx,
12101        );
12102        assert_eq!(
12103            editor.selections.ranges(cx),
12104            [
12105                Point::new(1, 3)..Point::new(1, 3),
12106                Point::new(2, 1)..Point::new(2, 1),
12107            ]
12108        );
12109        editor
12110    });
12111
12112    // Refreshing selections is a no-op when excerpts haven't changed.
12113    _ = editor.update(cx, |editor, window, cx| {
12114        editor.change_selections(None, window, cx, |s| s.refresh());
12115        assert_eq!(
12116            editor.selections.ranges(cx),
12117            [
12118                Point::new(1, 3)..Point::new(1, 3),
12119                Point::new(2, 1)..Point::new(2, 1),
12120            ]
12121        );
12122    });
12123
12124    multibuffer.update(cx, |multibuffer, cx| {
12125        multibuffer.remove_excerpts([excerpt1_id.unwrap()], cx);
12126    });
12127    _ = editor.update(cx, |editor, window, cx| {
12128        // Removing an excerpt causes the first selection to become degenerate.
12129        assert_eq!(
12130            editor.selections.ranges(cx),
12131            [
12132                Point::new(0, 0)..Point::new(0, 0),
12133                Point::new(0, 1)..Point::new(0, 1)
12134            ]
12135        );
12136
12137        // Refreshing selections will relocate the first selection to the original buffer
12138        // location.
12139        editor.change_selections(None, window, cx, |s| s.refresh());
12140        assert_eq!(
12141            editor.selections.ranges(cx),
12142            [
12143                Point::new(0, 1)..Point::new(0, 1),
12144                Point::new(0, 3)..Point::new(0, 3)
12145            ]
12146        );
12147        assert!(editor.selections.pending_anchor().is_some());
12148    });
12149}
12150
12151#[gpui::test]
12152fn test_refresh_selections_while_selecting_with_mouse(cx: &mut TestAppContext) {
12153    init_test(cx, |_| {});
12154
12155    let buffer = cx.new(|cx| Buffer::local(sample_text(3, 4, 'a'), cx));
12156    let mut excerpt1_id = None;
12157    let multibuffer = cx.new(|cx| {
12158        let mut multibuffer = MultiBuffer::new(ReadWrite);
12159        excerpt1_id = multibuffer
12160            .push_excerpts(
12161                buffer.clone(),
12162                [
12163                    ExcerptRange::new(Point::new(0, 0)..Point::new(1, 4)),
12164                    ExcerptRange::new(Point::new(1, 0)..Point::new(2, 4)),
12165                ],
12166                cx,
12167            )
12168            .into_iter()
12169            .next();
12170        assert_eq!(multibuffer.read(cx).text(), "aaaa\nbbbb\nbbbb\ncccc");
12171        multibuffer
12172    });
12173
12174    let editor = cx.add_window(|window, cx| {
12175        let mut editor = build_editor(multibuffer.clone(), window, cx);
12176        let snapshot = editor.snapshot(window, cx);
12177        editor.begin_selection(
12178            Point::new(1, 3).to_display_point(&snapshot),
12179            false,
12180            1,
12181            window,
12182            cx,
12183        );
12184        assert_eq!(
12185            editor.selections.ranges(cx),
12186            [Point::new(1, 3)..Point::new(1, 3)]
12187        );
12188        editor
12189    });
12190
12191    multibuffer.update(cx, |multibuffer, cx| {
12192        multibuffer.remove_excerpts([excerpt1_id.unwrap()], cx);
12193    });
12194    _ = editor.update(cx, |editor, window, cx| {
12195        assert_eq!(
12196            editor.selections.ranges(cx),
12197            [Point::new(0, 0)..Point::new(0, 0)]
12198        );
12199
12200        // Ensure we don't panic when selections are refreshed and that the pending selection is finalized.
12201        editor.change_selections(None, window, cx, |s| s.refresh());
12202        assert_eq!(
12203            editor.selections.ranges(cx),
12204            [Point::new(0, 3)..Point::new(0, 3)]
12205        );
12206        assert!(editor.selections.pending_anchor().is_some());
12207    });
12208}
12209
12210#[gpui::test]
12211async fn test_extra_newline_insertion(cx: &mut TestAppContext) {
12212    init_test(cx, |_| {});
12213
12214    let language = Arc::new(
12215        Language::new(
12216            LanguageConfig {
12217                brackets: BracketPairConfig {
12218                    pairs: vec![
12219                        BracketPair {
12220                            start: "{".to_string(),
12221                            end: "}".to_string(),
12222                            close: true,
12223                            surround: true,
12224                            newline: true,
12225                        },
12226                        BracketPair {
12227                            start: "/* ".to_string(),
12228                            end: " */".to_string(),
12229                            close: true,
12230                            surround: true,
12231                            newline: true,
12232                        },
12233                    ],
12234                    ..Default::default()
12235                },
12236                ..Default::default()
12237            },
12238            Some(tree_sitter_rust::LANGUAGE.into()),
12239        )
12240        .with_indents_query("")
12241        .unwrap(),
12242    );
12243
12244    let text = concat!(
12245        "{   }\n",     //
12246        "  x\n",       //
12247        "  /*   */\n", //
12248        "x\n",         //
12249        "{{} }\n",     //
12250    );
12251
12252    let buffer = cx.new(|cx| Buffer::local(text, cx).with_language(language, cx));
12253    let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
12254    let (editor, cx) = cx.add_window_view(|window, cx| build_editor(buffer, window, cx));
12255    editor
12256        .condition::<crate::EditorEvent>(cx, |editor, cx| !editor.buffer.read(cx).is_parsing(cx))
12257        .await;
12258
12259    editor.update_in(cx, |editor, window, cx| {
12260        editor.change_selections(None, window, cx, |s| {
12261            s.select_display_ranges([
12262                DisplayPoint::new(DisplayRow(0), 2)..DisplayPoint::new(DisplayRow(0), 3),
12263                DisplayPoint::new(DisplayRow(2), 5)..DisplayPoint::new(DisplayRow(2), 5),
12264                DisplayPoint::new(DisplayRow(4), 4)..DisplayPoint::new(DisplayRow(4), 4),
12265            ])
12266        });
12267        editor.newline(&Newline, window, cx);
12268
12269        assert_eq!(
12270            editor.buffer().read(cx).read(cx).text(),
12271            concat!(
12272                "{ \n",    // Suppress rustfmt
12273                "\n",      //
12274                "}\n",     //
12275                "  x\n",   //
12276                "  /* \n", //
12277                "  \n",    //
12278                "  */\n",  //
12279                "x\n",     //
12280                "{{} \n",  //
12281                "}\n",     //
12282            )
12283        );
12284    });
12285}
12286
12287#[gpui::test]
12288fn test_highlighted_ranges(cx: &mut TestAppContext) {
12289    init_test(cx, |_| {});
12290
12291    let editor = cx.add_window(|window, cx| {
12292        let buffer = MultiBuffer::build_simple(&sample_text(16, 8, 'a'), cx);
12293        build_editor(buffer.clone(), window, cx)
12294    });
12295
12296    _ = editor.update(cx, |editor, window, cx| {
12297        struct Type1;
12298        struct Type2;
12299
12300        let buffer = editor.buffer.read(cx).snapshot(cx);
12301
12302        let anchor_range =
12303            |range: Range<Point>| buffer.anchor_after(range.start)..buffer.anchor_after(range.end);
12304
12305        editor.highlight_background::<Type1>(
12306            &[
12307                anchor_range(Point::new(2, 1)..Point::new(2, 3)),
12308                anchor_range(Point::new(4, 2)..Point::new(4, 4)),
12309                anchor_range(Point::new(6, 3)..Point::new(6, 5)),
12310                anchor_range(Point::new(8, 4)..Point::new(8, 6)),
12311            ],
12312            |_| Hsla::red(),
12313            cx,
12314        );
12315        editor.highlight_background::<Type2>(
12316            &[
12317                anchor_range(Point::new(3, 2)..Point::new(3, 5)),
12318                anchor_range(Point::new(5, 3)..Point::new(5, 6)),
12319                anchor_range(Point::new(7, 4)..Point::new(7, 7)),
12320                anchor_range(Point::new(9, 5)..Point::new(9, 8)),
12321            ],
12322            |_| Hsla::green(),
12323            cx,
12324        );
12325
12326        let snapshot = editor.snapshot(window, cx);
12327        let mut highlighted_ranges = editor.background_highlights_in_range(
12328            anchor_range(Point::new(3, 4)..Point::new(7, 4)),
12329            &snapshot,
12330            cx.theme().colors(),
12331        );
12332        // Enforce a consistent ordering based on color without relying on the ordering of the
12333        // highlight's `TypeId` which is non-executor.
12334        highlighted_ranges.sort_unstable_by_key(|(_, color)| *color);
12335        assert_eq!(
12336            highlighted_ranges,
12337            &[
12338                (
12339                    DisplayPoint::new(DisplayRow(4), 2)..DisplayPoint::new(DisplayRow(4), 4),
12340                    Hsla::red(),
12341                ),
12342                (
12343                    DisplayPoint::new(DisplayRow(6), 3)..DisplayPoint::new(DisplayRow(6), 5),
12344                    Hsla::red(),
12345                ),
12346                (
12347                    DisplayPoint::new(DisplayRow(3), 2)..DisplayPoint::new(DisplayRow(3), 5),
12348                    Hsla::green(),
12349                ),
12350                (
12351                    DisplayPoint::new(DisplayRow(5), 3)..DisplayPoint::new(DisplayRow(5), 6),
12352                    Hsla::green(),
12353                ),
12354            ]
12355        );
12356        assert_eq!(
12357            editor.background_highlights_in_range(
12358                anchor_range(Point::new(5, 6)..Point::new(6, 4)),
12359                &snapshot,
12360                cx.theme().colors(),
12361            ),
12362            &[(
12363                DisplayPoint::new(DisplayRow(6), 3)..DisplayPoint::new(DisplayRow(6), 5),
12364                Hsla::red(),
12365            )]
12366        );
12367    });
12368}
12369
12370#[gpui::test]
12371async fn test_following(cx: &mut TestAppContext) {
12372    init_test(cx, |_| {});
12373
12374    let fs = FakeFs::new(cx.executor());
12375    let project = Project::test(fs, ["/file.rs".as_ref()], cx).await;
12376
12377    let buffer = project.update(cx, |project, cx| {
12378        let buffer = project.create_local_buffer(&sample_text(16, 8, 'a'), None, cx);
12379        cx.new(|cx| MultiBuffer::singleton(buffer, cx))
12380    });
12381    let leader = cx.add_window(|window, cx| build_editor(buffer.clone(), window, cx));
12382    let follower = cx.update(|cx| {
12383        cx.open_window(
12384            WindowOptions {
12385                window_bounds: Some(WindowBounds::Windowed(Bounds::from_corners(
12386                    gpui::Point::new(px(0.), px(0.)),
12387                    gpui::Point::new(px(10.), px(80.)),
12388                ))),
12389                ..Default::default()
12390            },
12391            |window, cx| cx.new(|cx| build_editor(buffer.clone(), window, cx)),
12392        )
12393        .unwrap()
12394    });
12395
12396    let is_still_following = Rc::new(RefCell::new(true));
12397    let follower_edit_event_count = Rc::new(RefCell::new(0));
12398    let pending_update = Rc::new(RefCell::new(None));
12399    let leader_entity = leader.root(cx).unwrap();
12400    let follower_entity = follower.root(cx).unwrap();
12401    _ = follower.update(cx, {
12402        let update = pending_update.clone();
12403        let is_still_following = is_still_following.clone();
12404        let follower_edit_event_count = follower_edit_event_count.clone();
12405        |_, window, cx| {
12406            cx.subscribe_in(
12407                &leader_entity,
12408                window,
12409                move |_, leader, event, window, cx| {
12410                    leader.read(cx).add_event_to_update_proto(
12411                        event,
12412                        &mut update.borrow_mut(),
12413                        window,
12414                        cx,
12415                    );
12416                },
12417            )
12418            .detach();
12419
12420            cx.subscribe_in(
12421                &follower_entity,
12422                window,
12423                move |_, _, event: &EditorEvent, _window, _cx| {
12424                    if matches!(Editor::to_follow_event(event), Some(FollowEvent::Unfollow)) {
12425                        *is_still_following.borrow_mut() = false;
12426                    }
12427
12428                    if let EditorEvent::BufferEdited = event {
12429                        *follower_edit_event_count.borrow_mut() += 1;
12430                    }
12431                },
12432            )
12433            .detach();
12434        }
12435    });
12436
12437    // Update the selections only
12438    _ = leader.update(cx, |leader, window, cx| {
12439        leader.change_selections(None, window, cx, |s| s.select_ranges([1..1]));
12440    });
12441    follower
12442        .update(cx, |follower, window, cx| {
12443            follower.apply_update_proto(
12444                &project,
12445                pending_update.borrow_mut().take().unwrap(),
12446                window,
12447                cx,
12448            )
12449        })
12450        .unwrap()
12451        .await
12452        .unwrap();
12453    _ = follower.update(cx, |follower, _, cx| {
12454        assert_eq!(follower.selections.ranges(cx), vec![1..1]);
12455    });
12456    assert!(*is_still_following.borrow());
12457    assert_eq!(*follower_edit_event_count.borrow(), 0);
12458
12459    // Update the scroll position only
12460    _ = leader.update(cx, |leader, window, cx| {
12461        leader.set_scroll_position(gpui::Point::new(1.5, 3.5), window, cx);
12462    });
12463    follower
12464        .update(cx, |follower, window, cx| {
12465            follower.apply_update_proto(
12466                &project,
12467                pending_update.borrow_mut().take().unwrap(),
12468                window,
12469                cx,
12470            )
12471        })
12472        .unwrap()
12473        .await
12474        .unwrap();
12475    assert_eq!(
12476        follower
12477            .update(cx, |follower, _, cx| follower.scroll_position(cx))
12478            .unwrap(),
12479        gpui::Point::new(1.5, 3.5)
12480    );
12481    assert!(*is_still_following.borrow());
12482    assert_eq!(*follower_edit_event_count.borrow(), 0);
12483
12484    // Update the selections and scroll position. The follower's scroll position is updated
12485    // via autoscroll, not via the leader's exact scroll position.
12486    _ = leader.update(cx, |leader, window, cx| {
12487        leader.change_selections(None, window, cx, |s| s.select_ranges([0..0]));
12488        leader.request_autoscroll(Autoscroll::newest(), cx);
12489        leader.set_scroll_position(gpui::Point::new(1.5, 3.5), window, cx);
12490    });
12491    follower
12492        .update(cx, |follower, window, cx| {
12493            follower.apply_update_proto(
12494                &project,
12495                pending_update.borrow_mut().take().unwrap(),
12496                window,
12497                cx,
12498            )
12499        })
12500        .unwrap()
12501        .await
12502        .unwrap();
12503    _ = follower.update(cx, |follower, _, cx| {
12504        assert_eq!(follower.scroll_position(cx), gpui::Point::new(1.5, 0.0));
12505        assert_eq!(follower.selections.ranges(cx), vec![0..0]);
12506    });
12507    assert!(*is_still_following.borrow());
12508
12509    // Creating a pending selection that precedes another selection
12510    _ = leader.update(cx, |leader, window, cx| {
12511        leader.change_selections(None, window, cx, |s| s.select_ranges([1..1]));
12512        leader.begin_selection(DisplayPoint::new(DisplayRow(0), 0), true, 1, window, cx);
12513    });
12514    follower
12515        .update(cx, |follower, window, cx| {
12516            follower.apply_update_proto(
12517                &project,
12518                pending_update.borrow_mut().take().unwrap(),
12519                window,
12520                cx,
12521            )
12522        })
12523        .unwrap()
12524        .await
12525        .unwrap();
12526    _ = follower.update(cx, |follower, _, cx| {
12527        assert_eq!(follower.selections.ranges(cx), vec![0..0, 1..1]);
12528    });
12529    assert!(*is_still_following.borrow());
12530
12531    // Extend the pending selection so that it surrounds another selection
12532    _ = leader.update(cx, |leader, window, cx| {
12533        leader.extend_selection(DisplayPoint::new(DisplayRow(0), 2), 1, window, cx);
12534    });
12535    follower
12536        .update(cx, |follower, window, cx| {
12537            follower.apply_update_proto(
12538                &project,
12539                pending_update.borrow_mut().take().unwrap(),
12540                window,
12541                cx,
12542            )
12543        })
12544        .unwrap()
12545        .await
12546        .unwrap();
12547    _ = follower.update(cx, |follower, _, cx| {
12548        assert_eq!(follower.selections.ranges(cx), vec![0..2]);
12549    });
12550
12551    // Scrolling locally breaks the follow
12552    _ = follower.update(cx, |follower, window, cx| {
12553        let top_anchor = follower.buffer().read(cx).read(cx).anchor_after(0);
12554        follower.set_scroll_anchor(
12555            ScrollAnchor {
12556                anchor: top_anchor,
12557                offset: gpui::Point::new(0.0, 0.5),
12558            },
12559            window,
12560            cx,
12561        );
12562    });
12563    assert!(!(*is_still_following.borrow()));
12564}
12565
12566#[gpui::test]
12567async fn test_following_with_multiple_excerpts(cx: &mut TestAppContext) {
12568    init_test(cx, |_| {});
12569
12570    let fs = FakeFs::new(cx.executor());
12571    let project = Project::test(fs, ["/file.rs".as_ref()], cx).await;
12572    let workspace = cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
12573    let pane = workspace
12574        .update(cx, |workspace, _, _| workspace.active_pane().clone())
12575        .unwrap();
12576
12577    let cx = &mut VisualTestContext::from_window(*workspace.deref(), cx);
12578
12579    let leader = pane.update_in(cx, |_, window, cx| {
12580        let multibuffer = cx.new(|_| MultiBuffer::new(ReadWrite));
12581        cx.new(|cx| build_editor(multibuffer.clone(), window, cx))
12582    });
12583
12584    // Start following the editor when it has no excerpts.
12585    let mut state_message =
12586        leader.update_in(cx, |leader, window, cx| leader.to_state_proto(window, cx));
12587    let workspace_entity = workspace.root(cx).unwrap();
12588    let follower_1 = cx
12589        .update_window(*workspace.deref(), |_, window, cx| {
12590            Editor::from_state_proto(
12591                workspace_entity,
12592                ViewId {
12593                    creator: Default::default(),
12594                    id: 0,
12595                },
12596                &mut state_message,
12597                window,
12598                cx,
12599            )
12600        })
12601        .unwrap()
12602        .unwrap()
12603        .await
12604        .unwrap();
12605
12606    let update_message = Rc::new(RefCell::new(None));
12607    follower_1.update_in(cx, {
12608        let update = update_message.clone();
12609        |_, window, cx| {
12610            cx.subscribe_in(&leader, window, move |_, leader, event, window, cx| {
12611                leader.read(cx).add_event_to_update_proto(
12612                    event,
12613                    &mut update.borrow_mut(),
12614                    window,
12615                    cx,
12616                );
12617            })
12618            .detach();
12619        }
12620    });
12621
12622    let (buffer_1, buffer_2) = project.update(cx, |project, cx| {
12623        (
12624            project.create_local_buffer("abc\ndef\nghi\njkl\n", None, cx),
12625            project.create_local_buffer("mno\npqr\nstu\nvwx\n", None, cx),
12626        )
12627    });
12628
12629    // Insert some excerpts.
12630    leader.update(cx, |leader, cx| {
12631        leader.buffer.update(cx, |multibuffer, cx| {
12632            let excerpt_ids = multibuffer.push_excerpts(
12633                buffer_1.clone(),
12634                [
12635                    ExcerptRange::new(1..6),
12636                    ExcerptRange::new(12..15),
12637                    ExcerptRange::new(0..3),
12638                ],
12639                cx,
12640            );
12641            multibuffer.insert_excerpts_after(
12642                excerpt_ids[0],
12643                buffer_2.clone(),
12644                [ExcerptRange::new(8..12), ExcerptRange::new(0..6)],
12645                cx,
12646            );
12647        });
12648    });
12649
12650    // Apply the update of adding the excerpts.
12651    follower_1
12652        .update_in(cx, |follower, window, cx| {
12653            follower.apply_update_proto(
12654                &project,
12655                update_message.borrow().clone().unwrap(),
12656                window,
12657                cx,
12658            )
12659        })
12660        .await
12661        .unwrap();
12662    assert_eq!(
12663        follower_1.update(cx, |editor, cx| editor.text(cx)),
12664        leader.update(cx, |editor, cx| editor.text(cx))
12665    );
12666    update_message.borrow_mut().take();
12667
12668    // Start following separately after it already has excerpts.
12669    let mut state_message =
12670        leader.update_in(cx, |leader, window, cx| leader.to_state_proto(window, cx));
12671    let workspace_entity = workspace.root(cx).unwrap();
12672    let follower_2 = cx
12673        .update_window(*workspace.deref(), |_, window, cx| {
12674            Editor::from_state_proto(
12675                workspace_entity,
12676                ViewId {
12677                    creator: Default::default(),
12678                    id: 0,
12679                },
12680                &mut state_message,
12681                window,
12682                cx,
12683            )
12684        })
12685        .unwrap()
12686        .unwrap()
12687        .await
12688        .unwrap();
12689    assert_eq!(
12690        follower_2.update(cx, |editor, cx| editor.text(cx)),
12691        leader.update(cx, |editor, cx| editor.text(cx))
12692    );
12693
12694    // Remove some excerpts.
12695    leader.update(cx, |leader, cx| {
12696        leader.buffer.update(cx, |multibuffer, cx| {
12697            let excerpt_ids = multibuffer.excerpt_ids();
12698            multibuffer.remove_excerpts([excerpt_ids[1], excerpt_ids[2]], cx);
12699            multibuffer.remove_excerpts([excerpt_ids[0]], cx);
12700        });
12701    });
12702
12703    // Apply the update of removing the excerpts.
12704    follower_1
12705        .update_in(cx, |follower, window, cx| {
12706            follower.apply_update_proto(
12707                &project,
12708                update_message.borrow().clone().unwrap(),
12709                window,
12710                cx,
12711            )
12712        })
12713        .await
12714        .unwrap();
12715    follower_2
12716        .update_in(cx, |follower, window, cx| {
12717            follower.apply_update_proto(
12718                &project,
12719                update_message.borrow().clone().unwrap(),
12720                window,
12721                cx,
12722            )
12723        })
12724        .await
12725        .unwrap();
12726    update_message.borrow_mut().take();
12727    assert_eq!(
12728        follower_1.update(cx, |editor, cx| editor.text(cx)),
12729        leader.update(cx, |editor, cx| editor.text(cx))
12730    );
12731}
12732
12733#[gpui::test]
12734async fn go_to_prev_overlapping_diagnostic(executor: BackgroundExecutor, cx: &mut TestAppContext) {
12735    init_test(cx, |_| {});
12736
12737    let mut cx = EditorTestContext::new(cx).await;
12738    let lsp_store =
12739        cx.update_editor(|editor, _, cx| editor.project.as_ref().unwrap().read(cx).lsp_store());
12740
12741    cx.set_state(indoc! {"
12742        ˇfn func(abc def: i32) -> u32 {
12743        }
12744    "});
12745
12746    cx.update(|_, cx| {
12747        lsp_store.update(cx, |lsp_store, cx| {
12748            lsp_store
12749                .update_diagnostics(
12750                    LanguageServerId(0),
12751                    lsp::PublishDiagnosticsParams {
12752                        uri: lsp::Url::from_file_path(path!("/root/file")).unwrap(),
12753                        version: None,
12754                        diagnostics: vec![
12755                            lsp::Diagnostic {
12756                                range: lsp::Range::new(
12757                                    lsp::Position::new(0, 11),
12758                                    lsp::Position::new(0, 12),
12759                                ),
12760                                severity: Some(lsp::DiagnosticSeverity::ERROR),
12761                                ..Default::default()
12762                            },
12763                            lsp::Diagnostic {
12764                                range: lsp::Range::new(
12765                                    lsp::Position::new(0, 12),
12766                                    lsp::Position::new(0, 15),
12767                                ),
12768                                severity: Some(lsp::DiagnosticSeverity::ERROR),
12769                                ..Default::default()
12770                            },
12771                            lsp::Diagnostic {
12772                                range: lsp::Range::new(
12773                                    lsp::Position::new(0, 25),
12774                                    lsp::Position::new(0, 28),
12775                                ),
12776                                severity: Some(lsp::DiagnosticSeverity::ERROR),
12777                                ..Default::default()
12778                            },
12779                        ],
12780                    },
12781                    &[],
12782                    cx,
12783                )
12784                .unwrap()
12785        });
12786    });
12787
12788    executor.run_until_parked();
12789
12790    cx.update_editor(|editor, window, cx| {
12791        editor.go_to_prev_diagnostic(&GoToPreviousDiagnostic, window, cx);
12792    });
12793
12794    cx.assert_editor_state(indoc! {"
12795        fn func(abc def: i32) -> ˇu32 {
12796        }
12797    "});
12798
12799    cx.update_editor(|editor, window, cx| {
12800        editor.go_to_prev_diagnostic(&GoToPreviousDiagnostic, window, cx);
12801    });
12802
12803    cx.assert_editor_state(indoc! {"
12804        fn func(abc ˇdef: i32) -> u32 {
12805        }
12806    "});
12807
12808    cx.update_editor(|editor, window, cx| {
12809        editor.go_to_prev_diagnostic(&GoToPreviousDiagnostic, window, cx);
12810    });
12811
12812    cx.assert_editor_state(indoc! {"
12813        fn func(abcˇ def: i32) -> u32 {
12814        }
12815    "});
12816
12817    cx.update_editor(|editor, window, cx| {
12818        editor.go_to_prev_diagnostic(&GoToPreviousDiagnostic, window, cx);
12819    });
12820
12821    cx.assert_editor_state(indoc! {"
12822        fn func(abc def: i32) -> ˇu32 {
12823        }
12824    "});
12825}
12826
12827#[gpui::test]
12828async fn test_diagnostics_with_links(cx: &mut TestAppContext) {
12829    init_test(cx, |_| {});
12830
12831    let mut cx = EditorTestContext::new(cx).await;
12832
12833    cx.set_state(indoc! {"
12834        fn func(abˇc def: i32) -> u32 {
12835        }
12836    "});
12837    let lsp_store =
12838        cx.update_editor(|editor, _, cx| editor.project.as_ref().unwrap().read(cx).lsp_store());
12839
12840    cx.update(|_, cx| {
12841        lsp_store.update(cx, |lsp_store, cx| {
12842            lsp_store.update_diagnostics(
12843                LanguageServerId(0),
12844                lsp::PublishDiagnosticsParams {
12845                    uri: lsp::Url::from_file_path(path!("/root/file")).unwrap(),
12846                    version: None,
12847                    diagnostics: vec![lsp::Diagnostic {
12848                        range: lsp::Range::new(lsp::Position::new(0, 8), lsp::Position::new(0, 12)),
12849                        severity: Some(lsp::DiagnosticSeverity::ERROR),
12850                        message: "we've had problems with <https://link.one>, and <https://link.two> is broken".to_string(),
12851                        ..Default::default()
12852                    }],
12853                },
12854                &[],
12855                cx,
12856            )
12857        })
12858    }).unwrap();
12859    cx.run_until_parked();
12860    cx.update_editor(|editor, window, cx| {
12861        hover_popover::hover(editor, &Default::default(), window, cx)
12862    });
12863    cx.run_until_parked();
12864    cx.update_editor(|editor, _, _| assert!(editor.hover_state.diagnostic_popover.is_some()))
12865}
12866
12867#[gpui::test]
12868async fn test_go_to_hunk(executor: BackgroundExecutor, cx: &mut TestAppContext) {
12869    init_test(cx, |_| {});
12870
12871    let mut cx = EditorTestContext::new(cx).await;
12872
12873    let diff_base = r#"
12874        use some::mod;
12875
12876        const A: u32 = 42;
12877
12878        fn main() {
12879            println!("hello");
12880
12881            println!("world");
12882        }
12883        "#
12884    .unindent();
12885
12886    // Edits are modified, removed, modified, added
12887    cx.set_state(
12888        &r#"
12889        use some::modified;
12890
12891        ˇ
12892        fn main() {
12893            println!("hello there");
12894
12895            println!("around the");
12896            println!("world");
12897        }
12898        "#
12899        .unindent(),
12900    );
12901
12902    cx.set_head_text(&diff_base);
12903    executor.run_until_parked();
12904
12905    cx.update_editor(|editor, window, cx| {
12906        //Wrap around the bottom of the buffer
12907        for _ in 0..3 {
12908            editor.go_to_next_hunk(&GoToHunk, window, cx);
12909        }
12910    });
12911
12912    cx.assert_editor_state(
12913        &r#"
12914        ˇuse some::modified;
12915
12916
12917        fn main() {
12918            println!("hello there");
12919
12920            println!("around the");
12921            println!("world");
12922        }
12923        "#
12924        .unindent(),
12925    );
12926
12927    cx.update_editor(|editor, window, cx| {
12928        //Wrap around the top of the buffer
12929        for _ in 0..2 {
12930            editor.go_to_prev_hunk(&GoToPreviousHunk, window, cx);
12931        }
12932    });
12933
12934    cx.assert_editor_state(
12935        &r#"
12936        use some::modified;
12937
12938
12939        fn main() {
12940        ˇ    println!("hello there");
12941
12942            println!("around the");
12943            println!("world");
12944        }
12945        "#
12946        .unindent(),
12947    );
12948
12949    cx.update_editor(|editor, window, cx| {
12950        editor.go_to_prev_hunk(&GoToPreviousHunk, window, cx);
12951    });
12952
12953    cx.assert_editor_state(
12954        &r#"
12955        use some::modified;
12956
12957        ˇ
12958        fn main() {
12959            println!("hello there");
12960
12961            println!("around the");
12962            println!("world");
12963        }
12964        "#
12965        .unindent(),
12966    );
12967
12968    cx.update_editor(|editor, window, cx| {
12969        editor.go_to_prev_hunk(&GoToPreviousHunk, window, cx);
12970    });
12971
12972    cx.assert_editor_state(
12973        &r#"
12974        ˇuse some::modified;
12975
12976
12977        fn main() {
12978            println!("hello there");
12979
12980            println!("around the");
12981            println!("world");
12982        }
12983        "#
12984        .unindent(),
12985    );
12986
12987    cx.update_editor(|editor, window, cx| {
12988        for _ in 0..2 {
12989            editor.go_to_prev_hunk(&GoToPreviousHunk, window, cx);
12990        }
12991    });
12992
12993    cx.assert_editor_state(
12994        &r#"
12995        use some::modified;
12996
12997
12998        fn main() {
12999        ˇ    println!("hello there");
13000
13001            println!("around the");
13002            println!("world");
13003        }
13004        "#
13005        .unindent(),
13006    );
13007
13008    cx.update_editor(|editor, window, cx| {
13009        editor.fold(&Fold, window, cx);
13010    });
13011
13012    cx.update_editor(|editor, window, cx| {
13013        editor.go_to_next_hunk(&GoToHunk, window, cx);
13014    });
13015
13016    cx.assert_editor_state(
13017        &r#"
13018        ˇuse some::modified;
13019
13020
13021        fn main() {
13022            println!("hello there");
13023
13024            println!("around the");
13025            println!("world");
13026        }
13027        "#
13028        .unindent(),
13029    );
13030}
13031
13032#[test]
13033fn test_split_words() {
13034    fn split(text: &str) -> Vec<&str> {
13035        split_words(text).collect()
13036    }
13037
13038    assert_eq!(split("HelloWorld"), &["Hello", "World"]);
13039    assert_eq!(split("hello_world"), &["hello_", "world"]);
13040    assert_eq!(split("_hello_world_"), &["_", "hello_", "world_"]);
13041    assert_eq!(split("Hello_World"), &["Hello_", "World"]);
13042    assert_eq!(split("helloWOrld"), &["hello", "WOrld"]);
13043    assert_eq!(split("helloworld"), &["helloworld"]);
13044
13045    assert_eq!(split(":do_the_thing"), &[":", "do_", "the_", "thing"]);
13046}
13047
13048#[gpui::test]
13049async fn test_move_to_enclosing_bracket(cx: &mut TestAppContext) {
13050    init_test(cx, |_| {});
13051
13052    let mut cx = EditorLspTestContext::new_typescript(Default::default(), cx).await;
13053    let mut assert = |before, after| {
13054        let _state_context = cx.set_state(before);
13055        cx.run_until_parked();
13056        cx.update_editor(|editor, window, cx| {
13057            editor.move_to_enclosing_bracket(&MoveToEnclosingBracket, window, cx)
13058        });
13059        cx.run_until_parked();
13060        cx.assert_editor_state(after);
13061    };
13062
13063    // Outside bracket jumps to outside of matching bracket
13064    assert("console.logˇ(var);", "console.log(var)ˇ;");
13065    assert("console.log(var)ˇ;", "console.logˇ(var);");
13066
13067    // Inside bracket jumps to inside of matching bracket
13068    assert("console.log(ˇvar);", "console.log(varˇ);");
13069    assert("console.log(varˇ);", "console.log(ˇvar);");
13070
13071    // When outside a bracket and inside, favor jumping to the inside bracket
13072    assert(
13073        "console.log('foo', [1, 2, 3]ˇ);",
13074        "console.log(ˇ'foo', [1, 2, 3]);",
13075    );
13076    assert(
13077        "console.log(ˇ'foo', [1, 2, 3]);",
13078        "console.log('foo', [1, 2, 3]ˇ);",
13079    );
13080
13081    // Bias forward if two options are equally likely
13082    assert(
13083        "let result = curried_fun()ˇ();",
13084        "let result = curried_fun()()ˇ;",
13085    );
13086
13087    // If directly adjacent to a smaller pair but inside a larger (not adjacent), pick the smaller
13088    assert(
13089        indoc! {"
13090            function test() {
13091                console.log('test')ˇ
13092            }"},
13093        indoc! {"
13094            function test() {
13095                console.logˇ('test')
13096            }"},
13097    );
13098}
13099
13100#[gpui::test]
13101async fn test_on_type_formatting_not_triggered(cx: &mut TestAppContext) {
13102    init_test(cx, |_| {});
13103
13104    let fs = FakeFs::new(cx.executor());
13105    fs.insert_tree(
13106        path!("/a"),
13107        json!({
13108            "main.rs": "fn main() { let a = 5; }",
13109            "other.rs": "// Test file",
13110        }),
13111    )
13112    .await;
13113    let project = Project::test(fs, [path!("/a").as_ref()], cx).await;
13114
13115    let language_registry = project.read_with(cx, |project, _| project.languages().clone());
13116    language_registry.add(Arc::new(Language::new(
13117        LanguageConfig {
13118            name: "Rust".into(),
13119            matcher: LanguageMatcher {
13120                path_suffixes: vec!["rs".to_string()],
13121                ..Default::default()
13122            },
13123            brackets: BracketPairConfig {
13124                pairs: vec![BracketPair {
13125                    start: "{".to_string(),
13126                    end: "}".to_string(),
13127                    close: true,
13128                    surround: true,
13129                    newline: true,
13130                }],
13131                disabled_scopes_by_bracket_ix: Vec::new(),
13132            },
13133            ..Default::default()
13134        },
13135        Some(tree_sitter_rust::LANGUAGE.into()),
13136    )));
13137    let mut fake_servers = language_registry.register_fake_lsp(
13138        "Rust",
13139        FakeLspAdapter {
13140            capabilities: lsp::ServerCapabilities {
13141                document_on_type_formatting_provider: Some(lsp::DocumentOnTypeFormattingOptions {
13142                    first_trigger_character: "{".to_string(),
13143                    more_trigger_character: None,
13144                }),
13145                ..Default::default()
13146            },
13147            ..Default::default()
13148        },
13149    );
13150
13151    let workspace = cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
13152
13153    let cx = &mut VisualTestContext::from_window(*workspace, cx);
13154
13155    let worktree_id = workspace
13156        .update(cx, |workspace, _, cx| {
13157            workspace.project().update(cx, |project, cx| {
13158                project.worktrees(cx).next().unwrap().read(cx).id()
13159            })
13160        })
13161        .unwrap();
13162
13163    let buffer = project
13164        .update(cx, |project, cx| {
13165            project.open_local_buffer(path!("/a/main.rs"), cx)
13166        })
13167        .await
13168        .unwrap();
13169    let editor_handle = workspace
13170        .update(cx, |workspace, window, cx| {
13171            workspace.open_path((worktree_id, "main.rs"), None, true, window, cx)
13172        })
13173        .unwrap()
13174        .await
13175        .unwrap()
13176        .downcast::<Editor>()
13177        .unwrap();
13178
13179    cx.executor().start_waiting();
13180    let fake_server = fake_servers.next().await.unwrap();
13181
13182    fake_server.set_request_handler::<lsp::request::OnTypeFormatting, _, _>(
13183        |params, _| async move {
13184            assert_eq!(
13185                params.text_document_position.text_document.uri,
13186                lsp::Url::from_file_path(path!("/a/main.rs")).unwrap(),
13187            );
13188            assert_eq!(
13189                params.text_document_position.position,
13190                lsp::Position::new(0, 21),
13191            );
13192
13193            Ok(Some(vec![lsp::TextEdit {
13194                new_text: "]".to_string(),
13195                range: lsp::Range::new(lsp::Position::new(0, 22), lsp::Position::new(0, 22)),
13196            }]))
13197        },
13198    );
13199
13200    editor_handle.update_in(cx, |editor, window, cx| {
13201        window.focus(&editor.focus_handle(cx));
13202        editor.change_selections(None, window, cx, |s| {
13203            s.select_ranges([Point::new(0, 21)..Point::new(0, 20)])
13204        });
13205        editor.handle_input("{", window, cx);
13206    });
13207
13208    cx.executor().run_until_parked();
13209
13210    buffer.update(cx, |buffer, _| {
13211        assert_eq!(
13212            buffer.text(),
13213            "fn main() { let a = {5}; }",
13214            "No extra braces from on type formatting should appear in the buffer"
13215        )
13216    });
13217}
13218
13219#[gpui::test]
13220async fn test_language_server_restart_due_to_settings_change(cx: &mut TestAppContext) {
13221    init_test(cx, |_| {});
13222
13223    let fs = FakeFs::new(cx.executor());
13224    fs.insert_tree(
13225        path!("/a"),
13226        json!({
13227            "main.rs": "fn main() { let a = 5; }",
13228            "other.rs": "// Test file",
13229        }),
13230    )
13231    .await;
13232
13233    let project = Project::test(fs, [path!("/a").as_ref()], cx).await;
13234
13235    let server_restarts = Arc::new(AtomicUsize::new(0));
13236    let closure_restarts = Arc::clone(&server_restarts);
13237    let language_server_name = "test language server";
13238    let language_name: LanguageName = "Rust".into();
13239
13240    let language_registry = project.read_with(cx, |project, _| project.languages().clone());
13241    language_registry.add(Arc::new(Language::new(
13242        LanguageConfig {
13243            name: language_name.clone(),
13244            matcher: LanguageMatcher {
13245                path_suffixes: vec!["rs".to_string()],
13246                ..Default::default()
13247            },
13248            ..Default::default()
13249        },
13250        Some(tree_sitter_rust::LANGUAGE.into()),
13251    )));
13252    let mut fake_servers = language_registry.register_fake_lsp(
13253        "Rust",
13254        FakeLspAdapter {
13255            name: language_server_name,
13256            initialization_options: Some(json!({
13257                "testOptionValue": true
13258            })),
13259            initializer: Some(Box::new(move |fake_server| {
13260                let task_restarts = Arc::clone(&closure_restarts);
13261                fake_server.set_request_handler::<lsp::request::Shutdown, _, _>(move |_, _| {
13262                    task_restarts.fetch_add(1, atomic::Ordering::Release);
13263                    futures::future::ready(Ok(()))
13264                });
13265            })),
13266            ..Default::default()
13267        },
13268    );
13269
13270    let _window = cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
13271    let _buffer = project
13272        .update(cx, |project, cx| {
13273            project.open_local_buffer_with_lsp(path!("/a/main.rs"), cx)
13274        })
13275        .await
13276        .unwrap();
13277    let _fake_server = fake_servers.next().await.unwrap();
13278    update_test_language_settings(cx, |language_settings| {
13279        language_settings.languages.insert(
13280            language_name.clone(),
13281            LanguageSettingsContent {
13282                tab_size: NonZeroU32::new(8),
13283                ..Default::default()
13284            },
13285        );
13286    });
13287    cx.executor().run_until_parked();
13288    assert_eq!(
13289        server_restarts.load(atomic::Ordering::Acquire),
13290        0,
13291        "Should not restart LSP server on an unrelated change"
13292    );
13293
13294    update_test_project_settings(cx, |project_settings| {
13295        project_settings.lsp.insert(
13296            "Some other server name".into(),
13297            LspSettings {
13298                binary: None,
13299                settings: None,
13300                initialization_options: Some(json!({
13301                    "some other init value": false
13302                })),
13303                enable_lsp_tasks: false,
13304            },
13305        );
13306    });
13307    cx.executor().run_until_parked();
13308    assert_eq!(
13309        server_restarts.load(atomic::Ordering::Acquire),
13310        0,
13311        "Should not restart LSP server on an unrelated LSP settings change"
13312    );
13313
13314    update_test_project_settings(cx, |project_settings| {
13315        project_settings.lsp.insert(
13316            language_server_name.into(),
13317            LspSettings {
13318                binary: None,
13319                settings: None,
13320                initialization_options: Some(json!({
13321                    "anotherInitValue": false
13322                })),
13323                enable_lsp_tasks: false,
13324            },
13325        );
13326    });
13327    cx.executor().run_until_parked();
13328    assert_eq!(
13329        server_restarts.load(atomic::Ordering::Acquire),
13330        1,
13331        "Should restart LSP server on a related LSP settings change"
13332    );
13333
13334    update_test_project_settings(cx, |project_settings| {
13335        project_settings.lsp.insert(
13336            language_server_name.into(),
13337            LspSettings {
13338                binary: None,
13339                settings: None,
13340                initialization_options: Some(json!({
13341                    "anotherInitValue": false
13342                })),
13343                enable_lsp_tasks: false,
13344            },
13345        );
13346    });
13347    cx.executor().run_until_parked();
13348    assert_eq!(
13349        server_restarts.load(atomic::Ordering::Acquire),
13350        1,
13351        "Should not restart LSP server on a related LSP settings change that is the same"
13352    );
13353
13354    update_test_project_settings(cx, |project_settings| {
13355        project_settings.lsp.insert(
13356            language_server_name.into(),
13357            LspSettings {
13358                binary: None,
13359                settings: None,
13360                initialization_options: None,
13361                enable_lsp_tasks: false,
13362            },
13363        );
13364    });
13365    cx.executor().run_until_parked();
13366    assert_eq!(
13367        server_restarts.load(atomic::Ordering::Acquire),
13368        2,
13369        "Should restart LSP server on another related LSP settings change"
13370    );
13371}
13372
13373#[gpui::test]
13374async fn test_completions_with_additional_edits(cx: &mut TestAppContext) {
13375    init_test(cx, |_| {});
13376
13377    let mut cx = EditorLspTestContext::new_rust(
13378        lsp::ServerCapabilities {
13379            completion_provider: Some(lsp::CompletionOptions {
13380                trigger_characters: Some(vec![".".to_string()]),
13381                resolve_provider: Some(true),
13382                ..Default::default()
13383            }),
13384            ..Default::default()
13385        },
13386        cx,
13387    )
13388    .await;
13389
13390    cx.set_state("fn main() { let a = 2ˇ; }");
13391    cx.simulate_keystroke(".");
13392    let completion_item = lsp::CompletionItem {
13393        label: "some".into(),
13394        kind: Some(lsp::CompletionItemKind::SNIPPET),
13395        detail: Some("Wrap the expression in an `Option::Some`".to_string()),
13396        documentation: Some(lsp::Documentation::MarkupContent(lsp::MarkupContent {
13397            kind: lsp::MarkupKind::Markdown,
13398            value: "```rust\nSome(2)\n```".to_string(),
13399        })),
13400        deprecated: Some(false),
13401        sort_text: Some("fffffff2".to_string()),
13402        filter_text: Some("some".to_string()),
13403        insert_text_format: Some(lsp::InsertTextFormat::SNIPPET),
13404        text_edit: Some(lsp::CompletionTextEdit::Edit(lsp::TextEdit {
13405            range: lsp::Range {
13406                start: lsp::Position {
13407                    line: 0,
13408                    character: 22,
13409                },
13410                end: lsp::Position {
13411                    line: 0,
13412                    character: 22,
13413                },
13414            },
13415            new_text: "Some(2)".to_string(),
13416        })),
13417        additional_text_edits: Some(vec![lsp::TextEdit {
13418            range: lsp::Range {
13419                start: lsp::Position {
13420                    line: 0,
13421                    character: 20,
13422                },
13423                end: lsp::Position {
13424                    line: 0,
13425                    character: 22,
13426                },
13427            },
13428            new_text: "".to_string(),
13429        }]),
13430        ..Default::default()
13431    };
13432
13433    let closure_completion_item = completion_item.clone();
13434    let mut request = cx.set_request_handler::<lsp::request::Completion, _, _>(move |_, _, _| {
13435        let task_completion_item = closure_completion_item.clone();
13436        async move {
13437            Ok(Some(lsp::CompletionResponse::Array(vec![
13438                task_completion_item,
13439            ])))
13440        }
13441    });
13442
13443    request.next().await;
13444
13445    cx.condition(|editor, _| editor.context_menu_visible())
13446        .await;
13447    let apply_additional_edits = cx.update_editor(|editor, window, cx| {
13448        editor
13449            .confirm_completion(&ConfirmCompletion::default(), window, cx)
13450            .unwrap()
13451    });
13452    cx.assert_editor_state("fn main() { let a = 2.Some(2)ˇ; }");
13453
13454    cx.set_request_handler::<lsp::request::ResolveCompletionItem, _, _>(move |_, _, _| {
13455        let task_completion_item = completion_item.clone();
13456        async move { Ok(task_completion_item) }
13457    })
13458    .next()
13459    .await
13460    .unwrap();
13461    apply_additional_edits.await.unwrap();
13462    cx.assert_editor_state("fn main() { let a = Some(2)ˇ; }");
13463}
13464
13465#[gpui::test]
13466async fn test_completions_resolve_updates_labels_if_filter_text_matches(cx: &mut TestAppContext) {
13467    init_test(cx, |_| {});
13468
13469    let mut cx = EditorLspTestContext::new_rust(
13470        lsp::ServerCapabilities {
13471            completion_provider: Some(lsp::CompletionOptions {
13472                trigger_characters: Some(vec![".".to_string()]),
13473                resolve_provider: Some(true),
13474                ..Default::default()
13475            }),
13476            ..Default::default()
13477        },
13478        cx,
13479    )
13480    .await;
13481
13482    cx.set_state("fn main() { let a = 2ˇ; }");
13483    cx.simulate_keystroke(".");
13484
13485    let item1 = lsp::CompletionItem {
13486        label: "method id()".to_string(),
13487        filter_text: Some("id".to_string()),
13488        detail: None,
13489        documentation: None,
13490        text_edit: Some(lsp::CompletionTextEdit::Edit(lsp::TextEdit {
13491            range: lsp::Range::new(lsp::Position::new(0, 22), lsp::Position::new(0, 22)),
13492            new_text: ".id".to_string(),
13493        })),
13494        ..lsp::CompletionItem::default()
13495    };
13496
13497    let item2 = lsp::CompletionItem {
13498        label: "other".to_string(),
13499        filter_text: Some("other".to_string()),
13500        detail: None,
13501        documentation: None,
13502        text_edit: Some(lsp::CompletionTextEdit::Edit(lsp::TextEdit {
13503            range: lsp::Range::new(lsp::Position::new(0, 22), lsp::Position::new(0, 22)),
13504            new_text: ".other".to_string(),
13505        })),
13506        ..lsp::CompletionItem::default()
13507    };
13508
13509    let item1 = item1.clone();
13510    cx.set_request_handler::<lsp::request::Completion, _, _>({
13511        let item1 = item1.clone();
13512        move |_, _, _| {
13513            let item1 = item1.clone();
13514            let item2 = item2.clone();
13515            async move { Ok(Some(lsp::CompletionResponse::Array(vec![item1, item2]))) }
13516        }
13517    })
13518    .next()
13519    .await;
13520
13521    cx.condition(|editor, _| editor.context_menu_visible())
13522        .await;
13523    cx.update_editor(|editor, _, _| {
13524        let context_menu = editor.context_menu.borrow_mut();
13525        let context_menu = context_menu
13526            .as_ref()
13527            .expect("Should have the context menu deployed");
13528        match context_menu {
13529            CodeContextMenu::Completions(completions_menu) => {
13530                let completions = completions_menu.completions.borrow_mut();
13531                assert_eq!(
13532                    completions
13533                        .iter()
13534                        .map(|completion| &completion.label.text)
13535                        .collect::<Vec<_>>(),
13536                    vec!["method id()", "other"]
13537                )
13538            }
13539            CodeContextMenu::CodeActions(_) => panic!("Should show the completions menu"),
13540        }
13541    });
13542
13543    cx.set_request_handler::<lsp::request::ResolveCompletionItem, _, _>({
13544        let item1 = item1.clone();
13545        move |_, item_to_resolve, _| {
13546            let item1 = item1.clone();
13547            async move {
13548                if item1 == item_to_resolve {
13549                    Ok(lsp::CompletionItem {
13550                        label: "method id()".to_string(),
13551                        filter_text: Some("id".to_string()),
13552                        detail: Some("Now resolved!".to_string()),
13553                        documentation: Some(lsp::Documentation::String("Docs".to_string())),
13554                        text_edit: Some(lsp::CompletionTextEdit::Edit(lsp::TextEdit {
13555                            range: lsp::Range::new(
13556                                lsp::Position::new(0, 22),
13557                                lsp::Position::new(0, 22),
13558                            ),
13559                            new_text: ".id".to_string(),
13560                        })),
13561                        ..lsp::CompletionItem::default()
13562                    })
13563                } else {
13564                    Ok(item_to_resolve)
13565                }
13566            }
13567        }
13568    })
13569    .next()
13570    .await
13571    .unwrap();
13572    cx.run_until_parked();
13573
13574    cx.update_editor(|editor, window, cx| {
13575        editor.context_menu_next(&Default::default(), window, cx);
13576    });
13577
13578    cx.update_editor(|editor, _, _| {
13579        let context_menu = editor.context_menu.borrow_mut();
13580        let context_menu = context_menu
13581            .as_ref()
13582            .expect("Should have the context menu deployed");
13583        match context_menu {
13584            CodeContextMenu::Completions(completions_menu) => {
13585                let completions = completions_menu.completions.borrow_mut();
13586                assert_eq!(
13587                    completions
13588                        .iter()
13589                        .map(|completion| &completion.label.text)
13590                        .collect::<Vec<_>>(),
13591                    vec!["method id() Now resolved!", "other"],
13592                    "Should update first completion label, but not second as the filter text did not match."
13593                );
13594            }
13595            CodeContextMenu::CodeActions(_) => panic!("Should show the completions menu"),
13596        }
13597    });
13598}
13599
13600#[gpui::test]
13601async fn test_completions_resolve_happens_once(cx: &mut TestAppContext) {
13602    init_test(cx, |_| {});
13603
13604    let mut cx = EditorLspTestContext::new_rust(
13605        lsp::ServerCapabilities {
13606            completion_provider: Some(lsp::CompletionOptions {
13607                trigger_characters: Some(vec![".".to_string()]),
13608                resolve_provider: Some(true),
13609                ..Default::default()
13610            }),
13611            ..Default::default()
13612        },
13613        cx,
13614    )
13615    .await;
13616
13617    cx.set_state("fn main() { let a = 2ˇ; }");
13618    cx.simulate_keystroke(".");
13619
13620    let unresolved_item_1 = lsp::CompletionItem {
13621        label: "id".to_string(),
13622        filter_text: Some("id".to_string()),
13623        detail: None,
13624        documentation: None,
13625        text_edit: Some(lsp::CompletionTextEdit::Edit(lsp::TextEdit {
13626            range: lsp::Range::new(lsp::Position::new(0, 22), lsp::Position::new(0, 22)),
13627            new_text: ".id".to_string(),
13628        })),
13629        ..lsp::CompletionItem::default()
13630    };
13631    let resolved_item_1 = lsp::CompletionItem {
13632        additional_text_edits: Some(vec![lsp::TextEdit {
13633            range: lsp::Range::new(lsp::Position::new(0, 20), lsp::Position::new(0, 22)),
13634            new_text: "!!".to_string(),
13635        }]),
13636        ..unresolved_item_1.clone()
13637    };
13638    let unresolved_item_2 = lsp::CompletionItem {
13639        label: "other".to_string(),
13640        filter_text: Some("other".to_string()),
13641        detail: None,
13642        documentation: None,
13643        text_edit: Some(lsp::CompletionTextEdit::Edit(lsp::TextEdit {
13644            range: lsp::Range::new(lsp::Position::new(0, 22), lsp::Position::new(0, 22)),
13645            new_text: ".other".to_string(),
13646        })),
13647        ..lsp::CompletionItem::default()
13648    };
13649    let resolved_item_2 = lsp::CompletionItem {
13650        additional_text_edits: Some(vec![lsp::TextEdit {
13651            range: lsp::Range::new(lsp::Position::new(0, 20), lsp::Position::new(0, 22)),
13652            new_text: "??".to_string(),
13653        }]),
13654        ..unresolved_item_2.clone()
13655    };
13656
13657    let resolve_requests_1 = Arc::new(AtomicUsize::new(0));
13658    let resolve_requests_2 = Arc::new(AtomicUsize::new(0));
13659    cx.lsp
13660        .server
13661        .on_request::<lsp::request::ResolveCompletionItem, _, _>({
13662            let unresolved_item_1 = unresolved_item_1.clone();
13663            let resolved_item_1 = resolved_item_1.clone();
13664            let unresolved_item_2 = unresolved_item_2.clone();
13665            let resolved_item_2 = resolved_item_2.clone();
13666            let resolve_requests_1 = resolve_requests_1.clone();
13667            let resolve_requests_2 = resolve_requests_2.clone();
13668            move |unresolved_request, _| {
13669                let unresolved_item_1 = unresolved_item_1.clone();
13670                let resolved_item_1 = resolved_item_1.clone();
13671                let unresolved_item_2 = unresolved_item_2.clone();
13672                let resolved_item_2 = resolved_item_2.clone();
13673                let resolve_requests_1 = resolve_requests_1.clone();
13674                let resolve_requests_2 = resolve_requests_2.clone();
13675                async move {
13676                    if unresolved_request == unresolved_item_1 {
13677                        resolve_requests_1.fetch_add(1, atomic::Ordering::Release);
13678                        Ok(resolved_item_1.clone())
13679                    } else if unresolved_request == unresolved_item_2 {
13680                        resolve_requests_2.fetch_add(1, atomic::Ordering::Release);
13681                        Ok(resolved_item_2.clone())
13682                    } else {
13683                        panic!("Unexpected completion item {unresolved_request:?}")
13684                    }
13685                }
13686            }
13687        })
13688        .detach();
13689
13690    cx.set_request_handler::<lsp::request::Completion, _, _>(move |_, _, _| {
13691        let unresolved_item_1 = unresolved_item_1.clone();
13692        let unresolved_item_2 = unresolved_item_2.clone();
13693        async move {
13694            Ok(Some(lsp::CompletionResponse::Array(vec![
13695                unresolved_item_1,
13696                unresolved_item_2,
13697            ])))
13698        }
13699    })
13700    .next()
13701    .await;
13702
13703    cx.condition(|editor, _| editor.context_menu_visible())
13704        .await;
13705    cx.update_editor(|editor, _, _| {
13706        let context_menu = editor.context_menu.borrow_mut();
13707        let context_menu = context_menu
13708            .as_ref()
13709            .expect("Should have the context menu deployed");
13710        match context_menu {
13711            CodeContextMenu::Completions(completions_menu) => {
13712                let completions = completions_menu.completions.borrow_mut();
13713                assert_eq!(
13714                    completions
13715                        .iter()
13716                        .map(|completion| &completion.label.text)
13717                        .collect::<Vec<_>>(),
13718                    vec!["id", "other"]
13719                )
13720            }
13721            CodeContextMenu::CodeActions(_) => panic!("Should show the completions menu"),
13722        }
13723    });
13724    cx.run_until_parked();
13725
13726    cx.update_editor(|editor, window, cx| {
13727        editor.context_menu_next(&ContextMenuNext, window, cx);
13728    });
13729    cx.run_until_parked();
13730    cx.update_editor(|editor, window, cx| {
13731        editor.context_menu_prev(&ContextMenuPrevious, window, cx);
13732    });
13733    cx.run_until_parked();
13734    cx.update_editor(|editor, window, cx| {
13735        editor.context_menu_next(&ContextMenuNext, window, cx);
13736    });
13737    cx.run_until_parked();
13738    cx.update_editor(|editor, window, cx| {
13739        editor
13740            .compose_completion(&ComposeCompletion::default(), window, cx)
13741            .expect("No task returned")
13742    })
13743    .await
13744    .expect("Completion failed");
13745    cx.run_until_parked();
13746
13747    cx.update_editor(|editor, _, cx| {
13748        assert_eq!(
13749            resolve_requests_1.load(atomic::Ordering::Acquire),
13750            1,
13751            "Should always resolve once despite multiple selections"
13752        );
13753        assert_eq!(
13754            resolve_requests_2.load(atomic::Ordering::Acquire),
13755            1,
13756            "Should always resolve once after multiple selections and applying the completion"
13757        );
13758        assert_eq!(
13759            editor.text(cx),
13760            "fn main() { let a = ??.other; }",
13761            "Should use resolved data when applying the completion"
13762        );
13763    });
13764}
13765
13766#[gpui::test]
13767async fn test_completions_default_resolve_data_handling(cx: &mut TestAppContext) {
13768    init_test(cx, |_| {});
13769
13770    let item_0 = lsp::CompletionItem {
13771        label: "abs".into(),
13772        insert_text: Some("abs".into()),
13773        data: Some(json!({ "very": "special"})),
13774        insert_text_mode: Some(lsp::InsertTextMode::ADJUST_INDENTATION),
13775        text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13776            lsp::InsertReplaceEdit {
13777                new_text: "abs".to_string(),
13778                insert: lsp::Range::default(),
13779                replace: lsp::Range::default(),
13780            },
13781        )),
13782        ..lsp::CompletionItem::default()
13783    };
13784    let items = iter::once(item_0.clone())
13785        .chain((11..51).map(|i| lsp::CompletionItem {
13786            label: format!("item_{}", i),
13787            insert_text: Some(format!("item_{}", i)),
13788            insert_text_format: Some(lsp::InsertTextFormat::PLAIN_TEXT),
13789            ..lsp::CompletionItem::default()
13790        }))
13791        .collect::<Vec<_>>();
13792
13793    let default_commit_characters = vec!["?".to_string()];
13794    let default_data = json!({ "default": "data"});
13795    let default_insert_text_format = lsp::InsertTextFormat::SNIPPET;
13796    let default_insert_text_mode = lsp::InsertTextMode::AS_IS;
13797    let default_edit_range = lsp::Range {
13798        start: lsp::Position {
13799            line: 0,
13800            character: 5,
13801        },
13802        end: lsp::Position {
13803            line: 0,
13804            character: 5,
13805        },
13806    };
13807
13808    let mut cx = EditorLspTestContext::new_rust(
13809        lsp::ServerCapabilities {
13810            completion_provider: Some(lsp::CompletionOptions {
13811                trigger_characters: Some(vec![".".to_string()]),
13812                resolve_provider: Some(true),
13813                ..Default::default()
13814            }),
13815            ..Default::default()
13816        },
13817        cx,
13818    )
13819    .await;
13820
13821    cx.set_state("fn main() { let a = 2ˇ; }");
13822    cx.simulate_keystroke(".");
13823
13824    let completion_data = default_data.clone();
13825    let completion_characters = default_commit_characters.clone();
13826    let completion_items = items.clone();
13827    cx.set_request_handler::<lsp::request::Completion, _, _>(move |_, _, _| {
13828        let default_data = completion_data.clone();
13829        let default_commit_characters = completion_characters.clone();
13830        let items = completion_items.clone();
13831        async move {
13832            Ok(Some(lsp::CompletionResponse::List(lsp::CompletionList {
13833                items,
13834                item_defaults: Some(lsp::CompletionListItemDefaults {
13835                    data: Some(default_data.clone()),
13836                    commit_characters: Some(default_commit_characters.clone()),
13837                    edit_range: Some(lsp::CompletionListItemDefaultsEditRange::Range(
13838                        default_edit_range,
13839                    )),
13840                    insert_text_format: Some(default_insert_text_format),
13841                    insert_text_mode: Some(default_insert_text_mode),
13842                }),
13843                ..lsp::CompletionList::default()
13844            })))
13845        }
13846    })
13847    .next()
13848    .await;
13849
13850    let resolved_items = Arc::new(Mutex::new(Vec::new()));
13851    cx.lsp
13852        .server
13853        .on_request::<lsp::request::ResolveCompletionItem, _, _>({
13854            let closure_resolved_items = resolved_items.clone();
13855            move |item_to_resolve, _| {
13856                let closure_resolved_items = closure_resolved_items.clone();
13857                async move {
13858                    closure_resolved_items.lock().push(item_to_resolve.clone());
13859                    Ok(item_to_resolve)
13860                }
13861            }
13862        })
13863        .detach();
13864
13865    cx.condition(|editor, _| editor.context_menu_visible())
13866        .await;
13867    cx.run_until_parked();
13868    cx.update_editor(|editor, _, _| {
13869        let menu = editor.context_menu.borrow_mut();
13870        match menu.as_ref().expect("should have the completions menu") {
13871            CodeContextMenu::Completions(completions_menu) => {
13872                assert_eq!(
13873                    completions_menu
13874                        .entries
13875                        .borrow()
13876                        .iter()
13877                        .map(|mat| mat.string.clone())
13878                        .collect::<Vec<String>>(),
13879                    items
13880                        .iter()
13881                        .map(|completion| completion.label.clone())
13882                        .collect::<Vec<String>>()
13883                );
13884            }
13885            CodeContextMenu::CodeActions(_) => panic!("Expected to have the completions menu"),
13886        }
13887    });
13888    // Approximate initial displayed interval is 0..12. With extra item padding of 4 this is 0..16
13889    // with 4 from the end.
13890    assert_eq!(
13891        *resolved_items.lock(),
13892        [&items[0..16], &items[items.len() - 4..items.len()]]
13893            .concat()
13894            .iter()
13895            .cloned()
13896            .map(|mut item| {
13897                if item.data.is_none() {
13898                    item.data = Some(default_data.clone());
13899                }
13900                item
13901            })
13902            .collect::<Vec<lsp::CompletionItem>>(),
13903        "Items sent for resolve should be unchanged modulo resolve `data` filled with default if missing"
13904    );
13905    resolved_items.lock().clear();
13906
13907    cx.update_editor(|editor, window, cx| {
13908        editor.context_menu_prev(&ContextMenuPrevious, window, cx);
13909    });
13910    cx.run_until_parked();
13911    // Completions that have already been resolved are skipped.
13912    assert_eq!(
13913        *resolved_items.lock(),
13914        items[items.len() - 16..items.len() - 4]
13915            .iter()
13916            .cloned()
13917            .map(|mut item| {
13918                if item.data.is_none() {
13919                    item.data = Some(default_data.clone());
13920                }
13921                item
13922            })
13923            .collect::<Vec<lsp::CompletionItem>>()
13924    );
13925    resolved_items.lock().clear();
13926}
13927
13928#[gpui::test]
13929async fn test_completions_in_languages_with_extra_word_characters(cx: &mut TestAppContext) {
13930    init_test(cx, |_| {});
13931
13932    let mut cx = EditorLspTestContext::new(
13933        Language::new(
13934            LanguageConfig {
13935                matcher: LanguageMatcher {
13936                    path_suffixes: vec!["jsx".into()],
13937                    ..Default::default()
13938                },
13939                overrides: [(
13940                    "element".into(),
13941                    LanguageConfigOverride {
13942                        completion_query_characters: Override::Set(['-'].into_iter().collect()),
13943                        ..Default::default()
13944                    },
13945                )]
13946                .into_iter()
13947                .collect(),
13948                ..Default::default()
13949            },
13950            Some(tree_sitter_typescript::LANGUAGE_TSX.into()),
13951        )
13952        .with_override_query("(jsx_self_closing_element) @element")
13953        .unwrap(),
13954        lsp::ServerCapabilities {
13955            completion_provider: Some(lsp::CompletionOptions {
13956                trigger_characters: Some(vec![":".to_string()]),
13957                ..Default::default()
13958            }),
13959            ..Default::default()
13960        },
13961        cx,
13962    )
13963    .await;
13964
13965    cx.lsp
13966        .set_request_handler::<lsp::request::Completion, _, _>(move |_, _| async move {
13967            Ok(Some(lsp::CompletionResponse::Array(vec![
13968                lsp::CompletionItem {
13969                    label: "bg-blue".into(),
13970                    ..Default::default()
13971                },
13972                lsp::CompletionItem {
13973                    label: "bg-red".into(),
13974                    ..Default::default()
13975                },
13976                lsp::CompletionItem {
13977                    label: "bg-yellow".into(),
13978                    ..Default::default()
13979                },
13980            ])))
13981        });
13982
13983    cx.set_state(r#"<p class="bgˇ" />"#);
13984
13985    // Trigger completion when typing a dash, because the dash is an extra
13986    // word character in the 'element' scope, which contains the cursor.
13987    cx.simulate_keystroke("-");
13988    cx.executor().run_until_parked();
13989    cx.update_editor(|editor, _, _| {
13990        if let Some(CodeContextMenu::Completions(menu)) = editor.context_menu.borrow_mut().as_ref()
13991        {
13992            assert_eq!(
13993                completion_menu_entries(&menu),
13994                &["bg-blue", "bg-red", "bg-yellow"]
13995            );
13996        } else {
13997            panic!("expected completion menu to be open");
13998        }
13999    });
14000
14001    cx.simulate_keystroke("l");
14002    cx.executor().run_until_parked();
14003    cx.update_editor(|editor, _, _| {
14004        if let Some(CodeContextMenu::Completions(menu)) = editor.context_menu.borrow_mut().as_ref()
14005        {
14006            assert_eq!(completion_menu_entries(&menu), &["bg-blue", "bg-yellow"]);
14007        } else {
14008            panic!("expected completion menu to be open");
14009        }
14010    });
14011
14012    // When filtering completions, consider the character after the '-' to
14013    // be the start of a subword.
14014    cx.set_state(r#"<p class="yelˇ" />"#);
14015    cx.simulate_keystroke("l");
14016    cx.executor().run_until_parked();
14017    cx.update_editor(|editor, _, _| {
14018        if let Some(CodeContextMenu::Completions(menu)) = editor.context_menu.borrow_mut().as_ref()
14019        {
14020            assert_eq!(completion_menu_entries(&menu), &["bg-yellow"]);
14021        } else {
14022            panic!("expected completion menu to be open");
14023        }
14024    });
14025}
14026
14027fn completion_menu_entries(menu: &CompletionsMenu) -> Vec<String> {
14028    let entries = menu.entries.borrow();
14029    entries.iter().map(|mat| mat.string.clone()).collect()
14030}
14031
14032#[gpui::test]
14033async fn test_document_format_with_prettier(cx: &mut TestAppContext) {
14034    init_test(cx, |settings| {
14035        settings.defaults.formatter = Some(language_settings::SelectedFormatter::List(
14036            FormatterList(vec![Formatter::Prettier].into()),
14037        ))
14038    });
14039
14040    let fs = FakeFs::new(cx.executor());
14041    fs.insert_file(path!("/file.ts"), Default::default()).await;
14042
14043    let project = Project::test(fs, [path!("/file.ts").as_ref()], cx).await;
14044    let language_registry = project.read_with(cx, |project, _| project.languages().clone());
14045
14046    language_registry.add(Arc::new(Language::new(
14047        LanguageConfig {
14048            name: "TypeScript".into(),
14049            matcher: LanguageMatcher {
14050                path_suffixes: vec!["ts".to_string()],
14051                ..Default::default()
14052            },
14053            ..Default::default()
14054        },
14055        Some(tree_sitter_typescript::LANGUAGE_TYPESCRIPT.into()),
14056    )));
14057    update_test_language_settings(cx, |settings| {
14058        settings.defaults.prettier = Some(PrettierSettings {
14059            allowed: true,
14060            ..PrettierSettings::default()
14061        });
14062    });
14063
14064    let test_plugin = "test_plugin";
14065    let _ = language_registry.register_fake_lsp(
14066        "TypeScript",
14067        FakeLspAdapter {
14068            prettier_plugins: vec![test_plugin],
14069            ..Default::default()
14070        },
14071    );
14072
14073    let prettier_format_suffix = project::TEST_PRETTIER_FORMAT_SUFFIX;
14074    let buffer = project
14075        .update(cx, |project, cx| {
14076            project.open_local_buffer(path!("/file.ts"), cx)
14077        })
14078        .await
14079        .unwrap();
14080
14081    let buffer_text = "one\ntwo\nthree\n";
14082    let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
14083    let (editor, cx) = cx.add_window_view(|window, cx| build_editor(buffer, window, cx));
14084    editor.update_in(cx, |editor, window, cx| {
14085        editor.set_text(buffer_text, window, cx)
14086    });
14087
14088    editor
14089        .update_in(cx, |editor, window, cx| {
14090            editor.perform_format(
14091                project.clone(),
14092                FormatTrigger::Manual,
14093                FormatTarget::Buffers,
14094                window,
14095                cx,
14096            )
14097        })
14098        .unwrap()
14099        .await;
14100    assert_eq!(
14101        editor.update(cx, |editor, cx| editor.text(cx)),
14102        buffer_text.to_string() + prettier_format_suffix,
14103        "Test prettier formatting was not applied to the original buffer text",
14104    );
14105
14106    update_test_language_settings(cx, |settings| {
14107        settings.defaults.formatter = Some(language_settings::SelectedFormatter::Auto)
14108    });
14109    let format = editor.update_in(cx, |editor, window, cx| {
14110        editor.perform_format(
14111            project.clone(),
14112            FormatTrigger::Manual,
14113            FormatTarget::Buffers,
14114            window,
14115            cx,
14116        )
14117    });
14118    format.await.unwrap();
14119    assert_eq!(
14120        editor.update(cx, |editor, cx| editor.text(cx)),
14121        buffer_text.to_string() + prettier_format_suffix + "\n" + prettier_format_suffix,
14122        "Autoformatting (via test prettier) was not applied to the original buffer text",
14123    );
14124}
14125
14126#[gpui::test]
14127async fn test_addition_reverts(cx: &mut TestAppContext) {
14128    init_test(cx, |_| {});
14129    let mut cx = EditorLspTestContext::new_rust(lsp::ServerCapabilities::default(), cx).await;
14130    let base_text = indoc! {r#"
14131        struct Row;
14132        struct Row1;
14133        struct Row2;
14134
14135        struct Row4;
14136        struct Row5;
14137        struct Row6;
14138
14139        struct Row8;
14140        struct Row9;
14141        struct Row10;"#};
14142
14143    // When addition hunks are not adjacent to carets, no hunk revert is performed
14144    assert_hunk_revert(
14145        indoc! {r#"struct Row;
14146                   struct Row1;
14147                   struct Row1.1;
14148                   struct Row1.2;
14149                   struct Row2;ˇ
14150
14151                   struct Row4;
14152                   struct Row5;
14153                   struct Row6;
14154
14155                   struct Row8;
14156                   ˇstruct Row9;
14157                   struct Row9.1;
14158                   struct Row9.2;
14159                   struct Row9.3;
14160                   struct Row10;"#},
14161        vec![DiffHunkStatusKind::Added, DiffHunkStatusKind::Added],
14162        indoc! {r#"struct Row;
14163                   struct Row1;
14164                   struct Row1.1;
14165                   struct Row1.2;
14166                   struct Row2;ˇ
14167
14168                   struct Row4;
14169                   struct Row5;
14170                   struct Row6;
14171
14172                   struct Row8;
14173                   ˇstruct Row9;
14174                   struct Row9.1;
14175                   struct Row9.2;
14176                   struct Row9.3;
14177                   struct Row10;"#},
14178        base_text,
14179        &mut cx,
14180    );
14181    // Same for selections
14182    assert_hunk_revert(
14183        indoc! {r#"struct Row;
14184                   struct Row1;
14185                   struct Row2;
14186                   struct Row2.1;
14187                   struct Row2.2;
14188                   «ˇ
14189                   struct Row4;
14190                   struct» Row5;
14191                   «struct Row6;
14192                   ˇ»
14193                   struct Row9.1;
14194                   struct Row9.2;
14195                   struct Row9.3;
14196                   struct Row8;
14197                   struct Row9;
14198                   struct Row10;"#},
14199        vec![DiffHunkStatusKind::Added, DiffHunkStatusKind::Added],
14200        indoc! {r#"struct Row;
14201                   struct Row1;
14202                   struct Row2;
14203                   struct Row2.1;
14204                   struct Row2.2;
14205                   «ˇ
14206                   struct Row4;
14207                   struct» Row5;
14208                   «struct Row6;
14209                   ˇ»
14210                   struct Row9.1;
14211                   struct Row9.2;
14212                   struct Row9.3;
14213                   struct Row8;
14214                   struct Row9;
14215                   struct Row10;"#},
14216        base_text,
14217        &mut cx,
14218    );
14219
14220    // When carets and selections intersect the addition hunks, those are reverted.
14221    // Adjacent carets got merged.
14222    assert_hunk_revert(
14223        indoc! {r#"struct Row;
14224                   ˇ// something on the top
14225                   struct Row1;
14226                   struct Row2;
14227                   struct Roˇw3.1;
14228                   struct Row2.2;
14229                   struct Row2.3;ˇ
14230
14231                   struct Row4;
14232                   struct ˇRow5.1;
14233                   struct Row5.2;
14234                   struct «Rowˇ»5.3;
14235                   struct Row5;
14236                   struct Row6;
14237                   ˇ
14238                   struct Row9.1;
14239                   struct «Rowˇ»9.2;
14240                   struct «ˇRow»9.3;
14241                   struct Row8;
14242                   struct Row9;
14243                   «ˇ// something on bottom»
14244                   struct Row10;"#},
14245        vec![
14246            DiffHunkStatusKind::Added,
14247            DiffHunkStatusKind::Added,
14248            DiffHunkStatusKind::Added,
14249            DiffHunkStatusKind::Added,
14250            DiffHunkStatusKind::Added,
14251        ],
14252        indoc! {r#"struct Row;
14253                   ˇstruct Row1;
14254                   struct Row2;
14255                   ˇ
14256                   struct Row4;
14257                   ˇstruct Row5;
14258                   struct Row6;
14259                   ˇ
14260                   ˇstruct Row8;
14261                   struct Row9;
14262                   ˇstruct Row10;"#},
14263        base_text,
14264        &mut cx,
14265    );
14266}
14267
14268#[gpui::test]
14269async fn test_modification_reverts(cx: &mut TestAppContext) {
14270    init_test(cx, |_| {});
14271    let mut cx = EditorLspTestContext::new_rust(lsp::ServerCapabilities::default(), cx).await;
14272    let base_text = indoc! {r#"
14273        struct Row;
14274        struct Row1;
14275        struct Row2;
14276
14277        struct Row4;
14278        struct Row5;
14279        struct Row6;
14280
14281        struct Row8;
14282        struct Row9;
14283        struct Row10;"#};
14284
14285    // Modification hunks behave the same as the addition ones.
14286    assert_hunk_revert(
14287        indoc! {r#"struct Row;
14288                   struct Row1;
14289                   struct Row33;
14290                   ˇ
14291                   struct Row4;
14292                   struct Row5;
14293                   struct Row6;
14294                   ˇ
14295                   struct Row99;
14296                   struct Row9;
14297                   struct Row10;"#},
14298        vec![DiffHunkStatusKind::Modified, DiffHunkStatusKind::Modified],
14299        indoc! {r#"struct Row;
14300                   struct Row1;
14301                   struct Row33;
14302                   ˇ
14303                   struct Row4;
14304                   struct Row5;
14305                   struct Row6;
14306                   ˇ
14307                   struct Row99;
14308                   struct Row9;
14309                   struct Row10;"#},
14310        base_text,
14311        &mut cx,
14312    );
14313    assert_hunk_revert(
14314        indoc! {r#"struct Row;
14315                   struct Row1;
14316                   struct Row33;
14317                   «ˇ
14318                   struct Row4;
14319                   struct» Row5;
14320                   «struct Row6;
14321                   ˇ»
14322                   struct Row99;
14323                   struct Row9;
14324                   struct Row10;"#},
14325        vec![DiffHunkStatusKind::Modified, DiffHunkStatusKind::Modified],
14326        indoc! {r#"struct Row;
14327                   struct Row1;
14328                   struct Row33;
14329                   «ˇ
14330                   struct Row4;
14331                   struct» Row5;
14332                   «struct Row6;
14333                   ˇ»
14334                   struct Row99;
14335                   struct Row9;
14336                   struct Row10;"#},
14337        base_text,
14338        &mut cx,
14339    );
14340
14341    assert_hunk_revert(
14342        indoc! {r#"ˇstruct Row1.1;
14343                   struct Row1;
14344                   «ˇstr»uct Row22;
14345
14346                   struct ˇRow44;
14347                   struct Row5;
14348                   struct «Rˇ»ow66;ˇ
14349
14350                   «struˇ»ct Row88;
14351                   struct Row9;
14352                   struct Row1011;ˇ"#},
14353        vec![
14354            DiffHunkStatusKind::Modified,
14355            DiffHunkStatusKind::Modified,
14356            DiffHunkStatusKind::Modified,
14357            DiffHunkStatusKind::Modified,
14358            DiffHunkStatusKind::Modified,
14359            DiffHunkStatusKind::Modified,
14360        ],
14361        indoc! {r#"struct Row;
14362                   ˇstruct Row1;
14363                   struct Row2;
14364                   ˇ
14365                   struct Row4;
14366                   ˇstruct Row5;
14367                   struct Row6;
14368                   ˇ
14369                   struct Row8;
14370                   ˇstruct Row9;
14371                   struct Row10;ˇ"#},
14372        base_text,
14373        &mut cx,
14374    );
14375}
14376
14377#[gpui::test]
14378async fn test_deleting_over_diff_hunk(cx: &mut TestAppContext) {
14379    init_test(cx, |_| {});
14380    let mut cx = EditorLspTestContext::new_rust(lsp::ServerCapabilities::default(), cx).await;
14381    let base_text = indoc! {r#"
14382        one
14383
14384        two
14385        three
14386        "#};
14387
14388    cx.set_head_text(base_text);
14389    cx.set_state("\nˇ\n");
14390    cx.executor().run_until_parked();
14391    cx.update_editor(|editor, _window, cx| {
14392        editor.expand_selected_diff_hunks(cx);
14393    });
14394    cx.executor().run_until_parked();
14395    cx.update_editor(|editor, window, cx| {
14396        editor.backspace(&Default::default(), window, cx);
14397    });
14398    cx.run_until_parked();
14399    cx.assert_state_with_diff(
14400        indoc! {r#"
14401
14402        - two
14403        - threeˇ
14404        +
14405        "#}
14406        .to_string(),
14407    );
14408}
14409
14410#[gpui::test]
14411async fn test_deletion_reverts(cx: &mut TestAppContext) {
14412    init_test(cx, |_| {});
14413    let mut cx = EditorLspTestContext::new_rust(lsp::ServerCapabilities::default(), cx).await;
14414    let base_text = indoc! {r#"struct Row;
14415struct Row1;
14416struct Row2;
14417
14418struct Row4;
14419struct Row5;
14420struct Row6;
14421
14422struct Row8;
14423struct Row9;
14424struct Row10;"#};
14425
14426    // Deletion hunks trigger with carets on adjacent rows, so carets and selections have to stay farther to avoid the revert
14427    assert_hunk_revert(
14428        indoc! {r#"struct Row;
14429                   struct Row2;
14430
14431                   ˇstruct Row4;
14432                   struct Row5;
14433                   struct Row6;
14434                   ˇ
14435                   struct Row8;
14436                   struct Row10;"#},
14437        vec![DiffHunkStatusKind::Deleted, DiffHunkStatusKind::Deleted],
14438        indoc! {r#"struct Row;
14439                   struct Row2;
14440
14441                   ˇstruct Row4;
14442                   struct Row5;
14443                   struct Row6;
14444                   ˇ
14445                   struct Row8;
14446                   struct Row10;"#},
14447        base_text,
14448        &mut cx,
14449    );
14450    assert_hunk_revert(
14451        indoc! {r#"struct Row;
14452                   struct Row2;
14453
14454                   «ˇstruct Row4;
14455                   struct» Row5;
14456                   «struct Row6;
14457                   ˇ»
14458                   struct Row8;
14459                   struct Row10;"#},
14460        vec![DiffHunkStatusKind::Deleted, DiffHunkStatusKind::Deleted],
14461        indoc! {r#"struct Row;
14462                   struct Row2;
14463
14464                   «ˇstruct Row4;
14465                   struct» Row5;
14466                   «struct Row6;
14467                   ˇ»
14468                   struct Row8;
14469                   struct Row10;"#},
14470        base_text,
14471        &mut cx,
14472    );
14473
14474    // Deletion hunks are ephemeral, so it's impossible to place the caret into them — Zed triggers reverts for lines, adjacent to carets and selections.
14475    assert_hunk_revert(
14476        indoc! {r#"struct Row;
14477                   ˇstruct Row2;
14478
14479                   struct Row4;
14480                   struct Row5;
14481                   struct Row6;
14482
14483                   struct Row8;ˇ
14484                   struct Row10;"#},
14485        vec![DiffHunkStatusKind::Deleted, DiffHunkStatusKind::Deleted],
14486        indoc! {r#"struct Row;
14487                   struct Row1;
14488                   ˇstruct Row2;
14489
14490                   struct Row4;
14491                   struct Row5;
14492                   struct Row6;
14493
14494                   struct Row8;ˇ
14495                   struct Row9;
14496                   struct Row10;"#},
14497        base_text,
14498        &mut cx,
14499    );
14500    assert_hunk_revert(
14501        indoc! {r#"struct Row;
14502                   struct Row2«ˇ;
14503                   struct Row4;
14504                   struct» Row5;
14505                   «struct Row6;
14506
14507                   struct Row8;ˇ»
14508                   struct Row10;"#},
14509        vec![
14510            DiffHunkStatusKind::Deleted,
14511            DiffHunkStatusKind::Deleted,
14512            DiffHunkStatusKind::Deleted,
14513        ],
14514        indoc! {r#"struct Row;
14515                   struct Row1;
14516                   struct Row2«ˇ;
14517
14518                   struct Row4;
14519                   struct» Row5;
14520                   «struct Row6;
14521
14522                   struct Row8;ˇ»
14523                   struct Row9;
14524                   struct Row10;"#},
14525        base_text,
14526        &mut cx,
14527    );
14528}
14529
14530#[gpui::test]
14531async fn test_multibuffer_reverts(cx: &mut TestAppContext) {
14532    init_test(cx, |_| {});
14533
14534    let base_text_1 = "aaaa\nbbbb\ncccc\ndddd\neeee\nffff\ngggg\nhhhh\niiii\njjjj";
14535    let base_text_2 = "llll\nmmmm\nnnnn\noooo\npppp\nqqqq\nrrrr\nssss\ntttt\nuuuu";
14536    let base_text_3 =
14537        "vvvv\nwwww\nxxxx\nyyyy\nzzzz\n{{{{\n||||\n}}}}\n~~~~\n\u{7f}\u{7f}\u{7f}\u{7f}";
14538
14539    let text_1 = edit_first_char_of_every_line(base_text_1);
14540    let text_2 = edit_first_char_of_every_line(base_text_2);
14541    let text_3 = edit_first_char_of_every_line(base_text_3);
14542
14543    let buffer_1 = cx.new(|cx| Buffer::local(text_1.clone(), cx));
14544    let buffer_2 = cx.new(|cx| Buffer::local(text_2.clone(), cx));
14545    let buffer_3 = cx.new(|cx| Buffer::local(text_3.clone(), cx));
14546
14547    let multibuffer = cx.new(|cx| {
14548        let mut multibuffer = MultiBuffer::new(ReadWrite);
14549        multibuffer.push_excerpts(
14550            buffer_1.clone(),
14551            [
14552                ExcerptRange::new(Point::new(0, 0)..Point::new(3, 0)),
14553                ExcerptRange::new(Point::new(5, 0)..Point::new(7, 0)),
14554                ExcerptRange::new(Point::new(9, 0)..Point::new(10, 4)),
14555            ],
14556            cx,
14557        );
14558        multibuffer.push_excerpts(
14559            buffer_2.clone(),
14560            [
14561                ExcerptRange::new(Point::new(0, 0)..Point::new(3, 0)),
14562                ExcerptRange::new(Point::new(5, 0)..Point::new(7, 0)),
14563                ExcerptRange::new(Point::new(9, 0)..Point::new(10, 4)),
14564            ],
14565            cx,
14566        );
14567        multibuffer.push_excerpts(
14568            buffer_3.clone(),
14569            [
14570                ExcerptRange::new(Point::new(0, 0)..Point::new(3, 0)),
14571                ExcerptRange::new(Point::new(5, 0)..Point::new(7, 0)),
14572                ExcerptRange::new(Point::new(9, 0)..Point::new(10, 4)),
14573            ],
14574            cx,
14575        );
14576        multibuffer
14577    });
14578
14579    let fs = FakeFs::new(cx.executor());
14580    let project = Project::test(fs, [path!("/").as_ref()], cx).await;
14581    let (editor, cx) = cx
14582        .add_window_view(|window, cx| build_editor_with_project(project, multibuffer, window, cx));
14583    editor.update_in(cx, |editor, _window, cx| {
14584        for (buffer, diff_base) in [
14585            (buffer_1.clone(), base_text_1),
14586            (buffer_2.clone(), base_text_2),
14587            (buffer_3.clone(), base_text_3),
14588        ] {
14589            let diff = cx.new(|cx| BufferDiff::new_with_base_text(&diff_base, &buffer, cx));
14590            editor
14591                .buffer
14592                .update(cx, |buffer, cx| buffer.add_diff(diff, cx));
14593        }
14594    });
14595    cx.executor().run_until_parked();
14596
14597    editor.update_in(cx, |editor, window, cx| {
14598        assert_eq!(editor.text(cx), "Xaaa\nXbbb\nXccc\n\nXfff\nXggg\n\nXjjj\nXlll\nXmmm\nXnnn\n\nXqqq\nXrrr\n\nXuuu\nXvvv\nXwww\nXxxx\n\nX{{{\nX|||\n\nX\u{7f}\u{7f}\u{7f}");
14599        editor.select_all(&SelectAll, window, cx);
14600        editor.git_restore(&Default::default(), window, cx);
14601    });
14602    cx.executor().run_until_parked();
14603
14604    // When all ranges are selected, all buffer hunks are reverted.
14605    editor.update(cx, |editor, cx| {
14606        assert_eq!(editor.text(cx), "aaaa\nbbbb\ncccc\ndddd\neeee\nffff\ngggg\nhhhh\niiii\njjjj\n\n\nllll\nmmmm\nnnnn\noooo\npppp\nqqqq\nrrrr\nssss\ntttt\nuuuu\n\n\nvvvv\nwwww\nxxxx\nyyyy\nzzzz\n{{{{\n||||\n}}}}\n~~~~\n\u{7f}\u{7f}\u{7f}\u{7f}\n\n");
14607    });
14608    buffer_1.update(cx, |buffer, _| {
14609        assert_eq!(buffer.text(), base_text_1);
14610    });
14611    buffer_2.update(cx, |buffer, _| {
14612        assert_eq!(buffer.text(), base_text_2);
14613    });
14614    buffer_3.update(cx, |buffer, _| {
14615        assert_eq!(buffer.text(), base_text_3);
14616    });
14617
14618    editor.update_in(cx, |editor, window, cx| {
14619        editor.undo(&Default::default(), window, cx);
14620    });
14621
14622    editor.update_in(cx, |editor, window, cx| {
14623        editor.change_selections(None, window, cx, |s| {
14624            s.select_ranges(Some(Point::new(0, 0)..Point::new(6, 0)));
14625        });
14626        editor.git_restore(&Default::default(), window, cx);
14627    });
14628
14629    // Now, when all ranges selected belong to buffer_1, the revert should succeed,
14630    // but not affect buffer_2 and its related excerpts.
14631    editor.update(cx, |editor, cx| {
14632        assert_eq!(
14633            editor.text(cx),
14634            "aaaa\nbbbb\ncccc\ndddd\neeee\nffff\ngggg\nhhhh\niiii\njjjj\n\n\nXlll\nXmmm\nXnnn\n\nXqqq\nXrrr\n\nXuuu\nXvvv\nXwww\nXxxx\n\nX{{{\nX|||\n\nX\u{7f}\u{7f}\u{7f}"
14635        );
14636    });
14637    buffer_1.update(cx, |buffer, _| {
14638        assert_eq!(buffer.text(), base_text_1);
14639    });
14640    buffer_2.update(cx, |buffer, _| {
14641        assert_eq!(
14642            buffer.text(),
14643            "Xlll\nXmmm\nXnnn\nXooo\nXppp\nXqqq\nXrrr\nXsss\nXttt\nXuuu"
14644        );
14645    });
14646    buffer_3.update(cx, |buffer, _| {
14647        assert_eq!(
14648            buffer.text(),
14649            "Xvvv\nXwww\nXxxx\nXyyy\nXzzz\nX{{{\nX|||\nX}}}\nX~~~\nX\u{7f}\u{7f}\u{7f}"
14650        );
14651    });
14652
14653    fn edit_first_char_of_every_line(text: &str) -> String {
14654        text.split('\n')
14655            .map(|line| format!("X{}", &line[1..]))
14656            .collect::<Vec<_>>()
14657            .join("\n")
14658    }
14659}
14660
14661#[gpui::test]
14662async fn test_mutlibuffer_in_navigation_history(cx: &mut TestAppContext) {
14663    init_test(cx, |_| {});
14664
14665    let cols = 4;
14666    let rows = 10;
14667    let sample_text_1 = sample_text(rows, cols, 'a');
14668    assert_eq!(
14669        sample_text_1,
14670        "aaaa\nbbbb\ncccc\ndddd\neeee\nffff\ngggg\nhhhh\niiii\njjjj"
14671    );
14672    let sample_text_2 = sample_text(rows, cols, 'l');
14673    assert_eq!(
14674        sample_text_2,
14675        "llll\nmmmm\nnnnn\noooo\npppp\nqqqq\nrrrr\nssss\ntttt\nuuuu"
14676    );
14677    let sample_text_3 = sample_text(rows, cols, 'v');
14678    assert_eq!(
14679        sample_text_3,
14680        "vvvv\nwwww\nxxxx\nyyyy\nzzzz\n{{{{\n||||\n}}}}\n~~~~\n\u{7f}\u{7f}\u{7f}\u{7f}"
14681    );
14682
14683    let buffer_1 = cx.new(|cx| Buffer::local(sample_text_1.clone(), cx));
14684    let buffer_2 = cx.new(|cx| Buffer::local(sample_text_2.clone(), cx));
14685    let buffer_3 = cx.new(|cx| Buffer::local(sample_text_3.clone(), cx));
14686
14687    let multi_buffer = cx.new(|cx| {
14688        let mut multibuffer = MultiBuffer::new(ReadWrite);
14689        multibuffer.push_excerpts(
14690            buffer_1.clone(),
14691            [
14692                ExcerptRange::new(Point::new(0, 0)..Point::new(3, 0)),
14693                ExcerptRange::new(Point::new(5, 0)..Point::new(7, 0)),
14694                ExcerptRange::new(Point::new(9, 0)..Point::new(10, 4)),
14695            ],
14696            cx,
14697        );
14698        multibuffer.push_excerpts(
14699            buffer_2.clone(),
14700            [
14701                ExcerptRange::new(Point::new(0, 0)..Point::new(3, 0)),
14702                ExcerptRange::new(Point::new(5, 0)..Point::new(7, 0)),
14703                ExcerptRange::new(Point::new(9, 0)..Point::new(10, 4)),
14704            ],
14705            cx,
14706        );
14707        multibuffer.push_excerpts(
14708            buffer_3.clone(),
14709            [
14710                ExcerptRange::new(Point::new(0, 0)..Point::new(3, 0)),
14711                ExcerptRange::new(Point::new(5, 0)..Point::new(7, 0)),
14712                ExcerptRange::new(Point::new(9, 0)..Point::new(10, 4)),
14713            ],
14714            cx,
14715        );
14716        multibuffer
14717    });
14718
14719    let fs = FakeFs::new(cx.executor());
14720    fs.insert_tree(
14721        "/a",
14722        json!({
14723            "main.rs": sample_text_1,
14724            "other.rs": sample_text_2,
14725            "lib.rs": sample_text_3,
14726        }),
14727    )
14728    .await;
14729    let project = Project::test(fs, ["/a".as_ref()], cx).await;
14730    let workspace = cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
14731    let cx = &mut VisualTestContext::from_window(*workspace.deref(), cx);
14732    let multi_buffer_editor = cx.new_window_entity(|window, cx| {
14733        Editor::new(
14734            EditorMode::full(),
14735            multi_buffer,
14736            Some(project.clone()),
14737            window,
14738            cx,
14739        )
14740    });
14741    let multibuffer_item_id = workspace
14742        .update(cx, |workspace, window, cx| {
14743            assert!(
14744                workspace.active_item(cx).is_none(),
14745                "active item should be None before the first item is added"
14746            );
14747            workspace.add_item_to_active_pane(
14748                Box::new(multi_buffer_editor.clone()),
14749                None,
14750                true,
14751                window,
14752                cx,
14753            );
14754            let active_item = workspace
14755                .active_item(cx)
14756                .expect("should have an active item after adding the multi buffer");
14757            assert!(
14758                !active_item.is_singleton(cx),
14759                "A multi buffer was expected to active after adding"
14760            );
14761            active_item.item_id()
14762        })
14763        .unwrap();
14764    cx.executor().run_until_parked();
14765
14766    multi_buffer_editor.update_in(cx, |editor, window, cx| {
14767        editor.change_selections(Some(Autoscroll::Next), window, cx, |s| {
14768            s.select_ranges(Some(1..2))
14769        });
14770        editor.open_excerpts(&OpenExcerpts, window, cx);
14771    });
14772    cx.executor().run_until_parked();
14773    let first_item_id = workspace
14774        .update(cx, |workspace, window, cx| {
14775            let active_item = workspace
14776                .active_item(cx)
14777                .expect("should have an active item after navigating into the 1st buffer");
14778            let first_item_id = active_item.item_id();
14779            assert_ne!(
14780                first_item_id, multibuffer_item_id,
14781                "Should navigate into the 1st buffer and activate it"
14782            );
14783            assert!(
14784                active_item.is_singleton(cx),
14785                "New active item should be a singleton buffer"
14786            );
14787            assert_eq!(
14788                active_item
14789                    .act_as::<Editor>(cx)
14790                    .expect("should have navigated into an editor for the 1st buffer")
14791                    .read(cx)
14792                    .text(cx),
14793                sample_text_1
14794            );
14795
14796            workspace
14797                .go_back(workspace.active_pane().downgrade(), window, cx)
14798                .detach_and_log_err(cx);
14799
14800            first_item_id
14801        })
14802        .unwrap();
14803    cx.executor().run_until_parked();
14804    workspace
14805        .update(cx, |workspace, _, cx| {
14806            let active_item = workspace
14807                .active_item(cx)
14808                .expect("should have an active item after navigating back");
14809            assert_eq!(
14810                active_item.item_id(),
14811                multibuffer_item_id,
14812                "Should navigate back to the multi buffer"
14813            );
14814            assert!(!active_item.is_singleton(cx));
14815        })
14816        .unwrap();
14817
14818    multi_buffer_editor.update_in(cx, |editor, window, cx| {
14819        editor.change_selections(Some(Autoscroll::Next), window, cx, |s| {
14820            s.select_ranges(Some(39..40))
14821        });
14822        editor.open_excerpts(&OpenExcerpts, window, cx);
14823    });
14824    cx.executor().run_until_parked();
14825    let second_item_id = workspace
14826        .update(cx, |workspace, window, cx| {
14827            let active_item = workspace
14828                .active_item(cx)
14829                .expect("should have an active item after navigating into the 2nd buffer");
14830            let second_item_id = active_item.item_id();
14831            assert_ne!(
14832                second_item_id, multibuffer_item_id,
14833                "Should navigate away from the multibuffer"
14834            );
14835            assert_ne!(
14836                second_item_id, first_item_id,
14837                "Should navigate into the 2nd buffer and activate it"
14838            );
14839            assert!(
14840                active_item.is_singleton(cx),
14841                "New active item should be a singleton buffer"
14842            );
14843            assert_eq!(
14844                active_item
14845                    .act_as::<Editor>(cx)
14846                    .expect("should have navigated into an editor")
14847                    .read(cx)
14848                    .text(cx),
14849                sample_text_2
14850            );
14851
14852            workspace
14853                .go_back(workspace.active_pane().downgrade(), window, cx)
14854                .detach_and_log_err(cx);
14855
14856            second_item_id
14857        })
14858        .unwrap();
14859    cx.executor().run_until_parked();
14860    workspace
14861        .update(cx, |workspace, _, cx| {
14862            let active_item = workspace
14863                .active_item(cx)
14864                .expect("should have an active item after navigating back from the 2nd buffer");
14865            assert_eq!(
14866                active_item.item_id(),
14867                multibuffer_item_id,
14868                "Should navigate back from the 2nd buffer to the multi buffer"
14869            );
14870            assert!(!active_item.is_singleton(cx));
14871        })
14872        .unwrap();
14873
14874    multi_buffer_editor.update_in(cx, |editor, window, cx| {
14875        editor.change_selections(Some(Autoscroll::Next), window, cx, |s| {
14876            s.select_ranges(Some(70..70))
14877        });
14878        editor.open_excerpts(&OpenExcerpts, window, cx);
14879    });
14880    cx.executor().run_until_parked();
14881    workspace
14882        .update(cx, |workspace, window, cx| {
14883            let active_item = workspace
14884                .active_item(cx)
14885                .expect("should have an active item after navigating into the 3rd buffer");
14886            let third_item_id = active_item.item_id();
14887            assert_ne!(
14888                third_item_id, multibuffer_item_id,
14889                "Should navigate into the 3rd buffer and activate it"
14890            );
14891            assert_ne!(third_item_id, first_item_id);
14892            assert_ne!(third_item_id, second_item_id);
14893            assert!(
14894                active_item.is_singleton(cx),
14895                "New active item should be a singleton buffer"
14896            );
14897            assert_eq!(
14898                active_item
14899                    .act_as::<Editor>(cx)
14900                    .expect("should have navigated into an editor")
14901                    .read(cx)
14902                    .text(cx),
14903                sample_text_3
14904            );
14905
14906            workspace
14907                .go_back(workspace.active_pane().downgrade(), window, cx)
14908                .detach_and_log_err(cx);
14909        })
14910        .unwrap();
14911    cx.executor().run_until_parked();
14912    workspace
14913        .update(cx, |workspace, _, cx| {
14914            let active_item = workspace
14915                .active_item(cx)
14916                .expect("should have an active item after navigating back from the 3rd buffer");
14917            assert_eq!(
14918                active_item.item_id(),
14919                multibuffer_item_id,
14920                "Should navigate back from the 3rd buffer to the multi buffer"
14921            );
14922            assert!(!active_item.is_singleton(cx));
14923        })
14924        .unwrap();
14925}
14926
14927#[gpui::test]
14928async fn test_toggle_selected_diff_hunks(executor: BackgroundExecutor, cx: &mut TestAppContext) {
14929    init_test(cx, |_| {});
14930
14931    let mut cx = EditorTestContext::new(cx).await;
14932
14933    let diff_base = r#"
14934        use some::mod;
14935
14936        const A: u32 = 42;
14937
14938        fn main() {
14939            println!("hello");
14940
14941            println!("world");
14942        }
14943        "#
14944    .unindent();
14945
14946    cx.set_state(
14947        &r#"
14948        use some::modified;
14949
14950        ˇ
14951        fn main() {
14952            println!("hello there");
14953
14954            println!("around the");
14955            println!("world");
14956        }
14957        "#
14958        .unindent(),
14959    );
14960
14961    cx.set_head_text(&diff_base);
14962    executor.run_until_parked();
14963
14964    cx.update_editor(|editor, window, cx| {
14965        editor.go_to_next_hunk(&GoToHunk, window, cx);
14966        editor.toggle_selected_diff_hunks(&ToggleSelectedDiffHunks, window, cx);
14967    });
14968    executor.run_until_parked();
14969    cx.assert_state_with_diff(
14970        r#"
14971          use some::modified;
14972
14973
14974          fn main() {
14975        -     println!("hello");
14976        + ˇ    println!("hello there");
14977
14978              println!("around the");
14979              println!("world");
14980          }
14981        "#
14982        .unindent(),
14983    );
14984
14985    cx.update_editor(|editor, window, cx| {
14986        for _ in 0..2 {
14987            editor.go_to_next_hunk(&GoToHunk, window, cx);
14988            editor.toggle_selected_diff_hunks(&ToggleSelectedDiffHunks, window, cx);
14989        }
14990    });
14991    executor.run_until_parked();
14992    cx.assert_state_with_diff(
14993        r#"
14994        - use some::mod;
14995        + ˇuse some::modified;
14996
14997
14998          fn main() {
14999        -     println!("hello");
15000        +     println!("hello there");
15001
15002        +     println!("around the");
15003              println!("world");
15004          }
15005        "#
15006        .unindent(),
15007    );
15008
15009    cx.update_editor(|editor, window, cx| {
15010        editor.go_to_next_hunk(&GoToHunk, window, cx);
15011        editor.toggle_selected_diff_hunks(&ToggleSelectedDiffHunks, window, cx);
15012    });
15013    executor.run_until_parked();
15014    cx.assert_state_with_diff(
15015        r#"
15016        - use some::mod;
15017        + use some::modified;
15018
15019        - const A: u32 = 42;
15020          ˇ
15021          fn main() {
15022        -     println!("hello");
15023        +     println!("hello there");
15024
15025        +     println!("around the");
15026              println!("world");
15027          }
15028        "#
15029        .unindent(),
15030    );
15031
15032    cx.update_editor(|editor, window, cx| {
15033        editor.cancel(&Cancel, window, cx);
15034    });
15035
15036    cx.assert_state_with_diff(
15037        r#"
15038          use some::modified;
15039
15040          ˇ
15041          fn main() {
15042              println!("hello there");
15043
15044              println!("around the");
15045              println!("world");
15046          }
15047        "#
15048        .unindent(),
15049    );
15050}
15051
15052#[gpui::test]
15053async fn test_diff_base_change_with_expanded_diff_hunks(
15054    executor: BackgroundExecutor,
15055    cx: &mut TestAppContext,
15056) {
15057    init_test(cx, |_| {});
15058
15059    let mut cx = EditorTestContext::new(cx).await;
15060
15061    let diff_base = r#"
15062        use some::mod1;
15063        use some::mod2;
15064
15065        const A: u32 = 42;
15066        const B: u32 = 42;
15067        const C: u32 = 42;
15068
15069        fn main() {
15070            println!("hello");
15071
15072            println!("world");
15073        }
15074        "#
15075    .unindent();
15076
15077    cx.set_state(
15078        &r#"
15079        use some::mod2;
15080
15081        const A: u32 = 42;
15082        const C: u32 = 42;
15083
15084        fn main(ˇ) {
15085            //println!("hello");
15086
15087            println!("world");
15088            //
15089            //
15090        }
15091        "#
15092        .unindent(),
15093    );
15094
15095    cx.set_head_text(&diff_base);
15096    executor.run_until_parked();
15097
15098    cx.update_editor(|editor, window, cx| {
15099        editor.expand_all_diff_hunks(&ExpandAllDiffHunks, window, cx);
15100    });
15101    executor.run_until_parked();
15102    cx.assert_state_with_diff(
15103        r#"
15104        - use some::mod1;
15105          use some::mod2;
15106
15107          const A: u32 = 42;
15108        - const B: u32 = 42;
15109          const C: u32 = 42;
15110
15111          fn main(ˇ) {
15112        -     println!("hello");
15113        +     //println!("hello");
15114
15115              println!("world");
15116        +     //
15117        +     //
15118          }
15119        "#
15120        .unindent(),
15121    );
15122
15123    cx.set_head_text("new diff base!");
15124    executor.run_until_parked();
15125    cx.assert_state_with_diff(
15126        r#"
15127        - new diff base!
15128        + use some::mod2;
15129        +
15130        + const A: u32 = 42;
15131        + const C: u32 = 42;
15132        +
15133        + fn main(ˇ) {
15134        +     //println!("hello");
15135        +
15136        +     println!("world");
15137        +     //
15138        +     //
15139        + }
15140        "#
15141        .unindent(),
15142    );
15143}
15144
15145#[gpui::test]
15146async fn test_toggle_diff_expand_in_multi_buffer(cx: &mut TestAppContext) {
15147    init_test(cx, |_| {});
15148
15149    let file_1_old = "aaa\nbbb\nccc\nddd\neee\nfff\nggg\nhhh\niii\njjj";
15150    let file_1_new = "aaa\nccc\nddd\neee\nfff\nggg\nhhh\niii\njjj";
15151    let file_2_old = "lll\nmmm\nnnn\nooo\nppp\nqqq\nrrr\nsss\nttt\nuuu";
15152    let file_2_new = "lll\nmmm\nNNN\nooo\nppp\nqqq\nrrr\nsss\nttt\nuuu";
15153    let file_3_old = "111\n222\n333\n444\n555\n777\n888\n999\n000\n!!!";
15154    let file_3_new = "111\n222\n333\n444\n555\n666\n777\n888\n999\n000\n!!!";
15155
15156    let buffer_1 = cx.new(|cx| Buffer::local(file_1_new.to_string(), cx));
15157    let buffer_2 = cx.new(|cx| Buffer::local(file_2_new.to_string(), cx));
15158    let buffer_3 = cx.new(|cx| Buffer::local(file_3_new.to_string(), cx));
15159
15160    let multi_buffer = cx.new(|cx| {
15161        let mut multibuffer = MultiBuffer::new(ReadWrite);
15162        multibuffer.push_excerpts(
15163            buffer_1.clone(),
15164            [
15165                ExcerptRange::new(Point::new(0, 0)..Point::new(3, 0)),
15166                ExcerptRange::new(Point::new(5, 0)..Point::new(7, 0)),
15167                ExcerptRange::new(Point::new(9, 0)..Point::new(10, 3)),
15168            ],
15169            cx,
15170        );
15171        multibuffer.push_excerpts(
15172            buffer_2.clone(),
15173            [
15174                ExcerptRange::new(Point::new(0, 0)..Point::new(3, 0)),
15175                ExcerptRange::new(Point::new(5, 0)..Point::new(7, 0)),
15176                ExcerptRange::new(Point::new(9, 0)..Point::new(10, 3)),
15177            ],
15178            cx,
15179        );
15180        multibuffer.push_excerpts(
15181            buffer_3.clone(),
15182            [
15183                ExcerptRange::new(Point::new(0, 0)..Point::new(3, 0)),
15184                ExcerptRange::new(Point::new(5, 0)..Point::new(7, 0)),
15185                ExcerptRange::new(Point::new(9, 0)..Point::new(10, 3)),
15186            ],
15187            cx,
15188        );
15189        multibuffer
15190    });
15191
15192    let editor =
15193        cx.add_window(|window, cx| Editor::new(EditorMode::full(), multi_buffer, None, window, cx));
15194    editor
15195        .update(cx, |editor, _window, cx| {
15196            for (buffer, diff_base) in [
15197                (buffer_1.clone(), file_1_old),
15198                (buffer_2.clone(), file_2_old),
15199                (buffer_3.clone(), file_3_old),
15200            ] {
15201                let diff = cx.new(|cx| BufferDiff::new_with_base_text(&diff_base, &buffer, cx));
15202                editor
15203                    .buffer
15204                    .update(cx, |buffer, cx| buffer.add_diff(diff, cx));
15205            }
15206        })
15207        .unwrap();
15208
15209    let mut cx = EditorTestContext::for_editor(editor, cx).await;
15210    cx.run_until_parked();
15211
15212    cx.assert_editor_state(
15213        &"
15214            ˇaaa
15215            ccc
15216            ddd
15217
15218            ggg
15219            hhh
15220
15221
15222            lll
15223            mmm
15224            NNN
15225
15226            qqq
15227            rrr
15228
15229            uuu
15230            111
15231            222
15232            333
15233
15234            666
15235            777
15236
15237            000
15238            !!!"
15239        .unindent(),
15240    );
15241
15242    cx.update_editor(|editor, window, cx| {
15243        editor.select_all(&SelectAll, window, cx);
15244        editor.toggle_selected_diff_hunks(&ToggleSelectedDiffHunks, window, cx);
15245    });
15246    cx.executor().run_until_parked();
15247
15248    cx.assert_state_with_diff(
15249        "
15250            «aaa
15251          - bbb
15252            ccc
15253            ddd
15254
15255            ggg
15256            hhh
15257
15258
15259            lll
15260            mmm
15261          - nnn
15262          + NNN
15263
15264            qqq
15265            rrr
15266
15267            uuu
15268            111
15269            222
15270            333
15271
15272          + 666
15273            777
15274
15275            000
15276            !!!ˇ»"
15277            .unindent(),
15278    );
15279}
15280
15281#[gpui::test]
15282async fn test_expand_diff_hunk_at_excerpt_boundary(cx: &mut TestAppContext) {
15283    init_test(cx, |_| {});
15284
15285    let base = "aaa\nbbb\nccc\nddd\neee\nfff\nggg\n";
15286    let text = "aaa\nBBB\nBB2\nccc\nDDD\nEEE\nfff\nggg\nhhh\niii\n";
15287
15288    let buffer = cx.new(|cx| Buffer::local(text.to_string(), cx));
15289    let multi_buffer = cx.new(|cx| {
15290        let mut multibuffer = MultiBuffer::new(ReadWrite);
15291        multibuffer.push_excerpts(
15292            buffer.clone(),
15293            [
15294                ExcerptRange::new(Point::new(0, 0)..Point::new(2, 0)),
15295                ExcerptRange::new(Point::new(4, 0)..Point::new(7, 0)),
15296                ExcerptRange::new(Point::new(9, 0)..Point::new(10, 0)),
15297            ],
15298            cx,
15299        );
15300        multibuffer
15301    });
15302
15303    let editor =
15304        cx.add_window(|window, cx| Editor::new(EditorMode::full(), multi_buffer, None, window, cx));
15305    editor
15306        .update(cx, |editor, _window, cx| {
15307            let diff = cx.new(|cx| BufferDiff::new_with_base_text(base, &buffer, cx));
15308            editor
15309                .buffer
15310                .update(cx, |buffer, cx| buffer.add_diff(diff, cx))
15311        })
15312        .unwrap();
15313
15314    let mut cx = EditorTestContext::for_editor(editor, cx).await;
15315    cx.run_until_parked();
15316
15317    cx.update_editor(|editor, window, cx| {
15318        editor.expand_all_diff_hunks(&Default::default(), window, cx)
15319    });
15320    cx.executor().run_until_parked();
15321
15322    // When the start of a hunk coincides with the start of its excerpt,
15323    // the hunk is expanded. When the start of a a hunk is earlier than
15324    // the start of its excerpt, the hunk is not expanded.
15325    cx.assert_state_with_diff(
15326        "
15327            ˇaaa
15328          - bbb
15329          + BBB
15330
15331          - ddd
15332          - eee
15333          + DDD
15334          + EEE
15335            fff
15336
15337            iii
15338        "
15339        .unindent(),
15340    );
15341}
15342
15343#[gpui::test]
15344async fn test_edits_around_expanded_insertion_hunks(
15345    executor: BackgroundExecutor,
15346    cx: &mut TestAppContext,
15347) {
15348    init_test(cx, |_| {});
15349
15350    let mut cx = EditorTestContext::new(cx).await;
15351
15352    let diff_base = r#"
15353        use some::mod1;
15354        use some::mod2;
15355
15356        const A: u32 = 42;
15357
15358        fn main() {
15359            println!("hello");
15360
15361            println!("world");
15362        }
15363        "#
15364    .unindent();
15365    executor.run_until_parked();
15366    cx.set_state(
15367        &r#"
15368        use some::mod1;
15369        use some::mod2;
15370
15371        const A: u32 = 42;
15372        const B: u32 = 42;
15373        const C: u32 = 42;
15374        ˇ
15375
15376        fn main() {
15377            println!("hello");
15378
15379            println!("world");
15380        }
15381        "#
15382        .unindent(),
15383    );
15384
15385    cx.set_head_text(&diff_base);
15386    executor.run_until_parked();
15387
15388    cx.update_editor(|editor, window, cx| {
15389        editor.expand_all_diff_hunks(&ExpandAllDiffHunks, window, cx);
15390    });
15391    executor.run_until_parked();
15392
15393    cx.assert_state_with_diff(
15394        r#"
15395        use some::mod1;
15396        use some::mod2;
15397
15398        const A: u32 = 42;
15399      + const B: u32 = 42;
15400      + const C: u32 = 42;
15401      + ˇ
15402
15403        fn main() {
15404            println!("hello");
15405
15406            println!("world");
15407        }
15408      "#
15409        .unindent(),
15410    );
15411
15412    cx.update_editor(|editor, window, cx| editor.handle_input("const D: u32 = 42;\n", window, cx));
15413    executor.run_until_parked();
15414
15415    cx.assert_state_with_diff(
15416        r#"
15417        use some::mod1;
15418        use some::mod2;
15419
15420        const A: u32 = 42;
15421      + const B: u32 = 42;
15422      + const C: u32 = 42;
15423      + const D: u32 = 42;
15424      + ˇ
15425
15426        fn main() {
15427            println!("hello");
15428
15429            println!("world");
15430        }
15431      "#
15432        .unindent(),
15433    );
15434
15435    cx.update_editor(|editor, window, cx| editor.handle_input("const E: u32 = 42;\n", window, cx));
15436    executor.run_until_parked();
15437
15438    cx.assert_state_with_diff(
15439        r#"
15440        use some::mod1;
15441        use some::mod2;
15442
15443        const A: u32 = 42;
15444      + const B: u32 = 42;
15445      + const C: u32 = 42;
15446      + const D: u32 = 42;
15447      + const E: u32 = 42;
15448      + ˇ
15449
15450        fn main() {
15451            println!("hello");
15452
15453            println!("world");
15454        }
15455      "#
15456        .unindent(),
15457    );
15458
15459    cx.update_editor(|editor, window, cx| {
15460        editor.delete_line(&DeleteLine, window, cx);
15461    });
15462    executor.run_until_parked();
15463
15464    cx.assert_state_with_diff(
15465        r#"
15466        use some::mod1;
15467        use some::mod2;
15468
15469        const A: u32 = 42;
15470      + const B: u32 = 42;
15471      + const C: u32 = 42;
15472      + const D: u32 = 42;
15473      + const E: u32 = 42;
15474        ˇ
15475        fn main() {
15476            println!("hello");
15477
15478            println!("world");
15479        }
15480      "#
15481        .unindent(),
15482    );
15483
15484    cx.update_editor(|editor, window, cx| {
15485        editor.move_up(&MoveUp, window, cx);
15486        editor.delete_line(&DeleteLine, window, cx);
15487        editor.move_up(&MoveUp, window, cx);
15488        editor.delete_line(&DeleteLine, window, cx);
15489        editor.move_up(&MoveUp, window, cx);
15490        editor.delete_line(&DeleteLine, window, cx);
15491    });
15492    executor.run_until_parked();
15493    cx.assert_state_with_diff(
15494        r#"
15495        use some::mod1;
15496        use some::mod2;
15497
15498        const A: u32 = 42;
15499      + const B: u32 = 42;
15500        ˇ
15501        fn main() {
15502            println!("hello");
15503
15504            println!("world");
15505        }
15506      "#
15507        .unindent(),
15508    );
15509
15510    cx.update_editor(|editor, window, cx| {
15511        editor.select_up_by_lines(&SelectUpByLines { lines: 5 }, window, cx);
15512        editor.delete_line(&DeleteLine, window, cx);
15513    });
15514    executor.run_until_parked();
15515    cx.assert_state_with_diff(
15516        r#"
15517        ˇ
15518        fn main() {
15519            println!("hello");
15520
15521            println!("world");
15522        }
15523      "#
15524        .unindent(),
15525    );
15526}
15527
15528#[gpui::test]
15529async fn test_toggling_adjacent_diff_hunks(cx: &mut TestAppContext) {
15530    init_test(cx, |_| {});
15531
15532    let mut cx = EditorTestContext::new(cx).await;
15533    cx.set_head_text(indoc! { "
15534        one
15535        two
15536        three
15537        four
15538        five
15539        "
15540    });
15541    cx.set_state(indoc! { "
15542        one
15543        ˇthree
15544        five
15545    "});
15546    cx.run_until_parked();
15547    cx.update_editor(|editor, window, cx| {
15548        editor.toggle_selected_diff_hunks(&Default::default(), window, cx);
15549    });
15550    cx.assert_state_with_diff(
15551        indoc! { "
15552        one
15553      - two
15554        ˇthree
15555      - four
15556        five
15557    "}
15558        .to_string(),
15559    );
15560    cx.update_editor(|editor, window, cx| {
15561        editor.toggle_selected_diff_hunks(&Default::default(), window, cx);
15562    });
15563
15564    cx.assert_state_with_diff(
15565        indoc! { "
15566        one
15567        ˇthree
15568        five
15569    "}
15570        .to_string(),
15571    );
15572
15573    cx.set_state(indoc! { "
15574        one
15575        ˇTWO
15576        three
15577        four
15578        five
15579    "});
15580    cx.run_until_parked();
15581    cx.update_editor(|editor, window, cx| {
15582        editor.toggle_selected_diff_hunks(&Default::default(), window, cx);
15583    });
15584
15585    cx.assert_state_with_diff(
15586        indoc! { "
15587            one
15588          - two
15589          + ˇTWO
15590            three
15591            four
15592            five
15593        "}
15594        .to_string(),
15595    );
15596    cx.update_editor(|editor, window, cx| {
15597        editor.move_up(&Default::default(), window, cx);
15598        editor.toggle_selected_diff_hunks(&Default::default(), window, cx);
15599    });
15600    cx.assert_state_with_diff(
15601        indoc! { "
15602            one
15603            ˇTWO
15604            three
15605            four
15606            five
15607        "}
15608        .to_string(),
15609    );
15610}
15611
15612#[gpui::test]
15613async fn test_edits_around_expanded_deletion_hunks(
15614    executor: BackgroundExecutor,
15615    cx: &mut TestAppContext,
15616) {
15617    init_test(cx, |_| {});
15618
15619    let mut cx = EditorTestContext::new(cx).await;
15620
15621    let diff_base = r#"
15622        use some::mod1;
15623        use some::mod2;
15624
15625        const A: u32 = 42;
15626        const B: u32 = 42;
15627        const C: u32 = 42;
15628
15629
15630        fn main() {
15631            println!("hello");
15632
15633            println!("world");
15634        }
15635    "#
15636    .unindent();
15637    executor.run_until_parked();
15638    cx.set_state(
15639        &r#"
15640        use some::mod1;
15641        use some::mod2;
15642
15643        ˇconst B: u32 = 42;
15644        const C: u32 = 42;
15645
15646
15647        fn main() {
15648            println!("hello");
15649
15650            println!("world");
15651        }
15652        "#
15653        .unindent(),
15654    );
15655
15656    cx.set_head_text(&diff_base);
15657    executor.run_until_parked();
15658
15659    cx.update_editor(|editor, window, cx| {
15660        editor.expand_all_diff_hunks(&ExpandAllDiffHunks, window, cx);
15661    });
15662    executor.run_until_parked();
15663
15664    cx.assert_state_with_diff(
15665        r#"
15666        use some::mod1;
15667        use some::mod2;
15668
15669      - const A: u32 = 42;
15670        ˇconst B: u32 = 42;
15671        const C: u32 = 42;
15672
15673
15674        fn main() {
15675            println!("hello");
15676
15677            println!("world");
15678        }
15679      "#
15680        .unindent(),
15681    );
15682
15683    cx.update_editor(|editor, window, cx| {
15684        editor.delete_line(&DeleteLine, window, cx);
15685    });
15686    executor.run_until_parked();
15687    cx.assert_state_with_diff(
15688        r#"
15689        use some::mod1;
15690        use some::mod2;
15691
15692      - const A: u32 = 42;
15693      - const B: u32 = 42;
15694        ˇconst C: u32 = 42;
15695
15696
15697        fn main() {
15698            println!("hello");
15699
15700            println!("world");
15701        }
15702      "#
15703        .unindent(),
15704    );
15705
15706    cx.update_editor(|editor, window, cx| {
15707        editor.delete_line(&DeleteLine, window, cx);
15708    });
15709    executor.run_until_parked();
15710    cx.assert_state_with_diff(
15711        r#"
15712        use some::mod1;
15713        use some::mod2;
15714
15715      - const A: u32 = 42;
15716      - const B: u32 = 42;
15717      - const C: u32 = 42;
15718        ˇ
15719
15720        fn main() {
15721            println!("hello");
15722
15723            println!("world");
15724        }
15725      "#
15726        .unindent(),
15727    );
15728
15729    cx.update_editor(|editor, window, cx| {
15730        editor.handle_input("replacement", window, cx);
15731    });
15732    executor.run_until_parked();
15733    cx.assert_state_with_diff(
15734        r#"
15735        use some::mod1;
15736        use some::mod2;
15737
15738      - const A: u32 = 42;
15739      - const B: u32 = 42;
15740      - const C: u32 = 42;
15741      -
15742      + replacementˇ
15743
15744        fn main() {
15745            println!("hello");
15746
15747            println!("world");
15748        }
15749      "#
15750        .unindent(),
15751    );
15752}
15753
15754#[gpui::test]
15755async fn test_backspace_after_deletion_hunk(executor: BackgroundExecutor, cx: &mut TestAppContext) {
15756    init_test(cx, |_| {});
15757
15758    let mut cx = EditorTestContext::new(cx).await;
15759
15760    let base_text = r#"
15761        one
15762        two
15763        three
15764        four
15765        five
15766    "#
15767    .unindent();
15768    executor.run_until_parked();
15769    cx.set_state(
15770        &r#"
15771        one
15772        two
15773        fˇour
15774        five
15775        "#
15776        .unindent(),
15777    );
15778
15779    cx.set_head_text(&base_text);
15780    executor.run_until_parked();
15781
15782    cx.update_editor(|editor, window, cx| {
15783        editor.expand_all_diff_hunks(&ExpandAllDiffHunks, window, cx);
15784    });
15785    executor.run_until_parked();
15786
15787    cx.assert_state_with_diff(
15788        r#"
15789          one
15790          two
15791        - three
15792          fˇour
15793          five
15794        "#
15795        .unindent(),
15796    );
15797
15798    cx.update_editor(|editor, window, cx| {
15799        editor.backspace(&Backspace, window, cx);
15800        editor.backspace(&Backspace, window, cx);
15801    });
15802    executor.run_until_parked();
15803    cx.assert_state_with_diff(
15804        r#"
15805          one
15806          two
15807        - threeˇ
15808        - four
15809        + our
15810          five
15811        "#
15812        .unindent(),
15813    );
15814}
15815
15816#[gpui::test]
15817async fn test_edit_after_expanded_modification_hunk(
15818    executor: BackgroundExecutor,
15819    cx: &mut TestAppContext,
15820) {
15821    init_test(cx, |_| {});
15822
15823    let mut cx = EditorTestContext::new(cx).await;
15824
15825    let diff_base = r#"
15826        use some::mod1;
15827        use some::mod2;
15828
15829        const A: u32 = 42;
15830        const B: u32 = 42;
15831        const C: u32 = 42;
15832        const D: u32 = 42;
15833
15834
15835        fn main() {
15836            println!("hello");
15837
15838            println!("world");
15839        }"#
15840    .unindent();
15841
15842    cx.set_state(
15843        &r#"
15844        use some::mod1;
15845        use some::mod2;
15846
15847        const A: u32 = 42;
15848        const B: u32 = 42;
15849        const C: u32 = 43ˇ
15850        const D: u32 = 42;
15851
15852
15853        fn main() {
15854            println!("hello");
15855
15856            println!("world");
15857        }"#
15858        .unindent(),
15859    );
15860
15861    cx.set_head_text(&diff_base);
15862    executor.run_until_parked();
15863    cx.update_editor(|editor, window, cx| {
15864        editor.expand_all_diff_hunks(&ExpandAllDiffHunks, window, cx);
15865    });
15866    executor.run_until_parked();
15867
15868    cx.assert_state_with_diff(
15869        r#"
15870        use some::mod1;
15871        use some::mod2;
15872
15873        const A: u32 = 42;
15874        const B: u32 = 42;
15875      - const C: u32 = 42;
15876      + const C: u32 = 43ˇ
15877        const D: u32 = 42;
15878
15879
15880        fn main() {
15881            println!("hello");
15882
15883            println!("world");
15884        }"#
15885        .unindent(),
15886    );
15887
15888    cx.update_editor(|editor, window, cx| {
15889        editor.handle_input("\nnew_line\n", window, cx);
15890    });
15891    executor.run_until_parked();
15892
15893    cx.assert_state_with_diff(
15894        r#"
15895        use some::mod1;
15896        use some::mod2;
15897
15898        const A: u32 = 42;
15899        const B: u32 = 42;
15900      - const C: u32 = 42;
15901      + const C: u32 = 43
15902      + new_line
15903      + ˇ
15904        const D: u32 = 42;
15905
15906
15907        fn main() {
15908            println!("hello");
15909
15910            println!("world");
15911        }"#
15912        .unindent(),
15913    );
15914}
15915
15916#[gpui::test]
15917async fn test_stage_and_unstage_added_file_hunk(
15918    executor: BackgroundExecutor,
15919    cx: &mut TestAppContext,
15920) {
15921    init_test(cx, |_| {});
15922
15923    let mut cx = EditorTestContext::new(cx).await;
15924    cx.update_editor(|editor, _, cx| {
15925        editor.set_expand_all_diff_hunks(cx);
15926    });
15927
15928    let working_copy = r#"
15929            ˇfn main() {
15930                println!("hello, world!");
15931            }
15932        "#
15933    .unindent();
15934
15935    cx.set_state(&working_copy);
15936    executor.run_until_parked();
15937
15938    cx.assert_state_with_diff(
15939        r#"
15940            + ˇfn main() {
15941            +     println!("hello, world!");
15942            + }
15943        "#
15944        .unindent(),
15945    );
15946    cx.assert_index_text(None);
15947
15948    cx.update_editor(|editor, window, cx| {
15949        editor.toggle_staged_selected_diff_hunks(&Default::default(), window, cx);
15950    });
15951    executor.run_until_parked();
15952    cx.assert_index_text(Some(&working_copy.replace("ˇ", "")));
15953    cx.assert_state_with_diff(
15954        r#"
15955            + ˇfn main() {
15956            +     println!("hello, world!");
15957            + }
15958        "#
15959        .unindent(),
15960    );
15961
15962    cx.update_editor(|editor, window, cx| {
15963        editor.toggle_staged_selected_diff_hunks(&Default::default(), window, cx);
15964    });
15965    executor.run_until_parked();
15966    cx.assert_index_text(None);
15967}
15968
15969async fn setup_indent_guides_editor(
15970    text: &str,
15971    cx: &mut TestAppContext,
15972) -> (BufferId, EditorTestContext) {
15973    init_test(cx, |_| {});
15974
15975    let mut cx = EditorTestContext::new(cx).await;
15976
15977    let buffer_id = cx.update_editor(|editor, window, cx| {
15978        editor.set_text(text, window, cx);
15979        let buffer_ids = editor.buffer().read(cx).excerpt_buffer_ids();
15980
15981        buffer_ids[0]
15982    });
15983
15984    (buffer_id, cx)
15985}
15986
15987fn assert_indent_guides(
15988    range: Range<u32>,
15989    expected: Vec<IndentGuide>,
15990    active_indices: Option<Vec<usize>>,
15991    cx: &mut EditorTestContext,
15992) {
15993    let indent_guides = cx.update_editor(|editor, window, cx| {
15994        let snapshot = editor.snapshot(window, cx).display_snapshot;
15995        let mut indent_guides: Vec<_> = crate::indent_guides::indent_guides_in_range(
15996            editor,
15997            MultiBufferRow(range.start)..MultiBufferRow(range.end),
15998            true,
15999            &snapshot,
16000            cx,
16001        );
16002
16003        indent_guides.sort_by(|a, b| {
16004            a.depth.cmp(&b.depth).then(
16005                a.start_row
16006                    .cmp(&b.start_row)
16007                    .then(a.end_row.cmp(&b.end_row)),
16008            )
16009        });
16010        indent_guides
16011    });
16012
16013    if let Some(expected) = active_indices {
16014        let active_indices = cx.update_editor(|editor, window, cx| {
16015            let snapshot = editor.snapshot(window, cx).display_snapshot;
16016            editor.find_active_indent_guide_indices(&indent_guides, &snapshot, window, cx)
16017        });
16018
16019        assert_eq!(
16020            active_indices.unwrap().into_iter().collect::<Vec<_>>(),
16021            expected,
16022            "Active indent guide indices do not match"
16023        );
16024    }
16025
16026    assert_eq!(indent_guides, expected, "Indent guides do not match");
16027}
16028
16029fn indent_guide(buffer_id: BufferId, start_row: u32, end_row: u32, depth: u32) -> IndentGuide {
16030    IndentGuide {
16031        buffer_id,
16032        start_row: MultiBufferRow(start_row),
16033        end_row: MultiBufferRow(end_row),
16034        depth,
16035        tab_size: 4,
16036        settings: IndentGuideSettings {
16037            enabled: true,
16038            line_width: 1,
16039            active_line_width: 1,
16040            ..Default::default()
16041        },
16042    }
16043}
16044
16045#[gpui::test]
16046async fn test_indent_guide_single_line(cx: &mut TestAppContext) {
16047    let (buffer_id, mut cx) = setup_indent_guides_editor(
16048        &"
16049    fn main() {
16050        let a = 1;
16051    }"
16052        .unindent(),
16053        cx,
16054    )
16055    .await;
16056
16057    assert_indent_guides(0..3, vec![indent_guide(buffer_id, 1, 1, 0)], None, &mut cx);
16058}
16059
16060#[gpui::test]
16061async fn test_indent_guide_simple_block(cx: &mut TestAppContext) {
16062    let (buffer_id, mut cx) = setup_indent_guides_editor(
16063        &"
16064    fn main() {
16065        let a = 1;
16066        let b = 2;
16067    }"
16068        .unindent(),
16069        cx,
16070    )
16071    .await;
16072
16073    assert_indent_guides(0..4, vec![indent_guide(buffer_id, 1, 2, 0)], None, &mut cx);
16074}
16075
16076#[gpui::test]
16077async fn test_indent_guide_nested(cx: &mut TestAppContext) {
16078    let (buffer_id, mut cx) = setup_indent_guides_editor(
16079        &"
16080    fn main() {
16081        let a = 1;
16082        if a == 3 {
16083            let b = 2;
16084        } else {
16085            let c = 3;
16086        }
16087    }"
16088        .unindent(),
16089        cx,
16090    )
16091    .await;
16092
16093    assert_indent_guides(
16094        0..8,
16095        vec![
16096            indent_guide(buffer_id, 1, 6, 0),
16097            indent_guide(buffer_id, 3, 3, 1),
16098            indent_guide(buffer_id, 5, 5, 1),
16099        ],
16100        None,
16101        &mut cx,
16102    );
16103}
16104
16105#[gpui::test]
16106async fn test_indent_guide_tab(cx: &mut TestAppContext) {
16107    let (buffer_id, mut cx) = setup_indent_guides_editor(
16108        &"
16109    fn main() {
16110        let a = 1;
16111            let b = 2;
16112        let c = 3;
16113    }"
16114        .unindent(),
16115        cx,
16116    )
16117    .await;
16118
16119    assert_indent_guides(
16120        0..5,
16121        vec![
16122            indent_guide(buffer_id, 1, 3, 0),
16123            indent_guide(buffer_id, 2, 2, 1),
16124        ],
16125        None,
16126        &mut cx,
16127    );
16128}
16129
16130#[gpui::test]
16131async fn test_indent_guide_continues_on_empty_line(cx: &mut TestAppContext) {
16132    let (buffer_id, mut cx) = setup_indent_guides_editor(
16133        &"
16134        fn main() {
16135            let a = 1;
16136
16137            let c = 3;
16138        }"
16139        .unindent(),
16140        cx,
16141    )
16142    .await;
16143
16144    assert_indent_guides(0..5, vec![indent_guide(buffer_id, 1, 3, 0)], None, &mut cx);
16145}
16146
16147#[gpui::test]
16148async fn test_indent_guide_complex(cx: &mut TestAppContext) {
16149    let (buffer_id, mut cx) = setup_indent_guides_editor(
16150        &"
16151        fn main() {
16152            let a = 1;
16153
16154            let c = 3;
16155
16156            if a == 3 {
16157                let b = 2;
16158            } else {
16159                let c = 3;
16160            }
16161        }"
16162        .unindent(),
16163        cx,
16164    )
16165    .await;
16166
16167    assert_indent_guides(
16168        0..11,
16169        vec![
16170            indent_guide(buffer_id, 1, 9, 0),
16171            indent_guide(buffer_id, 6, 6, 1),
16172            indent_guide(buffer_id, 8, 8, 1),
16173        ],
16174        None,
16175        &mut cx,
16176    );
16177}
16178
16179#[gpui::test]
16180async fn test_indent_guide_starts_off_screen(cx: &mut TestAppContext) {
16181    let (buffer_id, mut cx) = setup_indent_guides_editor(
16182        &"
16183        fn main() {
16184            let a = 1;
16185
16186            let c = 3;
16187
16188            if a == 3 {
16189                let b = 2;
16190            } else {
16191                let c = 3;
16192            }
16193        }"
16194        .unindent(),
16195        cx,
16196    )
16197    .await;
16198
16199    assert_indent_guides(
16200        1..11,
16201        vec![
16202            indent_guide(buffer_id, 1, 9, 0),
16203            indent_guide(buffer_id, 6, 6, 1),
16204            indent_guide(buffer_id, 8, 8, 1),
16205        ],
16206        None,
16207        &mut cx,
16208    );
16209}
16210
16211#[gpui::test]
16212async fn test_indent_guide_ends_off_screen(cx: &mut TestAppContext) {
16213    let (buffer_id, mut cx) = setup_indent_guides_editor(
16214        &"
16215        fn main() {
16216            let a = 1;
16217
16218            let c = 3;
16219
16220            if a == 3 {
16221                let b = 2;
16222            } else {
16223                let c = 3;
16224            }
16225        }"
16226        .unindent(),
16227        cx,
16228    )
16229    .await;
16230
16231    assert_indent_guides(
16232        1..10,
16233        vec![
16234            indent_guide(buffer_id, 1, 9, 0),
16235            indent_guide(buffer_id, 6, 6, 1),
16236            indent_guide(buffer_id, 8, 8, 1),
16237        ],
16238        None,
16239        &mut cx,
16240    );
16241}
16242
16243#[gpui::test]
16244async fn test_indent_guide_without_brackets(cx: &mut TestAppContext) {
16245    let (buffer_id, mut cx) = setup_indent_guides_editor(
16246        &"
16247        block1
16248            block2
16249                block3
16250                    block4
16251            block2
16252        block1
16253        block1"
16254            .unindent(),
16255        cx,
16256    )
16257    .await;
16258
16259    assert_indent_guides(
16260        1..10,
16261        vec![
16262            indent_guide(buffer_id, 1, 4, 0),
16263            indent_guide(buffer_id, 2, 3, 1),
16264            indent_guide(buffer_id, 3, 3, 2),
16265        ],
16266        None,
16267        &mut cx,
16268    );
16269}
16270
16271#[gpui::test]
16272async fn test_indent_guide_ends_before_empty_line(cx: &mut TestAppContext) {
16273    let (buffer_id, mut cx) = setup_indent_guides_editor(
16274        &"
16275        block1
16276            block2
16277                block3
16278
16279        block1
16280        block1"
16281            .unindent(),
16282        cx,
16283    )
16284    .await;
16285
16286    assert_indent_guides(
16287        0..6,
16288        vec![
16289            indent_guide(buffer_id, 1, 2, 0),
16290            indent_guide(buffer_id, 2, 2, 1),
16291        ],
16292        None,
16293        &mut cx,
16294    );
16295}
16296
16297#[gpui::test]
16298async fn test_indent_guide_continuing_off_screen(cx: &mut TestAppContext) {
16299    let (buffer_id, mut cx) = setup_indent_guides_editor(
16300        &"
16301        block1
16302
16303
16304
16305            block2
16306        "
16307        .unindent(),
16308        cx,
16309    )
16310    .await;
16311
16312    assert_indent_guides(0..1, vec![indent_guide(buffer_id, 1, 1, 0)], None, &mut cx);
16313}
16314
16315#[gpui::test]
16316async fn test_indent_guide_tabs(cx: &mut TestAppContext) {
16317    let (buffer_id, mut cx) = setup_indent_guides_editor(
16318        &"
16319        def a:
16320        \tb = 3
16321        \tif True:
16322        \t\tc = 4
16323        \t\td = 5
16324        \tprint(b)
16325        "
16326        .unindent(),
16327        cx,
16328    )
16329    .await;
16330
16331    assert_indent_guides(
16332        0..6,
16333        vec![
16334            indent_guide(buffer_id, 1, 6, 0),
16335            indent_guide(buffer_id, 3, 4, 1),
16336        ],
16337        None,
16338        &mut cx,
16339    );
16340}
16341
16342#[gpui::test]
16343async fn test_active_indent_guide_single_line(cx: &mut TestAppContext) {
16344    let (buffer_id, mut cx) = setup_indent_guides_editor(
16345        &"
16346    fn main() {
16347        let a = 1;
16348    }"
16349        .unindent(),
16350        cx,
16351    )
16352    .await;
16353
16354    cx.update_editor(|editor, window, cx| {
16355        editor.change_selections(None, window, cx, |s| {
16356            s.select_ranges([Point::new(1, 0)..Point::new(1, 0)])
16357        });
16358    });
16359
16360    assert_indent_guides(
16361        0..3,
16362        vec![indent_guide(buffer_id, 1, 1, 0)],
16363        Some(vec![0]),
16364        &mut cx,
16365    );
16366}
16367
16368#[gpui::test]
16369async fn test_active_indent_guide_respect_indented_range(cx: &mut TestAppContext) {
16370    let (buffer_id, mut cx) = setup_indent_guides_editor(
16371        &"
16372    fn main() {
16373        if 1 == 2 {
16374            let a = 1;
16375        }
16376    }"
16377        .unindent(),
16378        cx,
16379    )
16380    .await;
16381
16382    cx.update_editor(|editor, window, cx| {
16383        editor.change_selections(None, window, cx, |s| {
16384            s.select_ranges([Point::new(1, 0)..Point::new(1, 0)])
16385        });
16386    });
16387
16388    assert_indent_guides(
16389        0..4,
16390        vec![
16391            indent_guide(buffer_id, 1, 3, 0),
16392            indent_guide(buffer_id, 2, 2, 1),
16393        ],
16394        Some(vec![1]),
16395        &mut cx,
16396    );
16397
16398    cx.update_editor(|editor, window, cx| {
16399        editor.change_selections(None, window, cx, |s| {
16400            s.select_ranges([Point::new(2, 0)..Point::new(2, 0)])
16401        });
16402    });
16403
16404    assert_indent_guides(
16405        0..4,
16406        vec![
16407            indent_guide(buffer_id, 1, 3, 0),
16408            indent_guide(buffer_id, 2, 2, 1),
16409        ],
16410        Some(vec![1]),
16411        &mut cx,
16412    );
16413
16414    cx.update_editor(|editor, window, cx| {
16415        editor.change_selections(None, window, cx, |s| {
16416            s.select_ranges([Point::new(3, 0)..Point::new(3, 0)])
16417        });
16418    });
16419
16420    assert_indent_guides(
16421        0..4,
16422        vec![
16423            indent_guide(buffer_id, 1, 3, 0),
16424            indent_guide(buffer_id, 2, 2, 1),
16425        ],
16426        Some(vec![0]),
16427        &mut cx,
16428    );
16429}
16430
16431#[gpui::test]
16432async fn test_active_indent_guide_empty_line(cx: &mut TestAppContext) {
16433    let (buffer_id, mut cx) = setup_indent_guides_editor(
16434        &"
16435    fn main() {
16436        let a = 1;
16437
16438        let b = 2;
16439    }"
16440        .unindent(),
16441        cx,
16442    )
16443    .await;
16444
16445    cx.update_editor(|editor, window, cx| {
16446        editor.change_selections(None, window, cx, |s| {
16447            s.select_ranges([Point::new(2, 0)..Point::new(2, 0)])
16448        });
16449    });
16450
16451    assert_indent_guides(
16452        0..5,
16453        vec![indent_guide(buffer_id, 1, 3, 0)],
16454        Some(vec![0]),
16455        &mut cx,
16456    );
16457}
16458
16459#[gpui::test]
16460async fn test_active_indent_guide_non_matching_indent(cx: &mut TestAppContext) {
16461    let (buffer_id, mut cx) = setup_indent_guides_editor(
16462        &"
16463    def m:
16464        a = 1
16465        pass"
16466            .unindent(),
16467        cx,
16468    )
16469    .await;
16470
16471    cx.update_editor(|editor, window, cx| {
16472        editor.change_selections(None, window, cx, |s| {
16473            s.select_ranges([Point::new(1, 0)..Point::new(1, 0)])
16474        });
16475    });
16476
16477    assert_indent_guides(
16478        0..3,
16479        vec![indent_guide(buffer_id, 1, 2, 0)],
16480        Some(vec![0]),
16481        &mut cx,
16482    );
16483}
16484
16485#[gpui::test]
16486async fn test_indent_guide_with_expanded_diff_hunks(cx: &mut TestAppContext) {
16487    init_test(cx, |_| {});
16488    let mut cx = EditorTestContext::new(cx).await;
16489    let text = indoc! {
16490        "
16491        impl A {
16492            fn b() {
16493                0;
16494                3;
16495                5;
16496                6;
16497                7;
16498            }
16499        }
16500        "
16501    };
16502    let base_text = indoc! {
16503        "
16504        impl A {
16505            fn b() {
16506                0;
16507                1;
16508                2;
16509                3;
16510                4;
16511            }
16512            fn c() {
16513                5;
16514                6;
16515                7;
16516            }
16517        }
16518        "
16519    };
16520
16521    cx.update_editor(|editor, window, cx| {
16522        editor.set_text(text, window, cx);
16523
16524        editor.buffer().update(cx, |multibuffer, cx| {
16525            let buffer = multibuffer.as_singleton().unwrap();
16526            let diff = cx.new(|cx| BufferDiff::new_with_base_text(base_text, &buffer, cx));
16527
16528            multibuffer.set_all_diff_hunks_expanded(cx);
16529            multibuffer.add_diff(diff, cx);
16530
16531            buffer.read(cx).remote_id()
16532        })
16533    });
16534    cx.run_until_parked();
16535
16536    cx.assert_state_with_diff(
16537        indoc! { "
16538          impl A {
16539              fn b() {
16540                  0;
16541        -         1;
16542        -         2;
16543                  3;
16544        -         4;
16545        -     }
16546        -     fn c() {
16547                  5;
16548                  6;
16549                  7;
16550              }
16551          }
16552          ˇ"
16553        }
16554        .to_string(),
16555    );
16556
16557    let mut actual_guides = cx.update_editor(|editor, window, cx| {
16558        editor
16559            .snapshot(window, cx)
16560            .buffer_snapshot
16561            .indent_guides_in_range(Anchor::min()..Anchor::max(), false, cx)
16562            .map(|guide| (guide.start_row..=guide.end_row, guide.depth))
16563            .collect::<Vec<_>>()
16564    });
16565    actual_guides.sort_by_key(|item| (*item.0.start(), item.1));
16566    assert_eq!(
16567        actual_guides,
16568        vec![
16569            (MultiBufferRow(1)..=MultiBufferRow(12), 0),
16570            (MultiBufferRow(2)..=MultiBufferRow(6), 1),
16571            (MultiBufferRow(9)..=MultiBufferRow(11), 1),
16572        ]
16573    );
16574}
16575
16576#[gpui::test]
16577async fn test_adjacent_diff_hunks(executor: BackgroundExecutor, cx: &mut TestAppContext) {
16578    init_test(cx, |_| {});
16579    let mut cx = EditorTestContext::new(cx).await;
16580
16581    let diff_base = r#"
16582        a
16583        b
16584        c
16585        "#
16586    .unindent();
16587
16588    cx.set_state(
16589        &r#"
16590        ˇA
16591        b
16592        C
16593        "#
16594        .unindent(),
16595    );
16596    cx.set_head_text(&diff_base);
16597    cx.update_editor(|editor, window, cx| {
16598        editor.expand_all_diff_hunks(&ExpandAllDiffHunks, window, cx);
16599    });
16600    executor.run_until_parked();
16601
16602    let both_hunks_expanded = r#"
16603        - a
16604        + ˇA
16605          b
16606        - c
16607        + C
16608        "#
16609    .unindent();
16610
16611    cx.assert_state_with_diff(both_hunks_expanded.clone());
16612
16613    let hunk_ranges = cx.update_editor(|editor, window, cx| {
16614        let snapshot = editor.snapshot(window, cx);
16615        let hunks = editor
16616            .diff_hunks_in_ranges(&[Anchor::min()..Anchor::max()], &snapshot.buffer_snapshot)
16617            .collect::<Vec<_>>();
16618        let excerpt_id = editor.buffer.read(cx).excerpt_ids()[0];
16619        let buffer_id = hunks[0].buffer_id;
16620        hunks
16621            .into_iter()
16622            .map(|hunk| Anchor::range_in_buffer(excerpt_id, buffer_id, hunk.buffer_range.clone()))
16623            .collect::<Vec<_>>()
16624    });
16625    assert_eq!(hunk_ranges.len(), 2);
16626
16627    cx.update_editor(|editor, _, cx| {
16628        editor.toggle_single_diff_hunk(hunk_ranges[0].clone(), cx);
16629    });
16630    executor.run_until_parked();
16631
16632    let second_hunk_expanded = r#"
16633          ˇA
16634          b
16635        - c
16636        + C
16637        "#
16638    .unindent();
16639
16640    cx.assert_state_with_diff(second_hunk_expanded);
16641
16642    cx.update_editor(|editor, _, cx| {
16643        editor.toggle_single_diff_hunk(hunk_ranges[0].clone(), cx);
16644    });
16645    executor.run_until_parked();
16646
16647    cx.assert_state_with_diff(both_hunks_expanded.clone());
16648
16649    cx.update_editor(|editor, _, cx| {
16650        editor.toggle_single_diff_hunk(hunk_ranges[1].clone(), cx);
16651    });
16652    executor.run_until_parked();
16653
16654    let first_hunk_expanded = r#"
16655        - a
16656        + ˇA
16657          b
16658          C
16659        "#
16660    .unindent();
16661
16662    cx.assert_state_with_diff(first_hunk_expanded);
16663
16664    cx.update_editor(|editor, _, cx| {
16665        editor.toggle_single_diff_hunk(hunk_ranges[1].clone(), cx);
16666    });
16667    executor.run_until_parked();
16668
16669    cx.assert_state_with_diff(both_hunks_expanded);
16670
16671    cx.set_state(
16672        &r#"
16673        ˇA
16674        b
16675        "#
16676        .unindent(),
16677    );
16678    cx.run_until_parked();
16679
16680    // TODO this cursor position seems bad
16681    cx.assert_state_with_diff(
16682        r#"
16683        - ˇa
16684        + A
16685          b
16686        "#
16687        .unindent(),
16688    );
16689
16690    cx.update_editor(|editor, window, cx| {
16691        editor.expand_all_diff_hunks(&ExpandAllDiffHunks, window, cx);
16692    });
16693
16694    cx.assert_state_with_diff(
16695        r#"
16696            - ˇa
16697            + A
16698              b
16699            - c
16700            "#
16701        .unindent(),
16702    );
16703
16704    let hunk_ranges = cx.update_editor(|editor, window, cx| {
16705        let snapshot = editor.snapshot(window, cx);
16706        let hunks = editor
16707            .diff_hunks_in_ranges(&[Anchor::min()..Anchor::max()], &snapshot.buffer_snapshot)
16708            .collect::<Vec<_>>();
16709        let excerpt_id = editor.buffer.read(cx).excerpt_ids()[0];
16710        let buffer_id = hunks[0].buffer_id;
16711        hunks
16712            .into_iter()
16713            .map(|hunk| Anchor::range_in_buffer(excerpt_id, buffer_id, hunk.buffer_range.clone()))
16714            .collect::<Vec<_>>()
16715    });
16716    assert_eq!(hunk_ranges.len(), 2);
16717
16718    cx.update_editor(|editor, _, cx| {
16719        editor.toggle_single_diff_hunk(hunk_ranges[1].clone(), cx);
16720    });
16721    executor.run_until_parked();
16722
16723    cx.assert_state_with_diff(
16724        r#"
16725        - ˇa
16726        + A
16727          b
16728        "#
16729        .unindent(),
16730    );
16731}
16732
16733#[gpui::test]
16734async fn test_toggle_deletion_hunk_at_start_of_file(
16735    executor: BackgroundExecutor,
16736    cx: &mut TestAppContext,
16737) {
16738    init_test(cx, |_| {});
16739    let mut cx = EditorTestContext::new(cx).await;
16740
16741    let diff_base = r#"
16742        a
16743        b
16744        c
16745        "#
16746    .unindent();
16747
16748    cx.set_state(
16749        &r#"
16750        ˇb
16751        c
16752        "#
16753        .unindent(),
16754    );
16755    cx.set_head_text(&diff_base);
16756    cx.update_editor(|editor, window, cx| {
16757        editor.expand_all_diff_hunks(&ExpandAllDiffHunks, window, cx);
16758    });
16759    executor.run_until_parked();
16760
16761    let hunk_expanded = r#"
16762        - a
16763          ˇb
16764          c
16765        "#
16766    .unindent();
16767
16768    cx.assert_state_with_diff(hunk_expanded.clone());
16769
16770    let hunk_ranges = cx.update_editor(|editor, window, cx| {
16771        let snapshot = editor.snapshot(window, cx);
16772        let hunks = editor
16773            .diff_hunks_in_ranges(&[Anchor::min()..Anchor::max()], &snapshot.buffer_snapshot)
16774            .collect::<Vec<_>>();
16775        let excerpt_id = editor.buffer.read(cx).excerpt_ids()[0];
16776        let buffer_id = hunks[0].buffer_id;
16777        hunks
16778            .into_iter()
16779            .map(|hunk| Anchor::range_in_buffer(excerpt_id, buffer_id, hunk.buffer_range.clone()))
16780            .collect::<Vec<_>>()
16781    });
16782    assert_eq!(hunk_ranges.len(), 1);
16783
16784    cx.update_editor(|editor, _, cx| {
16785        editor.toggle_single_diff_hunk(hunk_ranges[0].clone(), cx);
16786    });
16787    executor.run_until_parked();
16788
16789    let hunk_collapsed = r#"
16790          ˇb
16791          c
16792        "#
16793    .unindent();
16794
16795    cx.assert_state_with_diff(hunk_collapsed);
16796
16797    cx.update_editor(|editor, _, cx| {
16798        editor.toggle_single_diff_hunk(hunk_ranges[0].clone(), cx);
16799    });
16800    executor.run_until_parked();
16801
16802    cx.assert_state_with_diff(hunk_expanded.clone());
16803}
16804
16805#[gpui::test]
16806async fn test_display_diff_hunks(cx: &mut TestAppContext) {
16807    init_test(cx, |_| {});
16808
16809    let fs = FakeFs::new(cx.executor());
16810    fs.insert_tree(
16811        path!("/test"),
16812        json!({
16813            ".git": {},
16814            "file-1": "ONE\n",
16815            "file-2": "TWO\n",
16816            "file-3": "THREE\n",
16817        }),
16818    )
16819    .await;
16820
16821    fs.set_head_for_repo(
16822        path!("/test/.git").as_ref(),
16823        &[
16824            ("file-1".into(), "one\n".into()),
16825            ("file-2".into(), "two\n".into()),
16826            ("file-3".into(), "three\n".into()),
16827        ],
16828    );
16829
16830    let project = Project::test(fs, [path!("/test").as_ref()], cx).await;
16831    let mut buffers = vec![];
16832    for i in 1..=3 {
16833        let buffer = project
16834            .update(cx, |project, cx| {
16835                let path = format!(path!("/test/file-{}"), i);
16836                project.open_local_buffer(path, cx)
16837            })
16838            .await
16839            .unwrap();
16840        buffers.push(buffer);
16841    }
16842
16843    let multibuffer = cx.new(|cx| {
16844        let mut multibuffer = MultiBuffer::new(Capability::ReadWrite);
16845        multibuffer.set_all_diff_hunks_expanded(cx);
16846        for buffer in &buffers {
16847            let snapshot = buffer.read(cx).snapshot();
16848            multibuffer.set_excerpts_for_path(
16849                PathKey::namespaced(0, buffer.read(cx).file().unwrap().path().clone()),
16850                buffer.clone(),
16851                vec![text::Anchor::MIN.to_point(&snapshot)..text::Anchor::MAX.to_point(&snapshot)],
16852                DEFAULT_MULTIBUFFER_CONTEXT,
16853                cx,
16854            );
16855        }
16856        multibuffer
16857    });
16858
16859    let editor = cx.add_window(|window, cx| {
16860        Editor::new(EditorMode::full(), multibuffer, Some(project), window, cx)
16861    });
16862    cx.run_until_parked();
16863
16864    let snapshot = editor
16865        .update(cx, |editor, window, cx| editor.snapshot(window, cx))
16866        .unwrap();
16867    let hunks = snapshot
16868        .display_diff_hunks_for_rows(DisplayRow(0)..DisplayRow(u32::MAX), &Default::default())
16869        .map(|hunk| match hunk {
16870            DisplayDiffHunk::Unfolded {
16871                display_row_range, ..
16872            } => display_row_range,
16873            DisplayDiffHunk::Folded { .. } => unreachable!(),
16874        })
16875        .collect::<Vec<_>>();
16876    assert_eq!(
16877        hunks,
16878        [
16879            DisplayRow(2)..DisplayRow(4),
16880            DisplayRow(7)..DisplayRow(9),
16881            DisplayRow(12)..DisplayRow(14),
16882        ]
16883    );
16884}
16885
16886#[gpui::test]
16887async fn test_partially_staged_hunk(cx: &mut TestAppContext) {
16888    init_test(cx, |_| {});
16889
16890    let mut cx = EditorTestContext::new(cx).await;
16891    cx.set_head_text(indoc! { "
16892        one
16893        two
16894        three
16895        four
16896        five
16897        "
16898    });
16899    cx.set_index_text(indoc! { "
16900        one
16901        two
16902        three
16903        four
16904        five
16905        "
16906    });
16907    cx.set_state(indoc! {"
16908        one
16909        TWO
16910        ˇTHREE
16911        FOUR
16912        five
16913    "});
16914    cx.run_until_parked();
16915    cx.update_editor(|editor, window, cx| {
16916        editor.toggle_staged_selected_diff_hunks(&Default::default(), window, cx);
16917    });
16918    cx.run_until_parked();
16919    cx.assert_index_text(Some(indoc! {"
16920        one
16921        TWO
16922        THREE
16923        FOUR
16924        five
16925    "}));
16926    cx.set_state(indoc! { "
16927        one
16928        TWO
16929        ˇTHREE-HUNDRED
16930        FOUR
16931        five
16932    "});
16933    cx.run_until_parked();
16934    cx.update_editor(|editor, window, cx| {
16935        let snapshot = editor.snapshot(window, cx);
16936        let hunks = editor
16937            .diff_hunks_in_ranges(&[Anchor::min()..Anchor::max()], &snapshot.buffer_snapshot)
16938            .collect::<Vec<_>>();
16939        assert_eq!(hunks.len(), 1);
16940        assert_eq!(
16941            hunks[0].status(),
16942            DiffHunkStatus {
16943                kind: DiffHunkStatusKind::Modified,
16944                secondary: DiffHunkSecondaryStatus::OverlapsWithSecondaryHunk
16945            }
16946        );
16947
16948        editor.toggle_staged_selected_diff_hunks(&Default::default(), window, cx);
16949    });
16950    cx.run_until_parked();
16951    cx.assert_index_text(Some(indoc! {"
16952        one
16953        TWO
16954        THREE-HUNDRED
16955        FOUR
16956        five
16957    "}));
16958}
16959
16960#[gpui::test]
16961fn test_crease_insertion_and_rendering(cx: &mut TestAppContext) {
16962    init_test(cx, |_| {});
16963
16964    let editor = cx.add_window(|window, cx| {
16965        let buffer = MultiBuffer::build_simple("aaaaaa\nbbbbbb\ncccccc\nddddddd\n", cx);
16966        build_editor(buffer, window, cx)
16967    });
16968
16969    let render_args = Arc::new(Mutex::new(None));
16970    let snapshot = editor
16971        .update(cx, |editor, window, cx| {
16972            let snapshot = editor.buffer().read(cx).snapshot(cx);
16973            let range =
16974                snapshot.anchor_before(Point::new(1, 0))..snapshot.anchor_after(Point::new(2, 6));
16975
16976            struct RenderArgs {
16977                row: MultiBufferRow,
16978                folded: bool,
16979                callback: Arc<dyn Fn(bool, &mut Window, &mut App) + Send + Sync>,
16980            }
16981
16982            let crease = Crease::inline(
16983                range,
16984                FoldPlaceholder::test(),
16985                {
16986                    let toggle_callback = render_args.clone();
16987                    move |row, folded, callback, _window, _cx| {
16988                        *toggle_callback.lock() = Some(RenderArgs {
16989                            row,
16990                            folded,
16991                            callback,
16992                        });
16993                        div()
16994                    }
16995                },
16996                |_row, _folded, _window, _cx| div(),
16997            );
16998
16999            editor.insert_creases(Some(crease), cx);
17000            let snapshot = editor.snapshot(window, cx);
17001            let _div = snapshot.render_crease_toggle(
17002                MultiBufferRow(1),
17003                false,
17004                cx.entity().clone(),
17005                window,
17006                cx,
17007            );
17008            snapshot
17009        })
17010        .unwrap();
17011
17012    let render_args = render_args.lock().take().unwrap();
17013    assert_eq!(render_args.row, MultiBufferRow(1));
17014    assert!(!render_args.folded);
17015    assert!(!snapshot.is_line_folded(MultiBufferRow(1)));
17016
17017    cx.update_window(*editor, |_, window, cx| {
17018        (render_args.callback)(true, window, cx)
17019    })
17020    .unwrap();
17021    let snapshot = editor
17022        .update(cx, |editor, window, cx| editor.snapshot(window, cx))
17023        .unwrap();
17024    assert!(snapshot.is_line_folded(MultiBufferRow(1)));
17025
17026    cx.update_window(*editor, |_, window, cx| {
17027        (render_args.callback)(false, window, cx)
17028    })
17029    .unwrap();
17030    let snapshot = editor
17031        .update(cx, |editor, window, cx| editor.snapshot(window, cx))
17032        .unwrap();
17033    assert!(!snapshot.is_line_folded(MultiBufferRow(1)));
17034}
17035
17036#[gpui::test]
17037async fn test_input_text(cx: &mut TestAppContext) {
17038    init_test(cx, |_| {});
17039    let mut cx = EditorTestContext::new(cx).await;
17040
17041    cx.set_state(
17042        &r#"ˇone
17043        two
17044
17045        three
17046        fourˇ
17047        five
17048
17049        siˇx"#
17050            .unindent(),
17051    );
17052
17053    cx.dispatch_action(HandleInput(String::new()));
17054    cx.assert_editor_state(
17055        &r#"ˇone
17056        two
17057
17058        three
17059        fourˇ
17060        five
17061
17062        siˇx"#
17063            .unindent(),
17064    );
17065
17066    cx.dispatch_action(HandleInput("AAAA".to_string()));
17067    cx.assert_editor_state(
17068        &r#"AAAAˇone
17069        two
17070
17071        three
17072        fourAAAAˇ
17073        five
17074
17075        siAAAAˇx"#
17076            .unindent(),
17077    );
17078}
17079
17080#[gpui::test]
17081async fn test_scroll_cursor_center_top_bottom(cx: &mut TestAppContext) {
17082    init_test(cx, |_| {});
17083
17084    let mut cx = EditorTestContext::new(cx).await;
17085    cx.set_state(
17086        r#"let foo = 1;
17087let foo = 2;
17088let foo = 3;
17089let fooˇ = 4;
17090let foo = 5;
17091let foo = 6;
17092let foo = 7;
17093let foo = 8;
17094let foo = 9;
17095let foo = 10;
17096let foo = 11;
17097let foo = 12;
17098let foo = 13;
17099let foo = 14;
17100let foo = 15;"#,
17101    );
17102
17103    cx.update_editor(|e, window, cx| {
17104        assert_eq!(
17105            e.next_scroll_position,
17106            NextScrollCursorCenterTopBottom::Center,
17107            "Default next scroll direction is center",
17108        );
17109
17110        e.scroll_cursor_center_top_bottom(&ScrollCursorCenterTopBottom, window, cx);
17111        assert_eq!(
17112            e.next_scroll_position,
17113            NextScrollCursorCenterTopBottom::Top,
17114            "After center, next scroll direction should be top",
17115        );
17116
17117        e.scroll_cursor_center_top_bottom(&ScrollCursorCenterTopBottom, window, cx);
17118        assert_eq!(
17119            e.next_scroll_position,
17120            NextScrollCursorCenterTopBottom::Bottom,
17121            "After top, next scroll direction should be bottom",
17122        );
17123
17124        e.scroll_cursor_center_top_bottom(&ScrollCursorCenterTopBottom, window, cx);
17125        assert_eq!(
17126            e.next_scroll_position,
17127            NextScrollCursorCenterTopBottom::Center,
17128            "After bottom, scrolling should start over",
17129        );
17130
17131        e.scroll_cursor_center_top_bottom(&ScrollCursorCenterTopBottom, window, cx);
17132        assert_eq!(
17133            e.next_scroll_position,
17134            NextScrollCursorCenterTopBottom::Top,
17135            "Scrolling continues if retriggered fast enough"
17136        );
17137    });
17138
17139    cx.executor()
17140        .advance_clock(SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT + Duration::from_millis(200));
17141    cx.executor().run_until_parked();
17142    cx.update_editor(|e, _, _| {
17143        assert_eq!(
17144            e.next_scroll_position,
17145            NextScrollCursorCenterTopBottom::Center,
17146            "If scrolling is not triggered fast enough, it should reset"
17147        );
17148    });
17149}
17150
17151#[gpui::test]
17152async fn test_goto_definition_with_find_all_references_fallback(cx: &mut TestAppContext) {
17153    init_test(cx, |_| {});
17154    let mut cx = EditorLspTestContext::new_rust(
17155        lsp::ServerCapabilities {
17156            definition_provider: Some(lsp::OneOf::Left(true)),
17157            references_provider: Some(lsp::OneOf::Left(true)),
17158            ..lsp::ServerCapabilities::default()
17159        },
17160        cx,
17161    )
17162    .await;
17163
17164    let set_up_lsp_handlers = |empty_go_to_definition: bool, cx: &mut EditorLspTestContext| {
17165        let go_to_definition = cx
17166            .lsp
17167            .set_request_handler::<lsp::request::GotoDefinition, _, _>(
17168                move |params, _| async move {
17169                    if empty_go_to_definition {
17170                        Ok(None)
17171                    } else {
17172                        Ok(Some(lsp::GotoDefinitionResponse::Scalar(lsp::Location {
17173                            uri: params.text_document_position_params.text_document.uri,
17174                            range: lsp::Range::new(
17175                                lsp::Position::new(4, 3),
17176                                lsp::Position::new(4, 6),
17177                            ),
17178                        })))
17179                    }
17180                },
17181            );
17182        let references = cx
17183            .lsp
17184            .set_request_handler::<lsp::request::References, _, _>(move |params, _| async move {
17185                Ok(Some(vec![lsp::Location {
17186                    uri: params.text_document_position.text_document.uri,
17187                    range: lsp::Range::new(lsp::Position::new(0, 8), lsp::Position::new(0, 11)),
17188                }]))
17189            });
17190        (go_to_definition, references)
17191    };
17192
17193    cx.set_state(
17194        &r#"fn one() {
17195            let mut a = ˇtwo();
17196        }
17197
17198        fn two() {}"#
17199            .unindent(),
17200    );
17201    set_up_lsp_handlers(false, &mut cx);
17202    let navigated = cx
17203        .update_editor(|editor, window, cx| editor.go_to_definition(&GoToDefinition, window, cx))
17204        .await
17205        .expect("Failed to navigate to definition");
17206    assert_eq!(
17207        navigated,
17208        Navigated::Yes,
17209        "Should have navigated to definition from the GetDefinition response"
17210    );
17211    cx.assert_editor_state(
17212        &r#"fn one() {
17213            let mut a = two();
17214        }
17215
17216        fn «twoˇ»() {}"#
17217            .unindent(),
17218    );
17219
17220    let editors = cx.update_workspace(|workspace, _, cx| {
17221        workspace.items_of_type::<Editor>(cx).collect::<Vec<_>>()
17222    });
17223    cx.update_editor(|_, _, test_editor_cx| {
17224        assert_eq!(
17225            editors.len(),
17226            1,
17227            "Initially, only one, test, editor should be open in the workspace"
17228        );
17229        assert_eq!(
17230            test_editor_cx.entity(),
17231            editors.last().expect("Asserted len is 1").clone()
17232        );
17233    });
17234
17235    set_up_lsp_handlers(true, &mut cx);
17236    let navigated = cx
17237        .update_editor(|editor, window, cx| editor.go_to_definition(&GoToDefinition, window, cx))
17238        .await
17239        .expect("Failed to navigate to lookup references");
17240    assert_eq!(
17241        navigated,
17242        Navigated::Yes,
17243        "Should have navigated to references as a fallback after empty GoToDefinition response"
17244    );
17245    // We should not change the selections in the existing file,
17246    // if opening another milti buffer with the references
17247    cx.assert_editor_state(
17248        &r#"fn one() {
17249            let mut a = two();
17250        }
17251
17252        fn «twoˇ»() {}"#
17253            .unindent(),
17254    );
17255    let editors = cx.update_workspace(|workspace, _, cx| {
17256        workspace.items_of_type::<Editor>(cx).collect::<Vec<_>>()
17257    });
17258    cx.update_editor(|_, _, test_editor_cx| {
17259        assert_eq!(
17260            editors.len(),
17261            2,
17262            "After falling back to references search, we open a new editor with the results"
17263        );
17264        let references_fallback_text = editors
17265            .into_iter()
17266            .find(|new_editor| *new_editor != test_editor_cx.entity())
17267            .expect("Should have one non-test editor now")
17268            .read(test_editor_cx)
17269            .text(test_editor_cx);
17270        assert_eq!(
17271            references_fallback_text, "fn one() {\n    let mut a = two();\n}",
17272            "Should use the range from the references response and not the GoToDefinition one"
17273        );
17274    });
17275}
17276
17277#[gpui::test]
17278async fn test_goto_definition_no_fallback(cx: &mut TestAppContext) {
17279    init_test(cx, |_| {});
17280    cx.update(|cx| {
17281        let mut editor_settings = EditorSettings::get_global(cx).clone();
17282        editor_settings.go_to_definition_fallback = GoToDefinitionFallback::None;
17283        EditorSettings::override_global(editor_settings, cx);
17284    });
17285    let mut cx = EditorLspTestContext::new_rust(
17286        lsp::ServerCapabilities {
17287            definition_provider: Some(lsp::OneOf::Left(true)),
17288            references_provider: Some(lsp::OneOf::Left(true)),
17289            ..lsp::ServerCapabilities::default()
17290        },
17291        cx,
17292    )
17293    .await;
17294    let original_state = r#"fn one() {
17295        let mut a = ˇtwo();
17296    }
17297
17298    fn two() {}"#
17299        .unindent();
17300    cx.set_state(&original_state);
17301
17302    let mut go_to_definition = cx
17303        .lsp
17304        .set_request_handler::<lsp::request::GotoDefinition, _, _>(
17305            move |_, _| async move { Ok(None) },
17306        );
17307    let _references = cx
17308        .lsp
17309        .set_request_handler::<lsp::request::References, _, _>(move |_, _| async move {
17310            panic!("Should not call for references with no go to definition fallback")
17311        });
17312
17313    let navigated = cx
17314        .update_editor(|editor, window, cx| editor.go_to_definition(&GoToDefinition, window, cx))
17315        .await
17316        .expect("Failed to navigate to lookup references");
17317    go_to_definition
17318        .next()
17319        .await
17320        .expect("Should have called the go_to_definition handler");
17321
17322    assert_eq!(
17323        navigated,
17324        Navigated::No,
17325        "Should have navigated to references as a fallback after empty GoToDefinition response"
17326    );
17327    cx.assert_editor_state(&original_state);
17328    let editors = cx.update_workspace(|workspace, _, cx| {
17329        workspace.items_of_type::<Editor>(cx).collect::<Vec<_>>()
17330    });
17331    cx.update_editor(|_, _, _| {
17332        assert_eq!(
17333            editors.len(),
17334            1,
17335            "After unsuccessful fallback, no other editor should have been opened"
17336        );
17337    });
17338}
17339
17340#[gpui::test]
17341async fn test_find_enclosing_node_with_task(cx: &mut TestAppContext) {
17342    init_test(cx, |_| {});
17343
17344    let language = Arc::new(Language::new(
17345        LanguageConfig::default(),
17346        Some(tree_sitter_rust::LANGUAGE.into()),
17347    ));
17348
17349    let text = r#"
17350        #[cfg(test)]
17351        mod tests() {
17352            #[test]
17353            fn runnable_1() {
17354                let a = 1;
17355            }
17356
17357            #[test]
17358            fn runnable_2() {
17359                let a = 1;
17360                let b = 2;
17361            }
17362        }
17363    "#
17364    .unindent();
17365
17366    let fs = FakeFs::new(cx.executor());
17367    fs.insert_file("/file.rs", Default::default()).await;
17368
17369    let project = Project::test(fs, ["/a".as_ref()], cx).await;
17370    let workspace = cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
17371    let cx = &mut VisualTestContext::from_window(*workspace.deref(), cx);
17372    let buffer = cx.new(|cx| Buffer::local(text, cx).with_language(language, cx));
17373    let multi_buffer = cx.new(|cx| MultiBuffer::singleton(buffer.clone(), cx));
17374
17375    let editor = cx.new_window_entity(|window, cx| {
17376        Editor::new(
17377            EditorMode::full(),
17378            multi_buffer,
17379            Some(project.clone()),
17380            window,
17381            cx,
17382        )
17383    });
17384
17385    editor.update_in(cx, |editor, window, cx| {
17386        let snapshot = editor.buffer().read(cx).snapshot(cx);
17387        editor.tasks.insert(
17388            (buffer.read(cx).remote_id(), 3),
17389            RunnableTasks {
17390                templates: vec![],
17391                offset: snapshot.anchor_before(43),
17392                column: 0,
17393                extra_variables: HashMap::default(),
17394                context_range: BufferOffset(43)..BufferOffset(85),
17395            },
17396        );
17397        editor.tasks.insert(
17398            (buffer.read(cx).remote_id(), 8),
17399            RunnableTasks {
17400                templates: vec![],
17401                offset: snapshot.anchor_before(86),
17402                column: 0,
17403                extra_variables: HashMap::default(),
17404                context_range: BufferOffset(86)..BufferOffset(191),
17405            },
17406        );
17407
17408        // Test finding task when cursor is inside function body
17409        editor.change_selections(None, window, cx, |s| {
17410            s.select_ranges([Point::new(4, 5)..Point::new(4, 5)])
17411        });
17412        let (_, row, _) = editor.find_enclosing_node_task(cx).unwrap();
17413        assert_eq!(row, 3, "Should find task for cursor inside runnable_1");
17414
17415        // Test finding task when cursor is on function name
17416        editor.change_selections(None, window, cx, |s| {
17417            s.select_ranges([Point::new(8, 4)..Point::new(8, 4)])
17418        });
17419        let (_, row, _) = editor.find_enclosing_node_task(cx).unwrap();
17420        assert_eq!(row, 8, "Should find task when cursor is on function name");
17421    });
17422}
17423
17424#[gpui::test]
17425async fn test_folding_buffers(cx: &mut TestAppContext) {
17426    init_test(cx, |_| {});
17427
17428    let sample_text_1 = "aaaa\nbbbb\ncccc\ndddd\neeee\nffff\ngggg\nhhhh\niiii\njjjj".to_string();
17429    let sample_text_2 = "llll\nmmmm\nnnnn\noooo\npppp\nqqqq\nrrrr\nssss\ntttt\nuuuu".to_string();
17430    let sample_text_3 = "vvvv\nwwww\nxxxx\nyyyy\nzzzz\n1111\n2222\n3333\n4444\n5555".to_string();
17431
17432    let fs = FakeFs::new(cx.executor());
17433    fs.insert_tree(
17434        path!("/a"),
17435        json!({
17436            "first.rs": sample_text_1,
17437            "second.rs": sample_text_2,
17438            "third.rs": sample_text_3,
17439        }),
17440    )
17441    .await;
17442    let project = Project::test(fs, [path!("/a").as_ref()], cx).await;
17443    let workspace = cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
17444    let cx = &mut VisualTestContext::from_window(*workspace.deref(), cx);
17445    let worktree = project.update(cx, |project, cx| {
17446        let mut worktrees = project.worktrees(cx).collect::<Vec<_>>();
17447        assert_eq!(worktrees.len(), 1);
17448        worktrees.pop().unwrap()
17449    });
17450    let worktree_id = worktree.update(cx, |worktree, _| worktree.id());
17451
17452    let buffer_1 = project
17453        .update(cx, |project, cx| {
17454            project.open_buffer((worktree_id, "first.rs"), cx)
17455        })
17456        .await
17457        .unwrap();
17458    let buffer_2 = project
17459        .update(cx, |project, cx| {
17460            project.open_buffer((worktree_id, "second.rs"), cx)
17461        })
17462        .await
17463        .unwrap();
17464    let buffer_3 = project
17465        .update(cx, |project, cx| {
17466            project.open_buffer((worktree_id, "third.rs"), cx)
17467        })
17468        .await
17469        .unwrap();
17470
17471    let multi_buffer = cx.new(|cx| {
17472        let mut multi_buffer = MultiBuffer::new(ReadWrite);
17473        multi_buffer.push_excerpts(
17474            buffer_1.clone(),
17475            [
17476                ExcerptRange::new(Point::new(0, 0)..Point::new(3, 0)),
17477                ExcerptRange::new(Point::new(5, 0)..Point::new(7, 0)),
17478                ExcerptRange::new(Point::new(9, 0)..Point::new(10, 4)),
17479            ],
17480            cx,
17481        );
17482        multi_buffer.push_excerpts(
17483            buffer_2.clone(),
17484            [
17485                ExcerptRange::new(Point::new(0, 0)..Point::new(3, 0)),
17486                ExcerptRange::new(Point::new(5, 0)..Point::new(7, 0)),
17487                ExcerptRange::new(Point::new(9, 0)..Point::new(10, 4)),
17488            ],
17489            cx,
17490        );
17491        multi_buffer.push_excerpts(
17492            buffer_3.clone(),
17493            [
17494                ExcerptRange::new(Point::new(0, 0)..Point::new(3, 0)),
17495                ExcerptRange::new(Point::new(5, 0)..Point::new(7, 0)),
17496                ExcerptRange::new(Point::new(9, 0)..Point::new(10, 4)),
17497            ],
17498            cx,
17499        );
17500        multi_buffer
17501    });
17502    let multi_buffer_editor = cx.new_window_entity(|window, cx| {
17503        Editor::new(
17504            EditorMode::full(),
17505            multi_buffer.clone(),
17506            Some(project.clone()),
17507            window,
17508            cx,
17509        )
17510    });
17511
17512    assert_eq!(
17513        multi_buffer_editor.update(cx, |editor, cx| editor.display_text(cx)),
17514        "\n\naaaa\nbbbb\ncccc\n\n\nffff\ngggg\n\n\njjjj\n\n\nllll\nmmmm\nnnnn\n\n\nqqqq\nrrrr\n\n\nuuuu\n\n\nvvvv\nwwww\nxxxx\n\n\n1111\n2222\n\n\n5555",
17515    );
17516
17517    multi_buffer_editor.update(cx, |editor, cx| {
17518        editor.fold_buffer(buffer_1.read(cx).remote_id(), cx)
17519    });
17520    assert_eq!(
17521        multi_buffer_editor.update(cx, |editor, cx| editor.display_text(cx)),
17522        "\n\n\n\nllll\nmmmm\nnnnn\n\n\nqqqq\nrrrr\n\n\nuuuu\n\n\nvvvv\nwwww\nxxxx\n\n\n1111\n2222\n\n\n5555",
17523        "After folding the first buffer, its text should not be displayed"
17524    );
17525
17526    multi_buffer_editor.update(cx, |editor, cx| {
17527        editor.fold_buffer(buffer_2.read(cx).remote_id(), cx)
17528    });
17529    assert_eq!(
17530        multi_buffer_editor.update(cx, |editor, cx| editor.display_text(cx)),
17531        "\n\n\n\n\n\nvvvv\nwwww\nxxxx\n\n\n1111\n2222\n\n\n5555",
17532        "After folding the second buffer, its text should not be displayed"
17533    );
17534
17535    multi_buffer_editor.update(cx, |editor, cx| {
17536        editor.fold_buffer(buffer_3.read(cx).remote_id(), cx)
17537    });
17538    assert_eq!(
17539        multi_buffer_editor.update(cx, |editor, cx| editor.display_text(cx)),
17540        "\n\n\n\n\n",
17541        "After folding the third buffer, its text should not be displayed"
17542    );
17543
17544    // Emulate selection inside the fold logic, that should work
17545    multi_buffer_editor.update_in(cx, |editor, window, cx| {
17546        editor
17547            .snapshot(window, cx)
17548            .next_line_boundary(Point::new(0, 4));
17549    });
17550
17551    multi_buffer_editor.update(cx, |editor, cx| {
17552        editor.unfold_buffer(buffer_2.read(cx).remote_id(), cx)
17553    });
17554    assert_eq!(
17555        multi_buffer_editor.update(cx, |editor, cx| editor.display_text(cx)),
17556        "\n\n\n\nllll\nmmmm\nnnnn\n\n\nqqqq\nrrrr\n\n\nuuuu\n\n",
17557        "After unfolding the second buffer, its text should be displayed"
17558    );
17559
17560    // Typing inside of buffer 1 causes that buffer to be unfolded.
17561    multi_buffer_editor.update_in(cx, |editor, window, cx| {
17562        assert_eq!(
17563            multi_buffer
17564                .read(cx)
17565                .snapshot(cx)
17566                .text_for_range(Point::new(1, 0)..Point::new(1, 4))
17567                .collect::<String>(),
17568            "bbbb"
17569        );
17570        editor.change_selections(None, window, cx, |selections| {
17571            selections.select_ranges(vec![Point::new(1, 0)..Point::new(1, 0)]);
17572        });
17573        editor.handle_input("B", window, cx);
17574    });
17575
17576    assert_eq!(
17577        multi_buffer_editor.update(cx, |editor, cx| editor.display_text(cx)),
17578        "\n\nB\n\n\n\n\n\n\nllll\nmmmm\nnnnn\n\n\nqqqq\nrrrr\n\n\nuuuu\n\n",
17579        "After unfolding the first buffer, its and 2nd buffer's text should be displayed"
17580    );
17581
17582    multi_buffer_editor.update(cx, |editor, cx| {
17583        editor.unfold_buffer(buffer_3.read(cx).remote_id(), cx)
17584    });
17585    assert_eq!(
17586        multi_buffer_editor.update(cx, |editor, cx| editor.display_text(cx)),
17587        "\n\nB\n\n\n\n\n\n\nllll\nmmmm\nnnnn\n\n\nqqqq\nrrrr\n\n\nuuuu\n\n\nvvvv\nwwww\nxxxx\n\n\n1111\n2222\n\n\n5555",
17588        "After unfolding the all buffers, all original text should be displayed"
17589    );
17590}
17591
17592#[gpui::test]
17593async fn test_folding_buffers_with_one_excerpt(cx: &mut TestAppContext) {
17594    init_test(cx, |_| {});
17595
17596    let sample_text_1 = "1111\n2222\n3333".to_string();
17597    let sample_text_2 = "4444\n5555\n6666".to_string();
17598    let sample_text_3 = "7777\n8888\n9999".to_string();
17599
17600    let fs = FakeFs::new(cx.executor());
17601    fs.insert_tree(
17602        path!("/a"),
17603        json!({
17604            "first.rs": sample_text_1,
17605            "second.rs": sample_text_2,
17606            "third.rs": sample_text_3,
17607        }),
17608    )
17609    .await;
17610    let project = Project::test(fs, [path!("/a").as_ref()], cx).await;
17611    let workspace = cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
17612    let cx = &mut VisualTestContext::from_window(*workspace.deref(), cx);
17613    let worktree = project.update(cx, |project, cx| {
17614        let mut worktrees = project.worktrees(cx).collect::<Vec<_>>();
17615        assert_eq!(worktrees.len(), 1);
17616        worktrees.pop().unwrap()
17617    });
17618    let worktree_id = worktree.update(cx, |worktree, _| worktree.id());
17619
17620    let buffer_1 = project
17621        .update(cx, |project, cx| {
17622            project.open_buffer((worktree_id, "first.rs"), cx)
17623        })
17624        .await
17625        .unwrap();
17626    let buffer_2 = project
17627        .update(cx, |project, cx| {
17628            project.open_buffer((worktree_id, "second.rs"), cx)
17629        })
17630        .await
17631        .unwrap();
17632    let buffer_3 = project
17633        .update(cx, |project, cx| {
17634            project.open_buffer((worktree_id, "third.rs"), cx)
17635        })
17636        .await
17637        .unwrap();
17638
17639    let multi_buffer = cx.new(|cx| {
17640        let mut multi_buffer = MultiBuffer::new(ReadWrite);
17641        multi_buffer.push_excerpts(
17642            buffer_1.clone(),
17643            [ExcerptRange::new(Point::new(0, 0)..Point::new(3, 0))],
17644            cx,
17645        );
17646        multi_buffer.push_excerpts(
17647            buffer_2.clone(),
17648            [ExcerptRange::new(Point::new(0, 0)..Point::new(3, 0))],
17649            cx,
17650        );
17651        multi_buffer.push_excerpts(
17652            buffer_3.clone(),
17653            [ExcerptRange::new(Point::new(0, 0)..Point::new(3, 0))],
17654            cx,
17655        );
17656        multi_buffer
17657    });
17658
17659    let multi_buffer_editor = cx.new_window_entity(|window, cx| {
17660        Editor::new(
17661            EditorMode::full(),
17662            multi_buffer,
17663            Some(project.clone()),
17664            window,
17665            cx,
17666        )
17667    });
17668
17669    let full_text = "\n\n1111\n2222\n3333\n\n\n4444\n5555\n6666\n\n\n7777\n8888\n9999";
17670    assert_eq!(
17671        multi_buffer_editor.update(cx, |editor, cx| editor.display_text(cx)),
17672        full_text,
17673    );
17674
17675    multi_buffer_editor.update(cx, |editor, cx| {
17676        editor.fold_buffer(buffer_1.read(cx).remote_id(), cx)
17677    });
17678    assert_eq!(
17679        multi_buffer_editor.update(cx, |editor, cx| editor.display_text(cx)),
17680        "\n\n\n\n4444\n5555\n6666\n\n\n7777\n8888\n9999",
17681        "After folding the first buffer, its text should not be displayed"
17682    );
17683
17684    multi_buffer_editor.update(cx, |editor, cx| {
17685        editor.fold_buffer(buffer_2.read(cx).remote_id(), cx)
17686    });
17687
17688    assert_eq!(
17689        multi_buffer_editor.update(cx, |editor, cx| editor.display_text(cx)),
17690        "\n\n\n\n\n\n7777\n8888\n9999",
17691        "After folding the second buffer, its text should not be displayed"
17692    );
17693
17694    multi_buffer_editor.update(cx, |editor, cx| {
17695        editor.fold_buffer(buffer_3.read(cx).remote_id(), cx)
17696    });
17697    assert_eq!(
17698        multi_buffer_editor.update(cx, |editor, cx| editor.display_text(cx)),
17699        "\n\n\n\n\n",
17700        "After folding the third buffer, its text should not be displayed"
17701    );
17702
17703    multi_buffer_editor.update(cx, |editor, cx| {
17704        editor.unfold_buffer(buffer_2.read(cx).remote_id(), cx)
17705    });
17706    assert_eq!(
17707        multi_buffer_editor.update(cx, |editor, cx| editor.display_text(cx)),
17708        "\n\n\n\n4444\n5555\n6666\n\n",
17709        "After unfolding the second buffer, its text should be displayed"
17710    );
17711
17712    multi_buffer_editor.update(cx, |editor, cx| {
17713        editor.unfold_buffer(buffer_1.read(cx).remote_id(), cx)
17714    });
17715    assert_eq!(
17716        multi_buffer_editor.update(cx, |editor, cx| editor.display_text(cx)),
17717        "\n\n1111\n2222\n3333\n\n\n4444\n5555\n6666\n\n",
17718        "After unfolding the first buffer, its text should be displayed"
17719    );
17720
17721    multi_buffer_editor.update(cx, |editor, cx| {
17722        editor.unfold_buffer(buffer_3.read(cx).remote_id(), cx)
17723    });
17724    assert_eq!(
17725        multi_buffer_editor.update(cx, |editor, cx| editor.display_text(cx)),
17726        full_text,
17727        "After unfolding all buffers, all original text should be displayed"
17728    );
17729}
17730
17731#[gpui::test]
17732async fn test_folding_buffer_when_multibuffer_has_only_one_excerpt(cx: &mut TestAppContext) {
17733    init_test(cx, |_| {});
17734
17735    let sample_text = "aaaa\nbbbb\ncccc\ndddd\neeee\nffff\ngggg\nhhhh\niiii\njjjj".to_string();
17736
17737    let fs = FakeFs::new(cx.executor());
17738    fs.insert_tree(
17739        path!("/a"),
17740        json!({
17741            "main.rs": sample_text,
17742        }),
17743    )
17744    .await;
17745    let project = Project::test(fs, [path!("/a").as_ref()], cx).await;
17746    let workspace = cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
17747    let cx = &mut VisualTestContext::from_window(*workspace.deref(), cx);
17748    let worktree = project.update(cx, |project, cx| {
17749        let mut worktrees = project.worktrees(cx).collect::<Vec<_>>();
17750        assert_eq!(worktrees.len(), 1);
17751        worktrees.pop().unwrap()
17752    });
17753    let worktree_id = worktree.update(cx, |worktree, _| worktree.id());
17754
17755    let buffer_1 = project
17756        .update(cx, |project, cx| {
17757            project.open_buffer((worktree_id, "main.rs"), cx)
17758        })
17759        .await
17760        .unwrap();
17761
17762    let multi_buffer = cx.new(|cx| {
17763        let mut multi_buffer = MultiBuffer::new(ReadWrite);
17764        multi_buffer.push_excerpts(
17765            buffer_1.clone(),
17766            [ExcerptRange::new(
17767                Point::new(0, 0)
17768                    ..Point::new(
17769                        sample_text.chars().filter(|&c| c == '\n').count() as u32 + 1,
17770                        0,
17771                    ),
17772            )],
17773            cx,
17774        );
17775        multi_buffer
17776    });
17777    let multi_buffer_editor = cx.new_window_entity(|window, cx| {
17778        Editor::new(
17779            EditorMode::full(),
17780            multi_buffer,
17781            Some(project.clone()),
17782            window,
17783            cx,
17784        )
17785    });
17786
17787    let selection_range = Point::new(1, 0)..Point::new(2, 0);
17788    multi_buffer_editor.update_in(cx, |editor, window, cx| {
17789        enum TestHighlight {}
17790        let multi_buffer_snapshot = editor.buffer().read(cx).snapshot(cx);
17791        let highlight_range = selection_range.clone().to_anchors(&multi_buffer_snapshot);
17792        editor.highlight_text::<TestHighlight>(
17793            vec![highlight_range.clone()],
17794            HighlightStyle::color(Hsla::green()),
17795            cx,
17796        );
17797        editor.change_selections(None, window, cx, |s| s.select_ranges(Some(highlight_range)));
17798    });
17799
17800    let full_text = format!("\n\n{sample_text}");
17801    assert_eq!(
17802        multi_buffer_editor.update(cx, |editor, cx| editor.display_text(cx)),
17803        full_text,
17804    );
17805}
17806
17807#[gpui::test]
17808async fn test_multi_buffer_navigation_with_folded_buffers(cx: &mut TestAppContext) {
17809    init_test(cx, |_| {});
17810    cx.update(|cx| {
17811        let default_key_bindings = settings::KeymapFile::load_asset_allow_partial_failure(
17812            "keymaps/default-linux.json",
17813            cx,
17814        )
17815        .unwrap();
17816        cx.bind_keys(default_key_bindings);
17817    });
17818
17819    let (editor, cx) = cx.add_window_view(|window, cx| {
17820        let multi_buffer = MultiBuffer::build_multi(
17821            [
17822                ("a0\nb0\nc0\nd0\ne0\n", vec![Point::row_range(0..2)]),
17823                ("a1\nb1\nc1\nd1\ne1\n", vec![Point::row_range(0..2)]),
17824                ("a2\nb2\nc2\nd2\ne2\n", vec![Point::row_range(0..2)]),
17825                ("a3\nb3\nc3\nd3\ne3\n", vec![Point::row_range(0..2)]),
17826            ],
17827            cx,
17828        );
17829        let mut editor = Editor::new(EditorMode::full(), multi_buffer.clone(), None, window, cx);
17830
17831        let buffer_ids = multi_buffer.read(cx).excerpt_buffer_ids();
17832        // fold all but the second buffer, so that we test navigating between two
17833        // adjacent folded buffers, as well as folded buffers at the start and
17834        // end the multibuffer
17835        editor.fold_buffer(buffer_ids[0], cx);
17836        editor.fold_buffer(buffer_ids[2], cx);
17837        editor.fold_buffer(buffer_ids[3], cx);
17838
17839        editor
17840    });
17841    cx.simulate_resize(size(px(1000.), px(1000.)));
17842
17843    let mut cx = EditorTestContext::for_editor_in(editor.clone(), cx).await;
17844    cx.assert_excerpts_with_selections(indoc! {"
17845        [EXCERPT]
17846        ˇ[FOLDED]
17847        [EXCERPT]
17848        a1
17849        b1
17850        [EXCERPT]
17851        [FOLDED]
17852        [EXCERPT]
17853        [FOLDED]
17854        "
17855    });
17856    cx.simulate_keystroke("down");
17857    cx.assert_excerpts_with_selections(indoc! {"
17858        [EXCERPT]
17859        [FOLDED]
17860        [EXCERPT]
17861        ˇa1
17862        b1
17863        [EXCERPT]
17864        [FOLDED]
17865        [EXCERPT]
17866        [FOLDED]
17867        "
17868    });
17869    cx.simulate_keystroke("down");
17870    cx.assert_excerpts_with_selections(indoc! {"
17871        [EXCERPT]
17872        [FOLDED]
17873        [EXCERPT]
17874        a1
17875        ˇb1
17876        [EXCERPT]
17877        [FOLDED]
17878        [EXCERPT]
17879        [FOLDED]
17880        "
17881    });
17882    cx.simulate_keystroke("down");
17883    cx.assert_excerpts_with_selections(indoc! {"
17884        [EXCERPT]
17885        [FOLDED]
17886        [EXCERPT]
17887        a1
17888        b1
17889        ˇ[EXCERPT]
17890        [FOLDED]
17891        [EXCERPT]
17892        [FOLDED]
17893        "
17894    });
17895    cx.simulate_keystroke("down");
17896    cx.assert_excerpts_with_selections(indoc! {"
17897        [EXCERPT]
17898        [FOLDED]
17899        [EXCERPT]
17900        a1
17901        b1
17902        [EXCERPT]
17903        ˇ[FOLDED]
17904        [EXCERPT]
17905        [FOLDED]
17906        "
17907    });
17908    for _ in 0..5 {
17909        cx.simulate_keystroke("down");
17910        cx.assert_excerpts_with_selections(indoc! {"
17911            [EXCERPT]
17912            [FOLDED]
17913            [EXCERPT]
17914            a1
17915            b1
17916            [EXCERPT]
17917            [FOLDED]
17918            [EXCERPT]
17919            ˇ[FOLDED]
17920            "
17921        });
17922    }
17923
17924    cx.simulate_keystroke("up");
17925    cx.assert_excerpts_with_selections(indoc! {"
17926        [EXCERPT]
17927        [FOLDED]
17928        [EXCERPT]
17929        a1
17930        b1
17931        [EXCERPT]
17932        ˇ[FOLDED]
17933        [EXCERPT]
17934        [FOLDED]
17935        "
17936    });
17937    cx.simulate_keystroke("up");
17938    cx.assert_excerpts_with_selections(indoc! {"
17939        [EXCERPT]
17940        [FOLDED]
17941        [EXCERPT]
17942        a1
17943        b1
17944        ˇ[EXCERPT]
17945        [FOLDED]
17946        [EXCERPT]
17947        [FOLDED]
17948        "
17949    });
17950    cx.simulate_keystroke("up");
17951    cx.assert_excerpts_with_selections(indoc! {"
17952        [EXCERPT]
17953        [FOLDED]
17954        [EXCERPT]
17955        a1
17956        ˇb1
17957        [EXCERPT]
17958        [FOLDED]
17959        [EXCERPT]
17960        [FOLDED]
17961        "
17962    });
17963    cx.simulate_keystroke("up");
17964    cx.assert_excerpts_with_selections(indoc! {"
17965        [EXCERPT]
17966        [FOLDED]
17967        [EXCERPT]
17968        ˇa1
17969        b1
17970        [EXCERPT]
17971        [FOLDED]
17972        [EXCERPT]
17973        [FOLDED]
17974        "
17975    });
17976    for _ in 0..5 {
17977        cx.simulate_keystroke("up");
17978        cx.assert_excerpts_with_selections(indoc! {"
17979            [EXCERPT]
17980            ˇ[FOLDED]
17981            [EXCERPT]
17982            a1
17983            b1
17984            [EXCERPT]
17985            [FOLDED]
17986            [EXCERPT]
17987            [FOLDED]
17988            "
17989        });
17990    }
17991}
17992
17993#[gpui::test]
17994async fn test_inline_completion_text(cx: &mut TestAppContext) {
17995    init_test(cx, |_| {});
17996
17997    // Simple insertion
17998    assert_highlighted_edits(
17999        "Hello, world!",
18000        vec![(Point::new(0, 6)..Point::new(0, 6), " beautiful".into())],
18001        true,
18002        cx,
18003        |highlighted_edits, cx| {
18004            assert_eq!(highlighted_edits.text, "Hello, beautiful world!");
18005            assert_eq!(highlighted_edits.highlights.len(), 1);
18006            assert_eq!(highlighted_edits.highlights[0].0, 6..16);
18007            assert_eq!(
18008                highlighted_edits.highlights[0].1.background_color,
18009                Some(cx.theme().status().created_background)
18010            );
18011        },
18012    )
18013    .await;
18014
18015    // Replacement
18016    assert_highlighted_edits(
18017        "This is a test.",
18018        vec![(Point::new(0, 0)..Point::new(0, 4), "That".into())],
18019        false,
18020        cx,
18021        |highlighted_edits, cx| {
18022            assert_eq!(highlighted_edits.text, "That is a test.");
18023            assert_eq!(highlighted_edits.highlights.len(), 1);
18024            assert_eq!(highlighted_edits.highlights[0].0, 0..4);
18025            assert_eq!(
18026                highlighted_edits.highlights[0].1.background_color,
18027                Some(cx.theme().status().created_background)
18028            );
18029        },
18030    )
18031    .await;
18032
18033    // Multiple edits
18034    assert_highlighted_edits(
18035        "Hello, world!",
18036        vec![
18037            (Point::new(0, 0)..Point::new(0, 5), "Greetings".into()),
18038            (Point::new(0, 12)..Point::new(0, 12), " and universe".into()),
18039        ],
18040        false,
18041        cx,
18042        |highlighted_edits, cx| {
18043            assert_eq!(highlighted_edits.text, "Greetings, world and universe!");
18044            assert_eq!(highlighted_edits.highlights.len(), 2);
18045            assert_eq!(highlighted_edits.highlights[0].0, 0..9);
18046            assert_eq!(highlighted_edits.highlights[1].0, 16..29);
18047            assert_eq!(
18048                highlighted_edits.highlights[0].1.background_color,
18049                Some(cx.theme().status().created_background)
18050            );
18051            assert_eq!(
18052                highlighted_edits.highlights[1].1.background_color,
18053                Some(cx.theme().status().created_background)
18054            );
18055        },
18056    )
18057    .await;
18058
18059    // Multiple lines with edits
18060    assert_highlighted_edits(
18061        "First line\nSecond line\nThird line\nFourth line",
18062        vec![
18063            (Point::new(1, 7)..Point::new(1, 11), "modified".to_string()),
18064            (
18065                Point::new(2, 0)..Point::new(2, 10),
18066                "New third line".to_string(),
18067            ),
18068            (Point::new(3, 6)..Point::new(3, 6), " updated".to_string()),
18069        ],
18070        false,
18071        cx,
18072        |highlighted_edits, cx| {
18073            assert_eq!(
18074                highlighted_edits.text,
18075                "Second modified\nNew third line\nFourth updated line"
18076            );
18077            assert_eq!(highlighted_edits.highlights.len(), 3);
18078            assert_eq!(highlighted_edits.highlights[0].0, 7..15); // "modified"
18079            assert_eq!(highlighted_edits.highlights[1].0, 16..30); // "New third line"
18080            assert_eq!(highlighted_edits.highlights[2].0, 37..45); // " updated"
18081            for highlight in &highlighted_edits.highlights {
18082                assert_eq!(
18083                    highlight.1.background_color,
18084                    Some(cx.theme().status().created_background)
18085                );
18086            }
18087        },
18088    )
18089    .await;
18090}
18091
18092#[gpui::test]
18093async fn test_inline_completion_text_with_deletions(cx: &mut TestAppContext) {
18094    init_test(cx, |_| {});
18095
18096    // Deletion
18097    assert_highlighted_edits(
18098        "Hello, world!",
18099        vec![(Point::new(0, 5)..Point::new(0, 11), "".to_string())],
18100        true,
18101        cx,
18102        |highlighted_edits, cx| {
18103            assert_eq!(highlighted_edits.text, "Hello, world!");
18104            assert_eq!(highlighted_edits.highlights.len(), 1);
18105            assert_eq!(highlighted_edits.highlights[0].0, 5..11);
18106            assert_eq!(
18107                highlighted_edits.highlights[0].1.background_color,
18108                Some(cx.theme().status().deleted_background)
18109            );
18110        },
18111    )
18112    .await;
18113
18114    // Insertion
18115    assert_highlighted_edits(
18116        "Hello, world!",
18117        vec![(Point::new(0, 6)..Point::new(0, 6), " digital".to_string())],
18118        true,
18119        cx,
18120        |highlighted_edits, cx| {
18121            assert_eq!(highlighted_edits.highlights.len(), 1);
18122            assert_eq!(highlighted_edits.highlights[0].0, 6..14);
18123            assert_eq!(
18124                highlighted_edits.highlights[0].1.background_color,
18125                Some(cx.theme().status().created_background)
18126            );
18127        },
18128    )
18129    .await;
18130}
18131
18132async fn assert_highlighted_edits(
18133    text: &str,
18134    edits: Vec<(Range<Point>, String)>,
18135    include_deletions: bool,
18136    cx: &mut TestAppContext,
18137    assertion_fn: impl Fn(HighlightedText, &App),
18138) {
18139    let window = cx.add_window(|window, cx| {
18140        let buffer = MultiBuffer::build_simple(text, cx);
18141        Editor::new(EditorMode::full(), buffer, None, window, cx)
18142    });
18143    let cx = &mut VisualTestContext::from_window(*window, cx);
18144
18145    let (buffer, snapshot) = window
18146        .update(cx, |editor, _window, cx| {
18147            (
18148                editor.buffer().clone(),
18149                editor.buffer().read(cx).snapshot(cx),
18150            )
18151        })
18152        .unwrap();
18153
18154    let edits = edits
18155        .into_iter()
18156        .map(|(range, edit)| {
18157            (
18158                snapshot.anchor_after(range.start)..snapshot.anchor_before(range.end),
18159                edit,
18160            )
18161        })
18162        .collect::<Vec<_>>();
18163
18164    let text_anchor_edits = edits
18165        .clone()
18166        .into_iter()
18167        .map(|(range, edit)| (range.start.text_anchor..range.end.text_anchor, edit))
18168        .collect::<Vec<_>>();
18169
18170    let edit_preview = window
18171        .update(cx, |_, _window, cx| {
18172            buffer
18173                .read(cx)
18174                .as_singleton()
18175                .unwrap()
18176                .read(cx)
18177                .preview_edits(text_anchor_edits.into(), cx)
18178        })
18179        .unwrap()
18180        .await;
18181
18182    cx.update(|_window, cx| {
18183        let highlighted_edits = inline_completion_edit_text(
18184            &snapshot.as_singleton().unwrap().2,
18185            &edits,
18186            &edit_preview,
18187            include_deletions,
18188            cx,
18189        );
18190        assertion_fn(highlighted_edits, cx)
18191    });
18192}
18193
18194#[track_caller]
18195fn assert_breakpoint(
18196    breakpoints: &BTreeMap<Arc<Path>, Vec<SourceBreakpoint>>,
18197    path: &Arc<Path>,
18198    expected: Vec<(u32, Breakpoint)>,
18199) {
18200    if expected.len() == 0usize {
18201        assert!(!breakpoints.contains_key(path), "{}", path.display());
18202    } else {
18203        let mut breakpoint = breakpoints
18204            .get(path)
18205            .unwrap()
18206            .into_iter()
18207            .map(|breakpoint| {
18208                (
18209                    breakpoint.row,
18210                    Breakpoint {
18211                        message: breakpoint.message.clone(),
18212                        state: breakpoint.state,
18213                        condition: breakpoint.condition.clone(),
18214                        hit_condition: breakpoint.hit_condition.clone(),
18215                    },
18216                )
18217            })
18218            .collect::<Vec<_>>();
18219
18220        breakpoint.sort_by_key(|(cached_position, _)| *cached_position);
18221
18222        assert_eq!(expected, breakpoint);
18223    }
18224}
18225
18226fn add_log_breakpoint_at_cursor(
18227    editor: &mut Editor,
18228    log_message: &str,
18229    window: &mut Window,
18230    cx: &mut Context<Editor>,
18231) {
18232    let (anchor, bp) = editor
18233        .breakpoints_at_cursors(window, cx)
18234        .first()
18235        .and_then(|(anchor, bp)| {
18236            if let Some(bp) = bp {
18237                Some((*anchor, bp.clone()))
18238            } else {
18239                None
18240            }
18241        })
18242        .unwrap_or_else(|| {
18243            let cursor_position: Point = editor.selections.newest(cx).head();
18244
18245            let breakpoint_position = editor
18246                .snapshot(window, cx)
18247                .display_snapshot
18248                .buffer_snapshot
18249                .anchor_before(Point::new(cursor_position.row, 0));
18250
18251            (breakpoint_position, Breakpoint::new_log(&log_message))
18252        });
18253
18254    editor.edit_breakpoint_at_anchor(
18255        anchor,
18256        bp,
18257        BreakpointEditAction::EditLogMessage(log_message.into()),
18258        cx,
18259    );
18260}
18261
18262#[gpui::test]
18263async fn test_breakpoint_toggling(cx: &mut TestAppContext) {
18264    init_test(cx, |_| {});
18265
18266    let sample_text = "First line\nSecond line\nThird line\nFourth line".to_string();
18267    let fs = FakeFs::new(cx.executor());
18268    fs.insert_tree(
18269        path!("/a"),
18270        json!({
18271            "main.rs": sample_text,
18272        }),
18273    )
18274    .await;
18275    let project = Project::test(fs, [path!("/a").as_ref()], cx).await;
18276    let workspace = cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
18277    let cx = &mut VisualTestContext::from_window(*workspace.deref(), cx);
18278
18279    let fs = FakeFs::new(cx.executor());
18280    fs.insert_tree(
18281        path!("/a"),
18282        json!({
18283            "main.rs": sample_text,
18284        }),
18285    )
18286    .await;
18287    let project = Project::test(fs, [path!("/a").as_ref()], cx).await;
18288    let workspace = cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
18289    let cx = &mut VisualTestContext::from_window(*workspace.deref(), cx);
18290    let worktree_id = workspace
18291        .update(cx, |workspace, _window, cx| {
18292            workspace.project().update(cx, |project, cx| {
18293                project.worktrees(cx).next().unwrap().read(cx).id()
18294            })
18295        })
18296        .unwrap();
18297
18298    let buffer = project
18299        .update(cx, |project, cx| {
18300            project.open_buffer((worktree_id, "main.rs"), cx)
18301        })
18302        .await
18303        .unwrap();
18304
18305    let (editor, cx) = cx.add_window_view(|window, cx| {
18306        Editor::new(
18307            EditorMode::full(),
18308            MultiBuffer::build_from_buffer(buffer, cx),
18309            Some(project.clone()),
18310            window,
18311            cx,
18312        )
18313    });
18314
18315    let project_path = editor.update(cx, |editor, cx| editor.project_path(cx).unwrap());
18316    let abs_path = project.read_with(cx, |project, cx| {
18317        project
18318            .absolute_path(&project_path, cx)
18319            .map(|path_buf| Arc::from(path_buf.to_owned()))
18320            .unwrap()
18321    });
18322
18323    // assert we can add breakpoint on the first line
18324    editor.update_in(cx, |editor, window, cx| {
18325        editor.toggle_breakpoint(&actions::ToggleBreakpoint, window, cx);
18326        editor.move_to_end(&MoveToEnd, window, cx);
18327        editor.toggle_breakpoint(&actions::ToggleBreakpoint, window, cx);
18328    });
18329
18330    let breakpoints = editor.update(cx, |editor, cx| {
18331        editor
18332            .breakpoint_store()
18333            .as_ref()
18334            .unwrap()
18335            .read(cx)
18336            .all_breakpoints(cx)
18337            .clone()
18338    });
18339
18340    assert_eq!(1, breakpoints.len());
18341    assert_breakpoint(
18342        &breakpoints,
18343        &abs_path,
18344        vec![
18345            (0, Breakpoint::new_standard()),
18346            (3, Breakpoint::new_standard()),
18347        ],
18348    );
18349
18350    editor.update_in(cx, |editor, window, cx| {
18351        editor.move_to_beginning(&MoveToBeginning, window, cx);
18352        editor.toggle_breakpoint(&actions::ToggleBreakpoint, window, cx);
18353    });
18354
18355    let breakpoints = editor.update(cx, |editor, cx| {
18356        editor
18357            .breakpoint_store()
18358            .as_ref()
18359            .unwrap()
18360            .read(cx)
18361            .all_breakpoints(cx)
18362            .clone()
18363    });
18364
18365    assert_eq!(1, breakpoints.len());
18366    assert_breakpoint(
18367        &breakpoints,
18368        &abs_path,
18369        vec![(3, Breakpoint::new_standard())],
18370    );
18371
18372    editor.update_in(cx, |editor, window, cx| {
18373        editor.move_to_end(&MoveToEnd, window, cx);
18374        editor.toggle_breakpoint(&actions::ToggleBreakpoint, window, cx);
18375    });
18376
18377    let breakpoints = editor.update(cx, |editor, cx| {
18378        editor
18379            .breakpoint_store()
18380            .as_ref()
18381            .unwrap()
18382            .read(cx)
18383            .all_breakpoints(cx)
18384            .clone()
18385    });
18386
18387    assert_eq!(0, breakpoints.len());
18388    assert_breakpoint(&breakpoints, &abs_path, vec![]);
18389}
18390
18391#[gpui::test]
18392async fn test_log_breakpoint_editing(cx: &mut TestAppContext) {
18393    init_test(cx, |_| {});
18394
18395    let sample_text = "First line\nSecond line\nThird line\nFourth line".to_string();
18396
18397    let fs = FakeFs::new(cx.executor());
18398    fs.insert_tree(
18399        path!("/a"),
18400        json!({
18401            "main.rs": sample_text,
18402        }),
18403    )
18404    .await;
18405    let project = Project::test(fs, [path!("/a").as_ref()], cx).await;
18406    let (workspace, cx) =
18407        cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
18408
18409    let worktree_id = workspace.update(cx, |workspace, cx| {
18410        workspace.project().update(cx, |project, cx| {
18411            project.worktrees(cx).next().unwrap().read(cx).id()
18412        })
18413    });
18414
18415    let buffer = project
18416        .update(cx, |project, cx| {
18417            project.open_buffer((worktree_id, "main.rs"), cx)
18418        })
18419        .await
18420        .unwrap();
18421
18422    let (editor, cx) = cx.add_window_view(|window, cx| {
18423        Editor::new(
18424            EditorMode::full(),
18425            MultiBuffer::build_from_buffer(buffer, cx),
18426            Some(project.clone()),
18427            window,
18428            cx,
18429        )
18430    });
18431
18432    let project_path = editor.update(cx, |editor, cx| editor.project_path(cx).unwrap());
18433    let abs_path = project.read_with(cx, |project, cx| {
18434        project
18435            .absolute_path(&project_path, cx)
18436            .map(|path_buf| Arc::from(path_buf.to_owned()))
18437            .unwrap()
18438    });
18439
18440    editor.update_in(cx, |editor, window, cx| {
18441        add_log_breakpoint_at_cursor(editor, "hello world", window, cx);
18442    });
18443
18444    let breakpoints = editor.update(cx, |editor, cx| {
18445        editor
18446            .breakpoint_store()
18447            .as_ref()
18448            .unwrap()
18449            .read(cx)
18450            .all_breakpoints(cx)
18451            .clone()
18452    });
18453
18454    assert_breakpoint(
18455        &breakpoints,
18456        &abs_path,
18457        vec![(0, Breakpoint::new_log("hello world"))],
18458    );
18459
18460    // Removing a log message from a log breakpoint should remove it
18461    editor.update_in(cx, |editor, window, cx| {
18462        add_log_breakpoint_at_cursor(editor, "", window, cx);
18463    });
18464
18465    let breakpoints = editor.update(cx, |editor, cx| {
18466        editor
18467            .breakpoint_store()
18468            .as_ref()
18469            .unwrap()
18470            .read(cx)
18471            .all_breakpoints(cx)
18472            .clone()
18473    });
18474
18475    assert_breakpoint(&breakpoints, &abs_path, vec![]);
18476
18477    editor.update_in(cx, |editor, window, cx| {
18478        editor.toggle_breakpoint(&actions::ToggleBreakpoint, window, cx);
18479        editor.move_to_end(&MoveToEnd, window, cx);
18480        editor.toggle_breakpoint(&actions::ToggleBreakpoint, window, cx);
18481        // Not adding a log message to a standard breakpoint shouldn't remove it
18482        add_log_breakpoint_at_cursor(editor, "", window, cx);
18483    });
18484
18485    let breakpoints = editor.update(cx, |editor, cx| {
18486        editor
18487            .breakpoint_store()
18488            .as_ref()
18489            .unwrap()
18490            .read(cx)
18491            .all_breakpoints(cx)
18492            .clone()
18493    });
18494
18495    assert_breakpoint(
18496        &breakpoints,
18497        &abs_path,
18498        vec![
18499            (0, Breakpoint::new_standard()),
18500            (3, Breakpoint::new_standard()),
18501        ],
18502    );
18503
18504    editor.update_in(cx, |editor, window, cx| {
18505        add_log_breakpoint_at_cursor(editor, "hello world", window, cx);
18506    });
18507
18508    let breakpoints = editor.update(cx, |editor, cx| {
18509        editor
18510            .breakpoint_store()
18511            .as_ref()
18512            .unwrap()
18513            .read(cx)
18514            .all_breakpoints(cx)
18515            .clone()
18516    });
18517
18518    assert_breakpoint(
18519        &breakpoints,
18520        &abs_path,
18521        vec![
18522            (0, Breakpoint::new_standard()),
18523            (3, Breakpoint::new_log("hello world")),
18524        ],
18525    );
18526
18527    editor.update_in(cx, |editor, window, cx| {
18528        add_log_breakpoint_at_cursor(editor, "hello Earth!!", window, cx);
18529    });
18530
18531    let breakpoints = editor.update(cx, |editor, cx| {
18532        editor
18533            .breakpoint_store()
18534            .as_ref()
18535            .unwrap()
18536            .read(cx)
18537            .all_breakpoints(cx)
18538            .clone()
18539    });
18540
18541    assert_breakpoint(
18542        &breakpoints,
18543        &abs_path,
18544        vec![
18545            (0, Breakpoint::new_standard()),
18546            (3, Breakpoint::new_log("hello Earth!!")),
18547        ],
18548    );
18549}
18550
18551/// This also tests that Editor::breakpoint_at_cursor_head is working properly
18552/// we had some issues where we wouldn't find a breakpoint at Point {row: 0, col: 0}
18553/// or when breakpoints were placed out of order. This tests for a regression too
18554#[gpui::test]
18555async fn test_breakpoint_enabling_and_disabling(cx: &mut TestAppContext) {
18556    init_test(cx, |_| {});
18557
18558    let sample_text = "First line\nSecond line\nThird line\nFourth line".to_string();
18559    let fs = FakeFs::new(cx.executor());
18560    fs.insert_tree(
18561        path!("/a"),
18562        json!({
18563            "main.rs": sample_text,
18564        }),
18565    )
18566    .await;
18567    let project = Project::test(fs, [path!("/a").as_ref()], cx).await;
18568    let workspace = cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
18569    let cx = &mut VisualTestContext::from_window(*workspace.deref(), cx);
18570
18571    let fs = FakeFs::new(cx.executor());
18572    fs.insert_tree(
18573        path!("/a"),
18574        json!({
18575            "main.rs": sample_text,
18576        }),
18577    )
18578    .await;
18579    let project = Project::test(fs, [path!("/a").as_ref()], cx).await;
18580    let workspace = cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
18581    let cx = &mut VisualTestContext::from_window(*workspace.deref(), cx);
18582    let worktree_id = workspace
18583        .update(cx, |workspace, _window, cx| {
18584            workspace.project().update(cx, |project, cx| {
18585                project.worktrees(cx).next().unwrap().read(cx).id()
18586            })
18587        })
18588        .unwrap();
18589
18590    let buffer = project
18591        .update(cx, |project, cx| {
18592            project.open_buffer((worktree_id, "main.rs"), cx)
18593        })
18594        .await
18595        .unwrap();
18596
18597    let (editor, cx) = cx.add_window_view(|window, cx| {
18598        Editor::new(
18599            EditorMode::full(),
18600            MultiBuffer::build_from_buffer(buffer, cx),
18601            Some(project.clone()),
18602            window,
18603            cx,
18604        )
18605    });
18606
18607    let project_path = editor.update(cx, |editor, cx| editor.project_path(cx).unwrap());
18608    let abs_path = project.read_with(cx, |project, cx| {
18609        project
18610            .absolute_path(&project_path, cx)
18611            .map(|path_buf| Arc::from(path_buf.to_owned()))
18612            .unwrap()
18613    });
18614
18615    // assert we can add breakpoint on the first line
18616    editor.update_in(cx, |editor, window, cx| {
18617        editor.toggle_breakpoint(&actions::ToggleBreakpoint, window, cx);
18618        editor.move_to_end(&MoveToEnd, window, cx);
18619        editor.toggle_breakpoint(&actions::ToggleBreakpoint, window, cx);
18620        editor.move_up(&MoveUp, window, cx);
18621        editor.toggle_breakpoint(&actions::ToggleBreakpoint, window, cx);
18622    });
18623
18624    let breakpoints = editor.update(cx, |editor, cx| {
18625        editor
18626            .breakpoint_store()
18627            .as_ref()
18628            .unwrap()
18629            .read(cx)
18630            .all_breakpoints(cx)
18631            .clone()
18632    });
18633
18634    assert_eq!(1, breakpoints.len());
18635    assert_breakpoint(
18636        &breakpoints,
18637        &abs_path,
18638        vec![
18639            (0, Breakpoint::new_standard()),
18640            (2, Breakpoint::new_standard()),
18641            (3, Breakpoint::new_standard()),
18642        ],
18643    );
18644
18645    editor.update_in(cx, |editor, window, cx| {
18646        editor.move_to_beginning(&MoveToBeginning, window, cx);
18647        editor.disable_breakpoint(&actions::DisableBreakpoint, window, cx);
18648        editor.move_to_end(&MoveToEnd, window, cx);
18649        editor.disable_breakpoint(&actions::DisableBreakpoint, window, cx);
18650        // Disabling a breakpoint that doesn't exist should do nothing
18651        editor.move_up(&MoveUp, window, cx);
18652        editor.move_up(&MoveUp, window, cx);
18653        editor.disable_breakpoint(&actions::DisableBreakpoint, window, cx);
18654    });
18655
18656    let breakpoints = editor.update(cx, |editor, cx| {
18657        editor
18658            .breakpoint_store()
18659            .as_ref()
18660            .unwrap()
18661            .read(cx)
18662            .all_breakpoints(cx)
18663            .clone()
18664    });
18665
18666    let disable_breakpoint = {
18667        let mut bp = Breakpoint::new_standard();
18668        bp.state = BreakpointState::Disabled;
18669        bp
18670    };
18671
18672    assert_eq!(1, breakpoints.len());
18673    assert_breakpoint(
18674        &breakpoints,
18675        &abs_path,
18676        vec![
18677            (0, disable_breakpoint.clone()),
18678            (2, Breakpoint::new_standard()),
18679            (3, disable_breakpoint.clone()),
18680        ],
18681    );
18682
18683    editor.update_in(cx, |editor, window, cx| {
18684        editor.move_to_beginning(&MoveToBeginning, window, cx);
18685        editor.enable_breakpoint(&actions::EnableBreakpoint, window, cx);
18686        editor.move_to_end(&MoveToEnd, window, cx);
18687        editor.enable_breakpoint(&actions::EnableBreakpoint, window, cx);
18688        editor.move_up(&MoveUp, window, cx);
18689        editor.disable_breakpoint(&actions::DisableBreakpoint, window, cx);
18690    });
18691
18692    let breakpoints = editor.update(cx, |editor, cx| {
18693        editor
18694            .breakpoint_store()
18695            .as_ref()
18696            .unwrap()
18697            .read(cx)
18698            .all_breakpoints(cx)
18699            .clone()
18700    });
18701
18702    assert_eq!(1, breakpoints.len());
18703    assert_breakpoint(
18704        &breakpoints,
18705        &abs_path,
18706        vec![
18707            (0, Breakpoint::new_standard()),
18708            (2, disable_breakpoint),
18709            (3, Breakpoint::new_standard()),
18710        ],
18711    );
18712}
18713
18714#[gpui::test]
18715async fn test_rename_with_duplicate_edits(cx: &mut TestAppContext) {
18716    init_test(cx, |_| {});
18717    let capabilities = lsp::ServerCapabilities {
18718        rename_provider: Some(lsp::OneOf::Right(lsp::RenameOptions {
18719            prepare_provider: Some(true),
18720            work_done_progress_options: Default::default(),
18721        })),
18722        ..Default::default()
18723    };
18724    let mut cx = EditorLspTestContext::new_rust(capabilities, cx).await;
18725
18726    cx.set_state(indoc! {"
18727        struct Fˇoo {}
18728    "});
18729
18730    cx.update_editor(|editor, _, cx| {
18731        let highlight_range = Point::new(0, 7)..Point::new(0, 10);
18732        let highlight_range = highlight_range.to_anchors(&editor.buffer().read(cx).snapshot(cx));
18733        editor.highlight_background::<DocumentHighlightRead>(
18734            &[highlight_range],
18735            |c| c.editor_document_highlight_read_background,
18736            cx,
18737        );
18738    });
18739
18740    let mut prepare_rename_handler = cx
18741        .set_request_handler::<lsp::request::PrepareRenameRequest, _, _>(
18742            move |_, _, _| async move {
18743                Ok(Some(lsp::PrepareRenameResponse::Range(lsp::Range {
18744                    start: lsp::Position {
18745                        line: 0,
18746                        character: 7,
18747                    },
18748                    end: lsp::Position {
18749                        line: 0,
18750                        character: 10,
18751                    },
18752                })))
18753            },
18754        );
18755    let prepare_rename_task = cx
18756        .update_editor(|e, window, cx| e.rename(&Rename, window, cx))
18757        .expect("Prepare rename was not started");
18758    prepare_rename_handler.next().await.unwrap();
18759    prepare_rename_task.await.expect("Prepare rename failed");
18760
18761    let mut rename_handler =
18762        cx.set_request_handler::<lsp::request::Rename, _, _>(move |url, _, _| async move {
18763            let edit = lsp::TextEdit {
18764                range: lsp::Range {
18765                    start: lsp::Position {
18766                        line: 0,
18767                        character: 7,
18768                    },
18769                    end: lsp::Position {
18770                        line: 0,
18771                        character: 10,
18772                    },
18773                },
18774                new_text: "FooRenamed".to_string(),
18775            };
18776            Ok(Some(lsp::WorkspaceEdit::new(
18777                // Specify the same edit twice
18778                std::collections::HashMap::from_iter(Some((url, vec![edit.clone(), edit]))),
18779            )))
18780        });
18781    let rename_task = cx
18782        .update_editor(|e, window, cx| e.confirm_rename(&ConfirmRename, window, cx))
18783        .expect("Confirm rename was not started");
18784    rename_handler.next().await.unwrap();
18785    rename_task.await.expect("Confirm rename failed");
18786    cx.run_until_parked();
18787
18788    // Despite two edits, only one is actually applied as those are identical
18789    cx.assert_editor_state(indoc! {"
18790        struct FooRenamedˇ {}
18791    "});
18792}
18793
18794#[gpui::test]
18795async fn test_rename_without_prepare(cx: &mut TestAppContext) {
18796    init_test(cx, |_| {});
18797    // These capabilities indicate that the server does not support prepare rename.
18798    let capabilities = lsp::ServerCapabilities {
18799        rename_provider: Some(lsp::OneOf::Left(true)),
18800        ..Default::default()
18801    };
18802    let mut cx = EditorLspTestContext::new_rust(capabilities, cx).await;
18803
18804    cx.set_state(indoc! {"
18805        struct Fˇoo {}
18806    "});
18807
18808    cx.update_editor(|editor, _window, cx| {
18809        let highlight_range = Point::new(0, 7)..Point::new(0, 10);
18810        let highlight_range = highlight_range.to_anchors(&editor.buffer().read(cx).snapshot(cx));
18811        editor.highlight_background::<DocumentHighlightRead>(
18812            &[highlight_range],
18813            |c| c.editor_document_highlight_read_background,
18814            cx,
18815        );
18816    });
18817
18818    cx.update_editor(|e, window, cx| e.rename(&Rename, window, cx))
18819        .expect("Prepare rename was not started")
18820        .await
18821        .expect("Prepare rename failed");
18822
18823    let mut rename_handler =
18824        cx.set_request_handler::<lsp::request::Rename, _, _>(move |url, _, _| async move {
18825            let edit = lsp::TextEdit {
18826                range: lsp::Range {
18827                    start: lsp::Position {
18828                        line: 0,
18829                        character: 7,
18830                    },
18831                    end: lsp::Position {
18832                        line: 0,
18833                        character: 10,
18834                    },
18835                },
18836                new_text: "FooRenamed".to_string(),
18837            };
18838            Ok(Some(lsp::WorkspaceEdit::new(
18839                std::collections::HashMap::from_iter(Some((url, vec![edit]))),
18840            )))
18841        });
18842    let rename_task = cx
18843        .update_editor(|e, window, cx| e.confirm_rename(&ConfirmRename, window, cx))
18844        .expect("Confirm rename was not started");
18845    rename_handler.next().await.unwrap();
18846    rename_task.await.expect("Confirm rename failed");
18847    cx.run_until_parked();
18848
18849    // Correct range is renamed, as `surrounding_word` is used to find it.
18850    cx.assert_editor_state(indoc! {"
18851        struct FooRenamedˇ {}
18852    "});
18853}
18854
18855#[gpui::test]
18856async fn test_tree_sitter_brackets_newline_insertion(cx: &mut TestAppContext) {
18857    init_test(cx, |_| {});
18858    let mut cx = EditorTestContext::new(cx).await;
18859
18860    let language = Arc::new(
18861        Language::new(
18862            LanguageConfig::default(),
18863            Some(tree_sitter_html::LANGUAGE.into()),
18864        )
18865        .with_brackets_query(
18866            r#"
18867            ("<" @open "/>" @close)
18868            ("</" @open ">" @close)
18869            ("<" @open ">" @close)
18870            ("\"" @open "\"" @close)
18871            ((element (start_tag) @open (end_tag) @close) (#set! newline.only))
18872        "#,
18873        )
18874        .unwrap(),
18875    );
18876    cx.update_buffer(|buffer, cx| buffer.set_language(Some(language), cx));
18877
18878    cx.set_state(indoc! {"
18879        <span>ˇ</span>
18880    "});
18881    cx.update_editor(|e, window, cx| e.newline(&Newline, window, cx));
18882    cx.assert_editor_state(indoc! {"
18883        <span>
18884        ˇ
18885        </span>
18886    "});
18887
18888    cx.set_state(indoc! {"
18889        <span><span></span>ˇ</span>
18890    "});
18891    cx.update_editor(|e, window, cx| e.newline(&Newline, window, cx));
18892    cx.assert_editor_state(indoc! {"
18893        <span><span></span>
18894        ˇ</span>
18895    "});
18896
18897    cx.set_state(indoc! {"
18898        <span>ˇ
18899        </span>
18900    "});
18901    cx.update_editor(|e, window, cx| e.newline(&Newline, window, cx));
18902    cx.assert_editor_state(indoc! {"
18903        <span>
18904        ˇ
18905        </span>
18906    "});
18907}
18908
18909#[gpui::test(iterations = 10)]
18910async fn test_apply_code_lens_actions_with_commands(cx: &mut gpui::TestAppContext) {
18911    init_test(cx, |_| {});
18912
18913    let fs = FakeFs::new(cx.executor());
18914    fs.insert_tree(
18915        path!("/dir"),
18916        json!({
18917            "a.ts": "a",
18918        }),
18919    )
18920    .await;
18921
18922    let project = Project::test(fs, [path!("/dir").as_ref()], cx).await;
18923    let workspace = cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
18924    let cx = &mut VisualTestContext::from_window(*workspace.deref(), cx);
18925
18926    let language_registry = project.read_with(cx, |project, _| project.languages().clone());
18927    language_registry.add(Arc::new(Language::new(
18928        LanguageConfig {
18929            name: "TypeScript".into(),
18930            matcher: LanguageMatcher {
18931                path_suffixes: vec!["ts".to_string()],
18932                ..Default::default()
18933            },
18934            ..Default::default()
18935        },
18936        Some(tree_sitter_typescript::LANGUAGE_TYPESCRIPT.into()),
18937    )));
18938    let mut fake_language_servers = language_registry.register_fake_lsp(
18939        "TypeScript",
18940        FakeLspAdapter {
18941            capabilities: lsp::ServerCapabilities {
18942                code_lens_provider: Some(lsp::CodeLensOptions {
18943                    resolve_provider: Some(true),
18944                }),
18945                execute_command_provider: Some(lsp::ExecuteCommandOptions {
18946                    commands: vec!["_the/command".to_string()],
18947                    ..lsp::ExecuteCommandOptions::default()
18948                }),
18949                ..lsp::ServerCapabilities::default()
18950            },
18951            ..FakeLspAdapter::default()
18952        },
18953    );
18954
18955    let (buffer, _handle) = project
18956        .update(cx, |p, cx| {
18957            p.open_local_buffer_with_lsp(path!("/dir/a.ts"), cx)
18958        })
18959        .await
18960        .unwrap();
18961    cx.executor().run_until_parked();
18962
18963    let fake_server = fake_language_servers.next().await.unwrap();
18964
18965    let buffer_snapshot = buffer.update(cx, |buffer, _| buffer.snapshot());
18966    let anchor = buffer_snapshot.anchor_at(0, text::Bias::Left);
18967    drop(buffer_snapshot);
18968    let actions = cx
18969        .update_window(*workspace, |_, window, cx| {
18970            project.code_actions(&buffer, anchor..anchor, window, cx)
18971        })
18972        .unwrap();
18973
18974    fake_server
18975        .set_request_handler::<lsp::request::CodeLensRequest, _, _>(|_, _| async move {
18976            Ok(Some(vec![
18977                lsp::CodeLens {
18978                    range: lsp::Range::default(),
18979                    command: Some(lsp::Command {
18980                        title: "Code lens command".to_owned(),
18981                        command: "_the/command".to_owned(),
18982                        arguments: None,
18983                    }),
18984                    data: None,
18985                },
18986                lsp::CodeLens {
18987                    range: lsp::Range::default(),
18988                    command: Some(lsp::Command {
18989                        title: "Command not in capabilities".to_owned(),
18990                        command: "not in capabilities".to_owned(),
18991                        arguments: None,
18992                    }),
18993                    data: None,
18994                },
18995                lsp::CodeLens {
18996                    range: lsp::Range {
18997                        start: lsp::Position {
18998                            line: 1,
18999                            character: 1,
19000                        },
19001                        end: lsp::Position {
19002                            line: 1,
19003                            character: 1,
19004                        },
19005                    },
19006                    command: Some(lsp::Command {
19007                        title: "Command not in range".to_owned(),
19008                        command: "_the/command".to_owned(),
19009                        arguments: None,
19010                    }),
19011                    data: None,
19012                },
19013            ]))
19014        })
19015        .next()
19016        .await;
19017
19018    let actions = actions.await.unwrap();
19019    assert_eq!(
19020        actions.len(),
19021        1,
19022        "Should have only one valid action for the 0..0 range"
19023    );
19024    let action = actions[0].clone();
19025    let apply = project.update(cx, |project, cx| {
19026        project.apply_code_action(buffer.clone(), action, true, cx)
19027    });
19028
19029    // Resolving the code action does not populate its edits. In absence of
19030    // edits, we must execute the given command.
19031    fake_server.set_request_handler::<lsp::request::CodeLensResolve, _, _>(
19032        |mut lens, _| async move {
19033            let lens_command = lens.command.as_mut().expect("should have a command");
19034            assert_eq!(lens_command.title, "Code lens command");
19035            lens_command.arguments = Some(vec![json!("the-argument")]);
19036            Ok(lens)
19037        },
19038    );
19039
19040    // While executing the command, the language server sends the editor
19041    // a `workspaceEdit` request.
19042    fake_server
19043        .set_request_handler::<lsp::request::ExecuteCommand, _, _>({
19044            let fake = fake_server.clone();
19045            move |params, _| {
19046                assert_eq!(params.command, "_the/command");
19047                let fake = fake.clone();
19048                async move {
19049                    fake.server
19050                        .request::<lsp::request::ApplyWorkspaceEdit>(
19051                            lsp::ApplyWorkspaceEditParams {
19052                                label: None,
19053                                edit: lsp::WorkspaceEdit {
19054                                    changes: Some(
19055                                        [(
19056                                            lsp::Url::from_file_path(path!("/dir/a.ts")).unwrap(),
19057                                            vec![lsp::TextEdit {
19058                                                range: lsp::Range::new(
19059                                                    lsp::Position::new(0, 0),
19060                                                    lsp::Position::new(0, 0),
19061                                                ),
19062                                                new_text: "X".into(),
19063                                            }],
19064                                        )]
19065                                        .into_iter()
19066                                        .collect(),
19067                                    ),
19068                                    ..Default::default()
19069                                },
19070                            },
19071                        )
19072                        .await
19073                        .unwrap();
19074                    Ok(Some(json!(null)))
19075                }
19076            }
19077        })
19078        .next()
19079        .await;
19080
19081    // Applying the code lens command returns a project transaction containing the edits
19082    // sent by the language server in its `workspaceEdit` request.
19083    let transaction = apply.await.unwrap();
19084    assert!(transaction.0.contains_key(&buffer));
19085    buffer.update(cx, |buffer, cx| {
19086        assert_eq!(buffer.text(), "Xa");
19087        buffer.undo(cx);
19088        assert_eq!(buffer.text(), "a");
19089    });
19090}
19091
19092#[gpui::test]
19093async fn test_editor_restore_data_different_in_panes(cx: &mut TestAppContext) {
19094    init_test(cx, |_| {});
19095
19096    let fs = FakeFs::new(cx.executor());
19097    let main_text = r#"fn main() {
19098println!("1");
19099println!("2");
19100println!("3");
19101println!("4");
19102println!("5");
19103}"#;
19104    let lib_text = "mod foo {}";
19105    fs.insert_tree(
19106        path!("/a"),
19107        json!({
19108            "lib.rs": lib_text,
19109            "main.rs": main_text,
19110        }),
19111    )
19112    .await;
19113
19114    let project = Project::test(fs, [path!("/a").as_ref()], cx).await;
19115    let (workspace, cx) =
19116        cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
19117    let worktree_id = workspace.update(cx, |workspace, cx| {
19118        workspace.project().update(cx, |project, cx| {
19119            project.worktrees(cx).next().unwrap().read(cx).id()
19120        })
19121    });
19122
19123    let expected_ranges = vec![
19124        Point::new(0, 0)..Point::new(0, 0),
19125        Point::new(1, 0)..Point::new(1, 1),
19126        Point::new(2, 0)..Point::new(2, 2),
19127        Point::new(3, 0)..Point::new(3, 3),
19128    ];
19129
19130    let pane_1 = workspace.update(cx, |workspace, _| workspace.active_pane().clone());
19131    let editor_1 = workspace
19132        .update_in(cx, |workspace, window, cx| {
19133            workspace.open_path(
19134                (worktree_id, "main.rs"),
19135                Some(pane_1.downgrade()),
19136                true,
19137                window,
19138                cx,
19139            )
19140        })
19141        .unwrap()
19142        .await
19143        .downcast::<Editor>()
19144        .unwrap();
19145    pane_1.update(cx, |pane, cx| {
19146        let open_editor = pane.active_item().unwrap().downcast::<Editor>().unwrap();
19147        open_editor.update(cx, |editor, cx| {
19148            assert_eq!(
19149                editor.display_text(cx),
19150                main_text,
19151                "Original main.rs text on initial open",
19152            );
19153            assert_eq!(
19154                editor
19155                    .selections
19156                    .all::<Point>(cx)
19157                    .into_iter()
19158                    .map(|s| s.range())
19159                    .collect::<Vec<_>>(),
19160                vec![Point::zero()..Point::zero()],
19161                "Default selections on initial open",
19162            );
19163        })
19164    });
19165    editor_1.update_in(cx, |editor, window, cx| {
19166        editor.change_selections(None, window, cx, |s| {
19167            s.select_ranges(expected_ranges.clone());
19168        });
19169    });
19170
19171    let pane_2 = workspace.update_in(cx, |workspace, window, cx| {
19172        workspace.split_pane(pane_1.clone(), SplitDirection::Right, window, cx)
19173    });
19174    let editor_2 = workspace
19175        .update_in(cx, |workspace, window, cx| {
19176            workspace.open_path(
19177                (worktree_id, "main.rs"),
19178                Some(pane_2.downgrade()),
19179                true,
19180                window,
19181                cx,
19182            )
19183        })
19184        .unwrap()
19185        .await
19186        .downcast::<Editor>()
19187        .unwrap();
19188    pane_2.update(cx, |pane, cx| {
19189        let open_editor = pane.active_item().unwrap().downcast::<Editor>().unwrap();
19190        open_editor.update(cx, |editor, cx| {
19191            assert_eq!(
19192                editor.display_text(cx),
19193                main_text,
19194                "Original main.rs text on initial open in another panel",
19195            );
19196            assert_eq!(
19197                editor
19198                    .selections
19199                    .all::<Point>(cx)
19200                    .into_iter()
19201                    .map(|s| s.range())
19202                    .collect::<Vec<_>>(),
19203                vec![Point::zero()..Point::zero()],
19204                "Default selections on initial open in another panel",
19205            );
19206        })
19207    });
19208
19209    editor_2.update_in(cx, |editor, window, cx| {
19210        editor.fold_ranges(expected_ranges.clone(), false, window, cx);
19211    });
19212
19213    let _other_editor_1 = workspace
19214        .update_in(cx, |workspace, window, cx| {
19215            workspace.open_path(
19216                (worktree_id, "lib.rs"),
19217                Some(pane_1.downgrade()),
19218                true,
19219                window,
19220                cx,
19221            )
19222        })
19223        .unwrap()
19224        .await
19225        .downcast::<Editor>()
19226        .unwrap();
19227    pane_1
19228        .update_in(cx, |pane, window, cx| {
19229            pane.close_inactive_items(&CloseInactiveItems::default(), window, cx)
19230                .unwrap()
19231        })
19232        .await
19233        .unwrap();
19234    drop(editor_1);
19235    pane_1.update(cx, |pane, cx| {
19236        pane.active_item()
19237            .unwrap()
19238            .downcast::<Editor>()
19239            .unwrap()
19240            .update(cx, |editor, cx| {
19241                assert_eq!(
19242                    editor.display_text(cx),
19243                    lib_text,
19244                    "Other file should be open and active",
19245                );
19246            });
19247        assert_eq!(pane.items().count(), 1, "No other editors should be open");
19248    });
19249
19250    let _other_editor_2 = workspace
19251        .update_in(cx, |workspace, window, cx| {
19252            workspace.open_path(
19253                (worktree_id, "lib.rs"),
19254                Some(pane_2.downgrade()),
19255                true,
19256                window,
19257                cx,
19258            )
19259        })
19260        .unwrap()
19261        .await
19262        .downcast::<Editor>()
19263        .unwrap();
19264    pane_2
19265        .update_in(cx, |pane, window, cx| {
19266            pane.close_inactive_items(&CloseInactiveItems::default(), window, cx)
19267                .unwrap()
19268        })
19269        .await
19270        .unwrap();
19271    drop(editor_2);
19272    pane_2.update(cx, |pane, cx| {
19273        let open_editor = pane.active_item().unwrap().downcast::<Editor>().unwrap();
19274        open_editor.update(cx, |editor, cx| {
19275            assert_eq!(
19276                editor.display_text(cx),
19277                lib_text,
19278                "Other file should be open and active in another panel too",
19279            );
19280        });
19281        assert_eq!(
19282            pane.items().count(),
19283            1,
19284            "No other editors should be open in another pane",
19285        );
19286    });
19287
19288    let _editor_1_reopened = workspace
19289        .update_in(cx, |workspace, window, cx| {
19290            workspace.open_path(
19291                (worktree_id, "main.rs"),
19292                Some(pane_1.downgrade()),
19293                true,
19294                window,
19295                cx,
19296            )
19297        })
19298        .unwrap()
19299        .await
19300        .downcast::<Editor>()
19301        .unwrap();
19302    let _editor_2_reopened = workspace
19303        .update_in(cx, |workspace, window, cx| {
19304            workspace.open_path(
19305                (worktree_id, "main.rs"),
19306                Some(pane_2.downgrade()),
19307                true,
19308                window,
19309                cx,
19310            )
19311        })
19312        .unwrap()
19313        .await
19314        .downcast::<Editor>()
19315        .unwrap();
19316    pane_1.update(cx, |pane, cx| {
19317        let open_editor = pane.active_item().unwrap().downcast::<Editor>().unwrap();
19318        open_editor.update(cx, |editor, cx| {
19319            assert_eq!(
19320                editor.display_text(cx),
19321                main_text,
19322                "Previous editor in the 1st panel had no extra text manipulations and should get none on reopen",
19323            );
19324            assert_eq!(
19325                editor
19326                    .selections
19327                    .all::<Point>(cx)
19328                    .into_iter()
19329                    .map(|s| s.range())
19330                    .collect::<Vec<_>>(),
19331                expected_ranges,
19332                "Previous editor in the 1st panel had selections and should get them restored on reopen",
19333            );
19334        })
19335    });
19336    pane_2.update(cx, |pane, cx| {
19337        let open_editor = pane.active_item().unwrap().downcast::<Editor>().unwrap();
19338        open_editor.update(cx, |editor, cx| {
19339            assert_eq!(
19340                editor.display_text(cx),
19341                r#"fn main() {
19342⋯rintln!("1");
19343⋯intln!("2");
19344⋯ntln!("3");
19345println!("4");
19346println!("5");
19347}"#,
19348                "Previous editor in the 2nd pane had folds and should restore those on reopen in the same pane",
19349            );
19350            assert_eq!(
19351                editor
19352                    .selections
19353                    .all::<Point>(cx)
19354                    .into_iter()
19355                    .map(|s| s.range())
19356                    .collect::<Vec<_>>(),
19357                vec![Point::zero()..Point::zero()],
19358                "Previous editor in the 2nd pane had no selections changed hence should restore none",
19359            );
19360        })
19361    });
19362}
19363
19364#[gpui::test]
19365async fn test_editor_does_not_restore_data_when_turned_off(cx: &mut TestAppContext) {
19366    init_test(cx, |_| {});
19367
19368    let fs = FakeFs::new(cx.executor());
19369    let main_text = r#"fn main() {
19370println!("1");
19371println!("2");
19372println!("3");
19373println!("4");
19374println!("5");
19375}"#;
19376    let lib_text = "mod foo {}";
19377    fs.insert_tree(
19378        path!("/a"),
19379        json!({
19380            "lib.rs": lib_text,
19381            "main.rs": main_text,
19382        }),
19383    )
19384    .await;
19385
19386    let project = Project::test(fs, [path!("/a").as_ref()], cx).await;
19387    let (workspace, cx) =
19388        cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
19389    let worktree_id = workspace.update(cx, |workspace, cx| {
19390        workspace.project().update(cx, |project, cx| {
19391            project.worktrees(cx).next().unwrap().read(cx).id()
19392        })
19393    });
19394
19395    let pane = workspace.update(cx, |workspace, _| workspace.active_pane().clone());
19396    let editor = workspace
19397        .update_in(cx, |workspace, window, cx| {
19398            workspace.open_path(
19399                (worktree_id, "main.rs"),
19400                Some(pane.downgrade()),
19401                true,
19402                window,
19403                cx,
19404            )
19405        })
19406        .unwrap()
19407        .await
19408        .downcast::<Editor>()
19409        .unwrap();
19410    pane.update(cx, |pane, cx| {
19411        let open_editor = pane.active_item().unwrap().downcast::<Editor>().unwrap();
19412        open_editor.update(cx, |editor, cx| {
19413            assert_eq!(
19414                editor.display_text(cx),
19415                main_text,
19416                "Original main.rs text on initial open",
19417            );
19418        })
19419    });
19420    editor.update_in(cx, |editor, window, cx| {
19421        editor.fold_ranges(vec![Point::new(0, 0)..Point::new(0, 0)], false, window, cx);
19422    });
19423
19424    cx.update_global(|store: &mut SettingsStore, cx| {
19425        store.update_user_settings::<WorkspaceSettings>(cx, |s| {
19426            s.restore_on_file_reopen = Some(false);
19427        });
19428    });
19429    editor.update_in(cx, |editor, window, cx| {
19430        editor.fold_ranges(
19431            vec![
19432                Point::new(1, 0)..Point::new(1, 1),
19433                Point::new(2, 0)..Point::new(2, 2),
19434                Point::new(3, 0)..Point::new(3, 3),
19435            ],
19436            false,
19437            window,
19438            cx,
19439        );
19440    });
19441    pane.update_in(cx, |pane, window, cx| {
19442        pane.close_all_items(&CloseAllItems::default(), window, cx)
19443            .unwrap()
19444    })
19445    .await
19446    .unwrap();
19447    pane.update(cx, |pane, _| {
19448        assert!(pane.active_item().is_none());
19449    });
19450    cx.update_global(|store: &mut SettingsStore, cx| {
19451        store.update_user_settings::<WorkspaceSettings>(cx, |s| {
19452            s.restore_on_file_reopen = Some(true);
19453        });
19454    });
19455
19456    let _editor_reopened = workspace
19457        .update_in(cx, |workspace, window, cx| {
19458            workspace.open_path(
19459                (worktree_id, "main.rs"),
19460                Some(pane.downgrade()),
19461                true,
19462                window,
19463                cx,
19464            )
19465        })
19466        .unwrap()
19467        .await
19468        .downcast::<Editor>()
19469        .unwrap();
19470    pane.update(cx, |pane, cx| {
19471        let open_editor = pane.active_item().unwrap().downcast::<Editor>().unwrap();
19472        open_editor.update(cx, |editor, cx| {
19473            assert_eq!(
19474                editor.display_text(cx),
19475                main_text,
19476                "No folds: even after enabling the restoration, previous editor's data should not be saved to be used for the restoration"
19477            );
19478        })
19479    });
19480}
19481
19482#[gpui::test]
19483async fn test_hide_mouse_context_menu_on_modal_opened(cx: &mut TestAppContext) {
19484    struct EmptyModalView {
19485        focus_handle: gpui::FocusHandle,
19486    }
19487    impl EventEmitter<DismissEvent> for EmptyModalView {}
19488    impl Render for EmptyModalView {
19489        fn render(&mut self, _: &mut Window, _: &mut Context<'_, Self>) -> impl IntoElement {
19490            div()
19491        }
19492    }
19493    impl Focusable for EmptyModalView {
19494        fn focus_handle(&self, _cx: &App) -> gpui::FocusHandle {
19495            self.focus_handle.clone()
19496        }
19497    }
19498    impl workspace::ModalView for EmptyModalView {}
19499    fn new_empty_modal_view(cx: &App) -> EmptyModalView {
19500        EmptyModalView {
19501            focus_handle: cx.focus_handle(),
19502        }
19503    }
19504
19505    init_test(cx, |_| {});
19506
19507    let fs = FakeFs::new(cx.executor());
19508    let project = Project::test(fs, [], cx).await;
19509    let workspace = cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
19510    let buffer = cx.update(|cx| MultiBuffer::build_simple("hello world!", cx));
19511    let cx = &mut VisualTestContext::from_window(*workspace.deref(), cx);
19512    let editor = cx.new_window_entity(|window, cx| {
19513        Editor::new(
19514            EditorMode::full(),
19515            buffer,
19516            Some(project.clone()),
19517            window,
19518            cx,
19519        )
19520    });
19521    workspace
19522        .update(cx, |workspace, window, cx| {
19523            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
19524        })
19525        .unwrap();
19526    editor.update_in(cx, |editor, window, cx| {
19527        editor.open_context_menu(&OpenContextMenu, window, cx);
19528        assert!(editor.mouse_context_menu.is_some());
19529    });
19530    workspace
19531        .update(cx, |workspace, window, cx| {
19532            workspace.toggle_modal(window, cx, |_, cx| new_empty_modal_view(cx));
19533        })
19534        .unwrap();
19535    cx.read(|cx| {
19536        assert!(editor.read(cx).mouse_context_menu.is_none());
19537    });
19538}
19539
19540fn empty_range(row: usize, column: usize) -> Range<DisplayPoint> {
19541    let point = DisplayPoint::new(DisplayRow(row as u32), column as u32);
19542    point..point
19543}
19544
19545fn assert_selection_ranges(marked_text: &str, editor: &mut Editor, cx: &mut Context<Editor>) {
19546    let (text, ranges) = marked_text_ranges(marked_text, true);
19547    assert_eq!(editor.text(cx), text);
19548    assert_eq!(
19549        editor.selections.ranges(cx),
19550        ranges,
19551        "Assert selections are {}",
19552        marked_text
19553    );
19554}
19555
19556pub fn handle_signature_help_request(
19557    cx: &mut EditorLspTestContext,
19558    mocked_response: lsp::SignatureHelp,
19559) -> impl Future<Output = ()> + use<> {
19560    let mut request =
19561        cx.set_request_handler::<lsp::request::SignatureHelpRequest, _, _>(move |_, _, _| {
19562            let mocked_response = mocked_response.clone();
19563            async move { Ok(Some(mocked_response)) }
19564        });
19565
19566    async move {
19567        request.next().await;
19568    }
19569}
19570
19571/// Handle completion request passing a marked string specifying where the completion
19572/// should be triggered from using '|' character, what range should be replaced, and what completions
19573/// should be returned using '<' and '>' to delimit the range.
19574///
19575/// Also see `handle_completion_request_with_insert_and_replace`.
19576#[track_caller]
19577pub fn handle_completion_request(
19578    cx: &mut EditorLspTestContext,
19579    marked_string: &str,
19580    completions: Vec<&'static str>,
19581    counter: Arc<AtomicUsize>,
19582) -> impl Future<Output = ()> {
19583    let complete_from_marker: TextRangeMarker = '|'.into();
19584    let replace_range_marker: TextRangeMarker = ('<', '>').into();
19585    let (_, mut marked_ranges) = marked_text_ranges_by(
19586        marked_string,
19587        vec![complete_from_marker.clone(), replace_range_marker.clone()],
19588    );
19589
19590    let complete_from_position =
19591        cx.to_lsp(marked_ranges.remove(&complete_from_marker).unwrap()[0].start);
19592    let replace_range =
19593        cx.to_lsp_range(marked_ranges.remove(&replace_range_marker).unwrap()[0].clone());
19594
19595    let mut request =
19596        cx.set_request_handler::<lsp::request::Completion, _, _>(move |url, params, _| {
19597            let completions = completions.clone();
19598            counter.fetch_add(1, atomic::Ordering::Release);
19599            async move {
19600                assert_eq!(params.text_document_position.text_document.uri, url.clone());
19601                assert_eq!(
19602                    params.text_document_position.position,
19603                    complete_from_position
19604                );
19605                Ok(Some(lsp::CompletionResponse::Array(
19606                    completions
19607                        .iter()
19608                        .map(|completion_text| lsp::CompletionItem {
19609                            label: completion_text.to_string(),
19610                            text_edit: Some(lsp::CompletionTextEdit::Edit(lsp::TextEdit {
19611                                range: replace_range,
19612                                new_text: completion_text.to_string(),
19613                            })),
19614                            ..Default::default()
19615                        })
19616                        .collect(),
19617                )))
19618            }
19619        });
19620
19621    async move {
19622        request.next().await;
19623    }
19624}
19625
19626/// Similar to `handle_completion_request`, but a [`CompletionTextEdit::InsertAndReplace`] will be
19627/// given instead, which also contains an `insert` range.
19628///
19629/// This function uses the cursor position to mimic what Rust-Analyzer provides as the `insert` range,
19630/// that is, `replace_range.start..cursor_pos`.
19631pub fn handle_completion_request_with_insert_and_replace(
19632    cx: &mut EditorLspTestContext,
19633    marked_string: &str,
19634    completions: Vec<&'static str>,
19635    counter: Arc<AtomicUsize>,
19636) -> impl Future<Output = ()> {
19637    let complete_from_marker: TextRangeMarker = '|'.into();
19638    let replace_range_marker: TextRangeMarker = ('<', '>').into();
19639    let (_, mut marked_ranges) = marked_text_ranges_by(
19640        marked_string,
19641        vec![complete_from_marker.clone(), replace_range_marker.clone()],
19642    );
19643
19644    let complete_from_position =
19645        cx.to_lsp(marked_ranges.remove(&complete_from_marker).unwrap()[0].start);
19646    let replace_range =
19647        cx.to_lsp_range(marked_ranges.remove(&replace_range_marker).unwrap()[0].clone());
19648
19649    let mut request =
19650        cx.set_request_handler::<lsp::request::Completion, _, _>(move |url, params, _| {
19651            let completions = completions.clone();
19652            counter.fetch_add(1, atomic::Ordering::Release);
19653            async move {
19654                assert_eq!(params.text_document_position.text_document.uri, url.clone());
19655                assert_eq!(
19656                    params.text_document_position.position, complete_from_position,
19657                    "marker `|` position doesn't match",
19658                );
19659                Ok(Some(lsp::CompletionResponse::Array(
19660                    completions
19661                        .iter()
19662                        .map(|completion_text| lsp::CompletionItem {
19663                            label: completion_text.to_string(),
19664                            text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
19665                                lsp::InsertReplaceEdit {
19666                                    insert: lsp::Range {
19667                                        start: replace_range.start,
19668                                        end: complete_from_position,
19669                                    },
19670                                    replace: replace_range,
19671                                    new_text: completion_text.to_string(),
19672                                },
19673                            )),
19674                            ..Default::default()
19675                        })
19676                        .collect(),
19677                )))
19678            }
19679        });
19680
19681    async move {
19682        request.next().await;
19683    }
19684}
19685
19686fn handle_resolve_completion_request(
19687    cx: &mut EditorLspTestContext,
19688    edits: Option<Vec<(&'static str, &'static str)>>,
19689) -> impl Future<Output = ()> {
19690    let edits = edits.map(|edits| {
19691        edits
19692            .iter()
19693            .map(|(marked_string, new_text)| {
19694                let (_, marked_ranges) = marked_text_ranges(marked_string, false);
19695                let replace_range = cx.to_lsp_range(marked_ranges[0].clone());
19696                lsp::TextEdit::new(replace_range, new_text.to_string())
19697            })
19698            .collect::<Vec<_>>()
19699    });
19700
19701    let mut request =
19702        cx.set_request_handler::<lsp::request::ResolveCompletionItem, _, _>(move |_, _, _| {
19703            let edits = edits.clone();
19704            async move {
19705                Ok(lsp::CompletionItem {
19706                    additional_text_edits: edits,
19707                    ..Default::default()
19708                })
19709            }
19710        });
19711
19712    async move {
19713        request.next().await;
19714    }
19715}
19716
19717pub(crate) fn update_test_language_settings(
19718    cx: &mut TestAppContext,
19719    f: impl Fn(&mut AllLanguageSettingsContent),
19720) {
19721    cx.update(|cx| {
19722        SettingsStore::update_global(cx, |store, cx| {
19723            store.update_user_settings::<AllLanguageSettings>(cx, f);
19724        });
19725    });
19726}
19727
19728pub(crate) fn update_test_project_settings(
19729    cx: &mut TestAppContext,
19730    f: impl Fn(&mut ProjectSettings),
19731) {
19732    cx.update(|cx| {
19733        SettingsStore::update_global(cx, |store, cx| {
19734            store.update_user_settings::<ProjectSettings>(cx, f);
19735        });
19736    });
19737}
19738
19739pub(crate) fn init_test(cx: &mut TestAppContext, f: fn(&mut AllLanguageSettingsContent)) {
19740    cx.update(|cx| {
19741        assets::Assets.load_test_fonts(cx);
19742        let store = SettingsStore::test(cx);
19743        cx.set_global(store);
19744        theme::init(theme::LoadThemes::JustBase, cx);
19745        release_channel::init(SemanticVersion::default(), cx);
19746        client::init_settings(cx);
19747        language::init(cx);
19748        Project::init_settings(cx);
19749        workspace::init_settings(cx);
19750        crate::init(cx);
19751    });
19752
19753    update_test_language_settings(cx, f);
19754}
19755
19756#[track_caller]
19757fn assert_hunk_revert(
19758    not_reverted_text_with_selections: &str,
19759    expected_hunk_statuses_before: Vec<DiffHunkStatusKind>,
19760    expected_reverted_text_with_selections: &str,
19761    base_text: &str,
19762    cx: &mut EditorLspTestContext,
19763) {
19764    cx.set_state(not_reverted_text_with_selections);
19765    cx.set_head_text(base_text);
19766    cx.executor().run_until_parked();
19767
19768    let actual_hunk_statuses_before = cx.update_editor(|editor, window, cx| {
19769        let snapshot = editor.snapshot(window, cx);
19770        let reverted_hunk_statuses = snapshot
19771            .buffer_snapshot
19772            .diff_hunks_in_range(0..snapshot.buffer_snapshot.len())
19773            .map(|hunk| hunk.status().kind)
19774            .collect::<Vec<_>>();
19775
19776        editor.git_restore(&Default::default(), window, cx);
19777        reverted_hunk_statuses
19778    });
19779    cx.executor().run_until_parked();
19780    cx.assert_editor_state(expected_reverted_text_with_selections);
19781    assert_eq!(actual_hunk_statuses_before, expected_hunk_statuses_before);
19782}