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, SemanticVersion, TestAppContext, UpdateGlobal, VisualTestContext,
   16    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
 5126#[gpui::test]
 5127async fn test_paste_multiline(cx: &mut TestAppContext) {
 5128    init_test(cx, |_| {});
 5129
 5130    let mut cx = EditorTestContext::new(cx).await;
 5131    cx.update_buffer(|buffer, cx| buffer.set_language(Some(rust_lang()), cx));
 5132
 5133    // Cut an indented block, without the leading whitespace.
 5134    cx.set_state(indoc! {"
 5135        const a: B = (
 5136            c(),
 5137            «d(
 5138                e,
 5139                f
 5140            )ˇ»
 5141        );
 5142    "});
 5143    cx.update_editor(|e, window, cx| e.cut(&Cut, window, cx));
 5144    cx.assert_editor_state(indoc! {"
 5145        const a: B = (
 5146            c(),
 5147            ˇ
 5148        );
 5149    "});
 5150
 5151    // Paste it at the same position.
 5152    cx.update_editor(|e, window, cx| e.paste(&Paste, window, cx));
 5153    cx.assert_editor_state(indoc! {"
 5154        const a: B = (
 5155            c(),
 5156            d(
 5157                e,
 5158                f
 5159 5160        );
 5161    "});
 5162
 5163    // Paste it at a line with a lower indent level.
 5164    cx.set_state(indoc! {"
 5165        ˇ
 5166        const a: B = (
 5167            c(),
 5168        );
 5169    "});
 5170    cx.update_editor(|e, window, cx| e.paste(&Paste, window, cx));
 5171    cx.assert_editor_state(indoc! {"
 5172        d(
 5173            e,
 5174            f
 5175 5176        const a: B = (
 5177            c(),
 5178        );
 5179    "});
 5180
 5181    // Cut an indented block, with the leading whitespace.
 5182    cx.set_state(indoc! {"
 5183        const a: B = (
 5184            c(),
 5185        «    d(
 5186                e,
 5187                f
 5188            )
 5189        ˇ»);
 5190    "});
 5191    cx.update_editor(|e, window, cx| e.cut(&Cut, window, cx));
 5192    cx.assert_editor_state(indoc! {"
 5193        const a: B = (
 5194            c(),
 5195        ˇ);
 5196    "});
 5197
 5198    // Paste it at the same position.
 5199    cx.update_editor(|e, window, cx| e.paste(&Paste, window, cx));
 5200    cx.assert_editor_state(indoc! {"
 5201        const a: B = (
 5202            c(),
 5203            d(
 5204                e,
 5205                f
 5206            )
 5207        ˇ);
 5208    "});
 5209
 5210    // Paste it at a line with a higher indent level.
 5211    cx.set_state(indoc! {"
 5212        const a: B = (
 5213            c(),
 5214            d(
 5215                e,
 5216 5217            )
 5218        );
 5219    "});
 5220    cx.update_editor(|e, window, cx| e.paste(&Paste, window, cx));
 5221    cx.assert_editor_state(indoc! {"
 5222        const a: B = (
 5223            c(),
 5224            d(
 5225                e,
 5226                f    d(
 5227                    e,
 5228                    f
 5229                )
 5230        ˇ
 5231            )
 5232        );
 5233    "});
 5234
 5235    // Copy an indented block, starting mid-line
 5236    cx.set_state(indoc! {"
 5237        const a: B = (
 5238            c(),
 5239            somethin«g(
 5240                e,
 5241                f
 5242            )ˇ»
 5243        );
 5244    "});
 5245    cx.update_editor(|e, window, cx| e.copy(&Copy, window, cx));
 5246
 5247    // Paste it on a line with a lower indent level
 5248    cx.update_editor(|e, window, cx| e.move_to_end(&Default::default(), window, cx));
 5249    cx.update_editor(|e, window, cx| e.paste(&Paste, window, cx));
 5250    cx.assert_editor_state(indoc! {"
 5251        const a: B = (
 5252            c(),
 5253            something(
 5254                e,
 5255                f
 5256            )
 5257        );
 5258        g(
 5259            e,
 5260            f
 5261"});
 5262}
 5263
 5264#[gpui::test]
 5265async fn test_paste_content_from_other_app(cx: &mut TestAppContext) {
 5266    init_test(cx, |_| {});
 5267
 5268    cx.write_to_clipboard(ClipboardItem::new_string(
 5269        "    d(\n        e\n    );\n".into(),
 5270    ));
 5271
 5272    let mut cx = EditorTestContext::new(cx).await;
 5273    cx.update_buffer(|buffer, cx| buffer.set_language(Some(rust_lang()), cx));
 5274
 5275    cx.set_state(indoc! {"
 5276        fn a() {
 5277            b();
 5278            if c() {
 5279                ˇ
 5280            }
 5281        }
 5282    "});
 5283
 5284    cx.update_editor(|e, window, cx| e.paste(&Paste, window, cx));
 5285    cx.assert_editor_state(indoc! {"
 5286        fn a() {
 5287            b();
 5288            if c() {
 5289                d(
 5290                    e
 5291                );
 5292        ˇ
 5293            }
 5294        }
 5295    "});
 5296
 5297    cx.set_state(indoc! {"
 5298        fn a() {
 5299            b();
 5300            ˇ
 5301        }
 5302    "});
 5303
 5304    cx.update_editor(|e, window, cx| e.paste(&Paste, window, cx));
 5305    cx.assert_editor_state(indoc! {"
 5306        fn a() {
 5307            b();
 5308            d(
 5309                e
 5310            );
 5311        ˇ
 5312        }
 5313    "});
 5314}
 5315
 5316#[gpui::test]
 5317fn test_select_all(cx: &mut TestAppContext) {
 5318    init_test(cx, |_| {});
 5319
 5320    let editor = cx.add_window(|window, cx| {
 5321        let buffer = MultiBuffer::build_simple("abc\nde\nfgh", cx);
 5322        build_editor(buffer, window, cx)
 5323    });
 5324    _ = editor.update(cx, |editor, window, cx| {
 5325        editor.select_all(&SelectAll, window, cx);
 5326        assert_eq!(
 5327            editor.selections.display_ranges(cx),
 5328            &[DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(2), 3)]
 5329        );
 5330    });
 5331}
 5332
 5333#[gpui::test]
 5334fn test_select_line(cx: &mut TestAppContext) {
 5335    init_test(cx, |_| {});
 5336
 5337    let editor = cx.add_window(|window, cx| {
 5338        let buffer = MultiBuffer::build_simple(&sample_text(6, 5, 'a'), cx);
 5339        build_editor(buffer, window, cx)
 5340    });
 5341    _ = editor.update(cx, |editor, window, cx| {
 5342        editor.change_selections(None, window, cx, |s| {
 5343            s.select_display_ranges([
 5344                DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(0), 1),
 5345                DisplayPoint::new(DisplayRow(0), 2)..DisplayPoint::new(DisplayRow(0), 2),
 5346                DisplayPoint::new(DisplayRow(1), 0)..DisplayPoint::new(DisplayRow(1), 0),
 5347                DisplayPoint::new(DisplayRow(4), 2)..DisplayPoint::new(DisplayRow(4), 2),
 5348            ])
 5349        });
 5350        editor.select_line(&SelectLine, window, cx);
 5351        assert_eq!(
 5352            editor.selections.display_ranges(cx),
 5353            vec![
 5354                DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(2), 0),
 5355                DisplayPoint::new(DisplayRow(4), 0)..DisplayPoint::new(DisplayRow(5), 0),
 5356            ]
 5357        );
 5358    });
 5359
 5360    _ = editor.update(cx, |editor, window, cx| {
 5361        editor.select_line(&SelectLine, window, cx);
 5362        assert_eq!(
 5363            editor.selections.display_ranges(cx),
 5364            vec![
 5365                DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(3), 0),
 5366                DisplayPoint::new(DisplayRow(4), 0)..DisplayPoint::new(DisplayRow(5), 5),
 5367            ]
 5368        );
 5369    });
 5370
 5371    _ = editor.update(cx, |editor, window, cx| {
 5372        editor.select_line(&SelectLine, window, cx);
 5373        assert_eq!(
 5374            editor.selections.display_ranges(cx),
 5375            vec![DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(5), 5)]
 5376        );
 5377    });
 5378}
 5379
 5380#[gpui::test]
 5381async fn test_split_selection_into_lines(cx: &mut TestAppContext) {
 5382    init_test(cx, |_| {});
 5383    let mut cx = EditorTestContext::new(cx).await;
 5384
 5385    #[track_caller]
 5386    fn test(cx: &mut EditorTestContext, initial_state: &'static str, expected_state: &'static str) {
 5387        cx.set_state(initial_state);
 5388        cx.update_editor(|e, window, cx| {
 5389            e.split_selection_into_lines(&SplitSelectionIntoLines, window, cx)
 5390        });
 5391        cx.assert_editor_state(expected_state);
 5392    }
 5393
 5394    // Selection starts and ends at the middle of lines, left-to-right
 5395    test(
 5396        &mut cx,
 5397        "aa\nb«ˇb\ncc\ndd\ne»e\nff",
 5398        "aa\nbbˇ\nccˇ\nddˇ\neˇe\nff",
 5399    );
 5400    // Same thing, right-to-left
 5401    test(
 5402        &mut cx,
 5403        "aa\nb«b\ncc\ndd\neˇ»e\nff",
 5404        "aa\nbbˇ\nccˇ\nddˇ\neˇe\nff",
 5405    );
 5406
 5407    // Whole buffer, left-to-right, last line *doesn't* end with newline
 5408    test(
 5409        &mut cx,
 5410        "«ˇaa\nbb\ncc\ndd\nee\nff»",
 5411        "aaˇ\nbbˇ\nccˇ\nddˇ\neeˇ\nffˇ",
 5412    );
 5413    // Same thing, right-to-left
 5414    test(
 5415        &mut cx,
 5416        "«aa\nbb\ncc\ndd\nee\nffˇ»",
 5417        "aaˇ\nbbˇ\nccˇ\nddˇ\neeˇ\nffˇ",
 5418    );
 5419
 5420    // Whole buffer, left-to-right, last line ends with newline
 5421    test(
 5422        &mut cx,
 5423        "«ˇaa\nbb\ncc\ndd\nee\nff\n»",
 5424        "aaˇ\nbbˇ\nccˇ\nddˇ\neeˇ\nffˇ\n",
 5425    );
 5426    // Same thing, right-to-left
 5427    test(
 5428        &mut cx,
 5429        "«aa\nbb\ncc\ndd\nee\nff\nˇ»",
 5430        "aaˇ\nbbˇ\nccˇ\nddˇ\neeˇ\nffˇ\n",
 5431    );
 5432
 5433    // Starts at the end of a line, ends at the start of another
 5434    test(
 5435        &mut cx,
 5436        "aa\nbb«ˇ\ncc\ndd\nee\n»ff\n",
 5437        "aa\nbbˇ\nccˇ\nddˇ\neeˇ\nff\n",
 5438    );
 5439}
 5440
 5441#[gpui::test]
 5442async fn test_split_selection_into_lines_interacting_with_creases(cx: &mut TestAppContext) {
 5443    init_test(cx, |_| {});
 5444
 5445    let editor = cx.add_window(|window, cx| {
 5446        let buffer = MultiBuffer::build_simple(&sample_text(9, 5, 'a'), cx);
 5447        build_editor(buffer, window, cx)
 5448    });
 5449
 5450    // setup
 5451    _ = editor.update(cx, |editor, window, cx| {
 5452        editor.fold_creases(
 5453            vec![
 5454                Crease::simple(Point::new(0, 2)..Point::new(1, 2), FoldPlaceholder::test()),
 5455                Crease::simple(Point::new(2, 3)..Point::new(4, 1), FoldPlaceholder::test()),
 5456                Crease::simple(Point::new(7, 0)..Point::new(8, 4), FoldPlaceholder::test()),
 5457            ],
 5458            true,
 5459            window,
 5460            cx,
 5461        );
 5462        assert_eq!(
 5463            editor.display_text(cx),
 5464            "aa⋯bbb\nccc⋯eeee\nfffff\nggggg\n⋯i"
 5465        );
 5466    });
 5467
 5468    _ = editor.update(cx, |editor, window, cx| {
 5469        editor.change_selections(None, window, cx, |s| {
 5470            s.select_display_ranges([
 5471                DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(0), 1),
 5472                DisplayPoint::new(DisplayRow(0), 2)..DisplayPoint::new(DisplayRow(0), 2),
 5473                DisplayPoint::new(DisplayRow(1), 0)..DisplayPoint::new(DisplayRow(1), 0),
 5474                DisplayPoint::new(DisplayRow(4), 4)..DisplayPoint::new(DisplayRow(4), 4),
 5475            ])
 5476        });
 5477        editor.split_selection_into_lines(&SplitSelectionIntoLines, window, cx);
 5478        assert_eq!(
 5479            editor.display_text(cx),
 5480            "aaaaa\nbbbbb\nccc⋯eeee\nfffff\nggggg\n⋯i"
 5481        );
 5482    });
 5483    EditorTestContext::for_editor(editor, cx)
 5484        .await
 5485        .assert_editor_state("aˇaˇaaa\nbbbbb\nˇccccc\nddddd\neeeee\nfffff\nggggg\nhhhhh\niiiiiˇ");
 5486
 5487    _ = editor.update(cx, |editor, window, cx| {
 5488        editor.change_selections(None, window, cx, |s| {
 5489            s.select_display_ranges([
 5490                DisplayPoint::new(DisplayRow(5), 0)..DisplayPoint::new(DisplayRow(0), 1)
 5491            ])
 5492        });
 5493        editor.split_selection_into_lines(&SplitSelectionIntoLines, window, cx);
 5494        assert_eq!(
 5495            editor.display_text(cx),
 5496            "aaaaa\nbbbbb\nccccc\nddddd\neeeee\nfffff\nggggg\nhhhhh\niiiii"
 5497        );
 5498        assert_eq!(
 5499            editor.selections.display_ranges(cx),
 5500            [
 5501                DisplayPoint::new(DisplayRow(0), 5)..DisplayPoint::new(DisplayRow(0), 5),
 5502                DisplayPoint::new(DisplayRow(1), 5)..DisplayPoint::new(DisplayRow(1), 5),
 5503                DisplayPoint::new(DisplayRow(2), 5)..DisplayPoint::new(DisplayRow(2), 5),
 5504                DisplayPoint::new(DisplayRow(3), 5)..DisplayPoint::new(DisplayRow(3), 5),
 5505                DisplayPoint::new(DisplayRow(4), 5)..DisplayPoint::new(DisplayRow(4), 5),
 5506                DisplayPoint::new(DisplayRow(5), 5)..DisplayPoint::new(DisplayRow(5), 5),
 5507                DisplayPoint::new(DisplayRow(6), 5)..DisplayPoint::new(DisplayRow(6), 5)
 5508            ]
 5509        );
 5510    });
 5511    EditorTestContext::for_editor(editor, cx)
 5512        .await
 5513        .assert_editor_state(
 5514            "aaaaaˇ\nbbbbbˇ\ncccccˇ\ndddddˇ\neeeeeˇ\nfffffˇ\ngggggˇ\nhhhhh\niiiii",
 5515        );
 5516}
 5517
 5518#[gpui::test]
 5519async fn test_add_selection_above_below(cx: &mut TestAppContext) {
 5520    init_test(cx, |_| {});
 5521
 5522    let mut cx = EditorTestContext::new(cx).await;
 5523
 5524    cx.set_state(indoc!(
 5525        r#"abc
 5526           defˇghi
 5527
 5528           jk
 5529           nlmo
 5530           "#
 5531    ));
 5532
 5533    cx.update_editor(|editor, window, cx| {
 5534        editor.add_selection_above(&Default::default(), window, cx);
 5535    });
 5536
 5537    cx.assert_editor_state(indoc!(
 5538        r#"abcˇ
 5539           defˇghi
 5540
 5541           jk
 5542           nlmo
 5543           "#
 5544    ));
 5545
 5546    cx.update_editor(|editor, window, cx| {
 5547        editor.add_selection_above(&Default::default(), window, cx);
 5548    });
 5549
 5550    cx.assert_editor_state(indoc!(
 5551        r#"abcˇ
 5552            defˇghi
 5553
 5554            jk
 5555            nlmo
 5556            "#
 5557    ));
 5558
 5559    cx.update_editor(|editor, window, cx| {
 5560        editor.add_selection_below(&Default::default(), window, cx);
 5561    });
 5562
 5563    cx.assert_editor_state(indoc!(
 5564        r#"abc
 5565           defˇghi
 5566
 5567           jk
 5568           nlmo
 5569           "#
 5570    ));
 5571
 5572    cx.update_editor(|editor, window, cx| {
 5573        editor.undo_selection(&Default::default(), window, cx);
 5574    });
 5575
 5576    cx.assert_editor_state(indoc!(
 5577        r#"abcˇ
 5578           defˇghi
 5579
 5580           jk
 5581           nlmo
 5582           "#
 5583    ));
 5584
 5585    cx.update_editor(|editor, window, cx| {
 5586        editor.redo_selection(&Default::default(), window, cx);
 5587    });
 5588
 5589    cx.assert_editor_state(indoc!(
 5590        r#"abc
 5591           defˇghi
 5592
 5593           jk
 5594           nlmo
 5595           "#
 5596    ));
 5597
 5598    cx.update_editor(|editor, window, cx| {
 5599        editor.add_selection_below(&Default::default(), window, cx);
 5600    });
 5601
 5602    cx.assert_editor_state(indoc!(
 5603        r#"abc
 5604           defˇghi
 5605
 5606           jk
 5607           nlmˇo
 5608           "#
 5609    ));
 5610
 5611    cx.update_editor(|editor, window, cx| {
 5612        editor.add_selection_below(&Default::default(), window, cx);
 5613    });
 5614
 5615    cx.assert_editor_state(indoc!(
 5616        r#"abc
 5617           defˇghi
 5618
 5619           jk
 5620           nlmˇo
 5621           "#
 5622    ));
 5623
 5624    // change selections
 5625    cx.set_state(indoc!(
 5626        r#"abc
 5627           def«ˇg»hi
 5628
 5629           jk
 5630           nlmo
 5631           "#
 5632    ));
 5633
 5634    cx.update_editor(|editor, window, cx| {
 5635        editor.add_selection_below(&Default::default(), window, cx);
 5636    });
 5637
 5638    cx.assert_editor_state(indoc!(
 5639        r#"abc
 5640           def«ˇg»hi
 5641
 5642           jk
 5643           nlm«ˇo»
 5644           "#
 5645    ));
 5646
 5647    cx.update_editor(|editor, window, cx| {
 5648        editor.add_selection_below(&Default::default(), window, cx);
 5649    });
 5650
 5651    cx.assert_editor_state(indoc!(
 5652        r#"abc
 5653           def«ˇg»hi
 5654
 5655           jk
 5656           nlm«ˇo»
 5657           "#
 5658    ));
 5659
 5660    cx.update_editor(|editor, window, cx| {
 5661        editor.add_selection_above(&Default::default(), window, cx);
 5662    });
 5663
 5664    cx.assert_editor_state(indoc!(
 5665        r#"abc
 5666           def«ˇg»hi
 5667
 5668           jk
 5669           nlmo
 5670           "#
 5671    ));
 5672
 5673    cx.update_editor(|editor, window, cx| {
 5674        editor.add_selection_above(&Default::default(), window, cx);
 5675    });
 5676
 5677    cx.assert_editor_state(indoc!(
 5678        r#"abc
 5679           def«ˇg»hi
 5680
 5681           jk
 5682           nlmo
 5683           "#
 5684    ));
 5685
 5686    // Change selections again
 5687    cx.set_state(indoc!(
 5688        r#"a«bc
 5689           defgˇ»hi
 5690
 5691           jk
 5692           nlmo
 5693           "#
 5694    ));
 5695
 5696    cx.update_editor(|editor, window, cx| {
 5697        editor.add_selection_below(&Default::default(), window, cx);
 5698    });
 5699
 5700    cx.assert_editor_state(indoc!(
 5701        r#"a«bcˇ»
 5702           d«efgˇ»hi
 5703
 5704           j«kˇ»
 5705           nlmo
 5706           "#
 5707    ));
 5708
 5709    cx.update_editor(|editor, window, cx| {
 5710        editor.add_selection_below(&Default::default(), window, cx);
 5711    });
 5712    cx.assert_editor_state(indoc!(
 5713        r#"a«bcˇ»
 5714           d«efgˇ»hi
 5715
 5716           j«kˇ»
 5717           n«lmoˇ»
 5718           "#
 5719    ));
 5720    cx.update_editor(|editor, window, cx| {
 5721        editor.add_selection_above(&Default::default(), window, cx);
 5722    });
 5723
 5724    cx.assert_editor_state(indoc!(
 5725        r#"a«bcˇ»
 5726           d«efgˇ»hi
 5727
 5728           j«kˇ»
 5729           nlmo
 5730           "#
 5731    ));
 5732
 5733    // Change selections again
 5734    cx.set_state(indoc!(
 5735        r#"abc
 5736           d«ˇefghi
 5737
 5738           jk
 5739           nlm»o
 5740           "#
 5741    ));
 5742
 5743    cx.update_editor(|editor, window, cx| {
 5744        editor.add_selection_above(&Default::default(), window, cx);
 5745    });
 5746
 5747    cx.assert_editor_state(indoc!(
 5748        r#"a«ˇbc»
 5749           d«ˇef»ghi
 5750
 5751           j«ˇk»
 5752           n«ˇlm»o
 5753           "#
 5754    ));
 5755
 5756    cx.update_editor(|editor, window, cx| {
 5757        editor.add_selection_below(&Default::default(), window, cx);
 5758    });
 5759
 5760    cx.assert_editor_state(indoc!(
 5761        r#"abc
 5762           d«ˇef»ghi
 5763
 5764           j«ˇk»
 5765           n«ˇlm»o
 5766           "#
 5767    ));
 5768}
 5769
 5770#[gpui::test]
 5771async fn test_select_next(cx: &mut TestAppContext) {
 5772    init_test(cx, |_| {});
 5773
 5774    let mut cx = EditorTestContext::new(cx).await;
 5775    cx.set_state("abc\nˇabc abc\ndefabc\nabc");
 5776
 5777    cx.update_editor(|e, window, cx| e.select_next(&SelectNext::default(), window, cx))
 5778        .unwrap();
 5779    cx.assert_editor_state("abc\n«abcˇ» abc\ndefabc\nabc");
 5780
 5781    cx.update_editor(|e, window, cx| e.select_next(&SelectNext::default(), window, cx))
 5782        .unwrap();
 5783    cx.assert_editor_state("abc\n«abcˇ» «abcˇ»\ndefabc\nabc");
 5784
 5785    cx.update_editor(|editor, window, cx| editor.undo_selection(&UndoSelection, window, cx));
 5786    cx.assert_editor_state("abc\n«abcˇ» abc\ndefabc\nabc");
 5787
 5788    cx.update_editor(|editor, window, cx| editor.redo_selection(&RedoSelection, window, cx));
 5789    cx.assert_editor_state("abc\n«abcˇ» «abcˇ»\ndefabc\nabc");
 5790
 5791    cx.update_editor(|e, window, cx| e.select_next(&SelectNext::default(), window, cx))
 5792        .unwrap();
 5793    cx.assert_editor_state("abc\n«abcˇ» «abcˇ»\ndefabc\n«abcˇ»");
 5794
 5795    cx.update_editor(|e, window, cx| e.select_next(&SelectNext::default(), window, cx))
 5796        .unwrap();
 5797    cx.assert_editor_state("«abcˇ»\n«abcˇ» «abcˇ»\ndefabc\n«abcˇ»");
 5798}
 5799
 5800#[gpui::test]
 5801async fn test_select_all_matches(cx: &mut TestAppContext) {
 5802    init_test(cx, |_| {});
 5803
 5804    let mut cx = EditorTestContext::new(cx).await;
 5805
 5806    // Test caret-only selections
 5807    cx.set_state("abc\nˇabc abc\ndefabc\nabc");
 5808    cx.update_editor(|e, window, cx| e.select_all_matches(&SelectAllMatches, window, cx))
 5809        .unwrap();
 5810    cx.assert_editor_state("«abcˇ»\n«abcˇ» «abcˇ»\ndefabc\n«abcˇ»");
 5811
 5812    // Test left-to-right selections
 5813    cx.set_state("abc\n«abcˇ»\nabc");
 5814    cx.update_editor(|e, window, cx| e.select_all_matches(&SelectAllMatches, window, cx))
 5815        .unwrap();
 5816    cx.assert_editor_state("«abcˇ»\n«abcˇ»\n«abcˇ»");
 5817
 5818    // Test right-to-left selections
 5819    cx.set_state("abc\n«ˇabc»\nabc");
 5820    cx.update_editor(|e, window, cx| e.select_all_matches(&SelectAllMatches, window, cx))
 5821        .unwrap();
 5822    cx.assert_editor_state("«ˇabc»\n«ˇabc»\n«ˇabc»");
 5823
 5824    // Test selecting whitespace with caret selection
 5825    cx.set_state("abc\nˇ   abc\nabc");
 5826    cx.update_editor(|e, window, cx| e.select_all_matches(&SelectAllMatches, window, cx))
 5827        .unwrap();
 5828    cx.assert_editor_state("abc\n«   ˇ»abc\nabc");
 5829
 5830    // Test selecting whitespace with left-to-right selection
 5831    cx.set_state("abc\n«ˇ  »abc\nabc");
 5832    cx.update_editor(|e, window, cx| e.select_all_matches(&SelectAllMatches, window, cx))
 5833        .unwrap();
 5834    cx.assert_editor_state("abc\n«ˇ  »abc\nabc");
 5835
 5836    // Test no matches with right-to-left selection
 5837    cx.set_state("abc\n«  ˇ»abc\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\nabc");
 5841}
 5842
 5843#[gpui::test]
 5844async fn test_select_all_matches_does_not_scroll(cx: &mut TestAppContext) {
 5845    init_test(cx, |_| {});
 5846
 5847    let mut cx = EditorTestContext::new(cx).await;
 5848
 5849    let large_body_1 = "\nd".repeat(200);
 5850    let large_body_2 = "\ne".repeat(200);
 5851
 5852    cx.set_state(&format!(
 5853        "abc\nabc{large_body_1} «ˇa»bc{large_body_2}\nefabc\nabc"
 5854    ));
 5855    let initial_scroll_position = cx.update_editor(|editor, _, cx| {
 5856        let scroll_position = editor.scroll_position(cx);
 5857        assert!(scroll_position.y > 0.0, "Initial selection is between two large bodies and should have the editor scrolled to it");
 5858        scroll_position
 5859    });
 5860
 5861    cx.update_editor(|e, window, cx| e.select_all_matches(&SelectAllMatches, window, cx))
 5862        .unwrap();
 5863    cx.assert_editor_state(&format!(
 5864        "«ˇa»bc\n«ˇa»bc{large_body_1} «ˇa»bc{large_body_2}\nef«ˇa»bc\n«ˇa»bc"
 5865    ));
 5866    let scroll_position_after_selection =
 5867        cx.update_editor(|editor, _, cx| editor.scroll_position(cx));
 5868    assert_eq!(
 5869        initial_scroll_position, scroll_position_after_selection,
 5870        "Scroll position should not change after selecting all matches"
 5871    );
 5872}
 5873
 5874#[gpui::test]
 5875async fn test_undo_format_scrolls_to_last_edit_pos(cx: &mut TestAppContext) {
 5876    init_test(cx, |_| {});
 5877
 5878    let mut cx = EditorLspTestContext::new_rust(
 5879        lsp::ServerCapabilities {
 5880            document_formatting_provider: Some(lsp::OneOf::Left(true)),
 5881            ..Default::default()
 5882        },
 5883        cx,
 5884    )
 5885    .await;
 5886
 5887    cx.set_state(indoc! {"
 5888        line 1
 5889        line 2
 5890        linˇe 3
 5891        line 4
 5892        line 5
 5893    "});
 5894
 5895    // Make an edit
 5896    cx.update_editor(|editor, window, cx| {
 5897        editor.handle_input("X", window, cx);
 5898    });
 5899
 5900    // Move cursor to a different position
 5901    cx.update_editor(|editor, window, cx| {
 5902        editor.change_selections(None, window, cx, |s| {
 5903            s.select_ranges([Point::new(4, 2)..Point::new(4, 2)]);
 5904        });
 5905    });
 5906
 5907    cx.assert_editor_state(indoc! {"
 5908        line 1
 5909        line 2
 5910        linXe 3
 5911        line 4
 5912        liˇne 5
 5913    "});
 5914
 5915    cx.lsp
 5916        .set_request_handler::<lsp::request::Formatting, _, _>(move |_, _| async move {
 5917            Ok(Some(vec![lsp::TextEdit::new(
 5918                lsp::Range::new(lsp::Position::new(0, 0), lsp::Position::new(0, 0)),
 5919                "PREFIX ".to_string(),
 5920            )]))
 5921        });
 5922
 5923    cx.update_editor(|editor, window, cx| editor.format(&Default::default(), window, cx))
 5924        .unwrap()
 5925        .await
 5926        .unwrap();
 5927
 5928    cx.assert_editor_state(indoc! {"
 5929        PREFIX line 1
 5930        line 2
 5931        linXe 3
 5932        line 4
 5933        liˇne 5
 5934    "});
 5935
 5936    // Undo formatting
 5937    cx.update_editor(|editor, window, cx| {
 5938        editor.undo(&Default::default(), window, cx);
 5939    });
 5940
 5941    // Verify cursor moved back to position after edit
 5942    cx.assert_editor_state(indoc! {"
 5943        line 1
 5944        line 2
 5945        linXˇe 3
 5946        line 4
 5947        line 5
 5948    "});
 5949}
 5950
 5951#[gpui::test]
 5952async fn test_select_next_with_multiple_carets(cx: &mut TestAppContext) {
 5953    init_test(cx, |_| {});
 5954
 5955    let mut cx = EditorTestContext::new(cx).await;
 5956    cx.set_state(
 5957        r#"let foo = 2;
 5958lˇet foo = 2;
 5959let fooˇ = 2;
 5960let foo = 2;
 5961let foo = ˇ2;"#,
 5962    );
 5963
 5964    cx.update_editor(|e, window, cx| e.select_next(&SelectNext::default(), window, cx))
 5965        .unwrap();
 5966    cx.assert_editor_state(
 5967        r#"let foo = 2;
 5968«letˇ» foo = 2;
 5969let «fooˇ» = 2;
 5970let foo = 2;
 5971let foo = «2ˇ»;"#,
 5972    );
 5973
 5974    // noop for multiple selections with different contents
 5975    cx.update_editor(|e, window, cx| e.select_next(&SelectNext::default(), window, cx))
 5976        .unwrap();
 5977    cx.assert_editor_state(
 5978        r#"let foo = 2;
 5979«letˇ» foo = 2;
 5980let «fooˇ» = 2;
 5981let foo = 2;
 5982let foo = «2ˇ»;"#,
 5983    );
 5984}
 5985
 5986#[gpui::test]
 5987async fn test_select_previous_multibuffer(cx: &mut TestAppContext) {
 5988    init_test(cx, |_| {});
 5989
 5990    let mut cx =
 5991        EditorTestContext::new_multibuffer(cx, ["aaa\n«bbb\nccc\n»ddd", "aaa\n«bbb\nccc\n»ddd"]);
 5992
 5993    cx.assert_editor_state(indoc! {"
 5994        ˇbbb
 5995        ccc
 5996
 5997        bbb
 5998        ccc
 5999        "});
 6000    cx.dispatch_action(SelectPrevious::default());
 6001    cx.assert_editor_state(indoc! {"
 6002                «bbbˇ»
 6003                ccc
 6004
 6005                bbb
 6006                ccc
 6007                "});
 6008    cx.dispatch_action(SelectPrevious::default());
 6009    cx.assert_editor_state(indoc! {"
 6010                «bbbˇ»
 6011                ccc
 6012
 6013                «bbbˇ»
 6014                ccc
 6015                "});
 6016}
 6017
 6018#[gpui::test]
 6019async fn test_select_previous_with_single_caret(cx: &mut TestAppContext) {
 6020    init_test(cx, |_| {});
 6021
 6022    let mut cx = EditorTestContext::new(cx).await;
 6023    cx.set_state("abc\nˇabc abc\ndefabc\nabc");
 6024
 6025    cx.update_editor(|e, window, cx| e.select_previous(&SelectPrevious::default(), window, cx))
 6026        .unwrap();
 6027    cx.assert_editor_state("abc\n«abcˇ» abc\ndefabc\nabc");
 6028
 6029    cx.update_editor(|e, window, cx| e.select_previous(&SelectPrevious::default(), window, cx))
 6030        .unwrap();
 6031    cx.assert_editor_state("«abcˇ»\n«abcˇ» abc\ndefabc\nabc");
 6032
 6033    cx.update_editor(|editor, window, cx| editor.undo_selection(&UndoSelection, window, cx));
 6034    cx.assert_editor_state("abc\n«abcˇ» abc\ndefabc\nabc");
 6035
 6036    cx.update_editor(|editor, window, cx| editor.redo_selection(&RedoSelection, window, cx));
 6037    cx.assert_editor_state("«abcˇ»\n«abcˇ» abc\ndefabc\nabc");
 6038
 6039    cx.update_editor(|e, window, cx| e.select_previous(&SelectPrevious::default(), window, cx))
 6040        .unwrap();
 6041    cx.assert_editor_state("«abcˇ»\n«abcˇ» abc\ndefabc\n«abcˇ»");
 6042
 6043    cx.update_editor(|e, window, cx| e.select_previous(&SelectPrevious::default(), window, cx))
 6044        .unwrap();
 6045    cx.assert_editor_state("«abcˇ»\n«abcˇ» abc\ndef«abcˇ»\n«abcˇ»");
 6046
 6047    cx.update_editor(|e, window, cx| e.select_previous(&SelectPrevious::default(), window, cx))
 6048        .unwrap();
 6049    cx.assert_editor_state("«abcˇ»\n«abcˇ» «abcˇ»\ndef«abcˇ»\n«abcˇ»");
 6050}
 6051
 6052#[gpui::test]
 6053async fn test_select_previous_empty_buffer(cx: &mut TestAppContext) {
 6054    init_test(cx, |_| {});
 6055
 6056    let mut cx = EditorTestContext::new(cx).await;
 6057    cx.set_state("");
 6058
 6059    cx.update_editor(|e, window, cx| e.select_previous(&SelectPrevious::default(), window, cx))
 6060        .unwrap();
 6061    cx.assert_editor_state("«aˇ»");
 6062    cx.update_editor(|e, window, cx| e.select_previous(&SelectPrevious::default(), window, cx))
 6063        .unwrap();
 6064    cx.assert_editor_state("«aˇ»");
 6065}
 6066
 6067#[gpui::test]
 6068async fn test_select_previous_with_multiple_carets(cx: &mut TestAppContext) {
 6069    init_test(cx, |_| {});
 6070
 6071    let mut cx = EditorTestContext::new(cx).await;
 6072    cx.set_state(
 6073        r#"let foo = 2;
 6074lˇet foo = 2;
 6075let fooˇ = 2;
 6076let foo = 2;
 6077let foo = ˇ2;"#,
 6078    );
 6079
 6080    cx.update_editor(|e, window, cx| e.select_previous(&SelectPrevious::default(), window, cx))
 6081        .unwrap();
 6082    cx.assert_editor_state(
 6083        r#"let foo = 2;
 6084«letˇ» foo = 2;
 6085let «fooˇ» = 2;
 6086let foo = 2;
 6087let foo = «2ˇ»;"#,
 6088    );
 6089
 6090    // noop for multiple selections with different contents
 6091    cx.update_editor(|e, window, cx| e.select_previous(&SelectPrevious::default(), window, cx))
 6092        .unwrap();
 6093    cx.assert_editor_state(
 6094        r#"let foo = 2;
 6095«letˇ» foo = 2;
 6096let «fooˇ» = 2;
 6097let foo = 2;
 6098let foo = «2ˇ»;"#,
 6099    );
 6100}
 6101
 6102#[gpui::test]
 6103async fn test_select_previous_with_single_selection(cx: &mut TestAppContext) {
 6104    init_test(cx, |_| {});
 6105
 6106    let mut cx = EditorTestContext::new(cx).await;
 6107    cx.set_state("abc\n«ˇabc» abc\ndefabc\nabc");
 6108
 6109    cx.update_editor(|e, window, cx| e.select_previous(&SelectPrevious::default(), window, cx))
 6110        .unwrap();
 6111    cx.assert_editor_state("«abcˇ»\n«ˇabc» abc\ndefabc\nabc");
 6112
 6113    cx.update_editor(|e, window, cx| e.select_previous(&SelectPrevious::default(), window, cx))
 6114        .unwrap();
 6115    cx.assert_editor_state("«abcˇ»\n«ˇabc» abc\ndefabc\n«abcˇ»");
 6116
 6117    cx.update_editor(|editor, window, cx| editor.undo_selection(&UndoSelection, window, cx));
 6118    cx.assert_editor_state("«abcˇ»\n«ˇabc» abc\ndefabc\nabc");
 6119
 6120    cx.update_editor(|editor, window, cx| editor.redo_selection(&RedoSelection, window, cx));
 6121    cx.assert_editor_state("«abcˇ»\n«ˇabc» abc\ndefabc\n«abcˇ»");
 6122
 6123    cx.update_editor(|e, window, cx| e.select_previous(&SelectPrevious::default(), window, cx))
 6124        .unwrap();
 6125    cx.assert_editor_state("«abcˇ»\n«ˇabc» abc\ndef«abcˇ»\n«abcˇ»");
 6126
 6127    cx.update_editor(|e, window, cx| e.select_previous(&SelectPrevious::default(), window, cx))
 6128        .unwrap();
 6129    cx.assert_editor_state("«abcˇ»\n«ˇabc» «abcˇ»\ndef«abcˇ»\n«abcˇ»");
 6130}
 6131
 6132#[gpui::test]
 6133async fn test_select_larger_smaller_syntax_node(cx: &mut TestAppContext) {
 6134    init_test(cx, |_| {});
 6135
 6136    let language = Arc::new(Language::new(
 6137        LanguageConfig::default(),
 6138        Some(tree_sitter_rust::LANGUAGE.into()),
 6139    ));
 6140
 6141    let text = r#"
 6142        use mod1::mod2::{mod3, mod4};
 6143
 6144        fn fn_1(param1: bool, param2: &str) {
 6145            let var1 = "text";
 6146        }
 6147    "#
 6148    .unindent();
 6149
 6150    let buffer = cx.new(|cx| Buffer::local(text, cx).with_language(language, cx));
 6151    let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 6152    let (editor, cx) = cx.add_window_view(|window, cx| build_editor(buffer, window, cx));
 6153
 6154    editor
 6155        .condition::<crate::EditorEvent>(cx, |editor, cx| !editor.buffer.read(cx).is_parsing(cx))
 6156        .await;
 6157
 6158    editor.update_in(cx, |editor, window, cx| {
 6159        editor.change_selections(None, window, cx, |s| {
 6160            s.select_display_ranges([
 6161                DisplayPoint::new(DisplayRow(0), 25)..DisplayPoint::new(DisplayRow(0), 25),
 6162                DisplayPoint::new(DisplayRow(2), 24)..DisplayPoint::new(DisplayRow(2), 12),
 6163                DisplayPoint::new(DisplayRow(3), 18)..DisplayPoint::new(DisplayRow(3), 18),
 6164            ]);
 6165        });
 6166        editor.select_larger_syntax_node(&SelectLargerSyntaxNode, window, cx);
 6167    });
 6168    editor.update(cx, |editor, cx| {
 6169        assert_text_with_selections(
 6170            editor,
 6171            indoc! {r#"
 6172                use mod1::mod2::{mod3, «mod4ˇ»};
 6173
 6174                fn fn_1«ˇ(param1: bool, param2: &str)» {
 6175                    let var1 = "«ˇtext»";
 6176                }
 6177            "#},
 6178            cx,
 6179        );
 6180    });
 6181
 6182    editor.update_in(cx, |editor, window, cx| {
 6183        editor.select_larger_syntax_node(&SelectLargerSyntaxNode, window, cx);
 6184    });
 6185    editor.update(cx, |editor, cx| {
 6186        assert_text_with_selections(
 6187            editor,
 6188            indoc! {r#"
 6189                use mod1::mod2::«{mod3, mod4}ˇ»;
 6190
 6191                «ˇfn fn_1(param1: bool, param2: &str) {
 6192                    let var1 = "text";
 6193 6194            "#},
 6195            cx,
 6196        );
 6197    });
 6198
 6199    editor.update_in(cx, |editor, window, cx| {
 6200        editor.select_larger_syntax_node(&SelectLargerSyntaxNode, window, cx);
 6201    });
 6202    assert_eq!(
 6203        editor.update(cx, |editor, cx| editor.selections.display_ranges(cx)),
 6204        &[DisplayPoint::new(DisplayRow(5), 0)..DisplayPoint::new(DisplayRow(0), 0)]
 6205    );
 6206
 6207    // Trying to expand the selected syntax node one more time has no effect.
 6208    editor.update_in(cx, |editor, window, cx| {
 6209        editor.select_larger_syntax_node(&SelectLargerSyntaxNode, window, cx);
 6210    });
 6211    assert_eq!(
 6212        editor.update(cx, |editor, cx| editor.selections.display_ranges(cx)),
 6213        &[DisplayPoint::new(DisplayRow(5), 0)..DisplayPoint::new(DisplayRow(0), 0)]
 6214    );
 6215
 6216    editor.update_in(cx, |editor, window, cx| {
 6217        editor.select_smaller_syntax_node(&SelectSmallerSyntaxNode, window, cx);
 6218    });
 6219    editor.update(cx, |editor, cx| {
 6220        assert_text_with_selections(
 6221            editor,
 6222            indoc! {r#"
 6223                use mod1::mod2::«{mod3, mod4}ˇ»;
 6224
 6225                «ˇfn fn_1(param1: bool, param2: &str) {
 6226                    let var1 = "text";
 6227 6228            "#},
 6229            cx,
 6230        );
 6231    });
 6232
 6233    editor.update_in(cx, |editor, window, cx| {
 6234        editor.select_smaller_syntax_node(&SelectSmallerSyntaxNode, window, cx);
 6235    });
 6236    editor.update(cx, |editor, cx| {
 6237        assert_text_with_selections(
 6238            editor,
 6239            indoc! {r#"
 6240                use mod1::mod2::{mod3, «mod4ˇ»};
 6241
 6242                fn fn_1«ˇ(param1: bool, param2: &str)» {
 6243                    let var1 = "«ˇtext»";
 6244                }
 6245            "#},
 6246            cx,
 6247        );
 6248    });
 6249
 6250    editor.update_in(cx, |editor, window, cx| {
 6251        editor.select_smaller_syntax_node(&SelectSmallerSyntaxNode, window, cx);
 6252    });
 6253    editor.update(cx, |editor, cx| {
 6254        assert_text_with_selections(
 6255            editor,
 6256            indoc! {r#"
 6257                use mod1::mod2::{mod3, mo«ˇ»d4};
 6258
 6259                fn fn_1(para«ˇm1: bool, pa»ram2: &str) {
 6260                    let var1 = "te«ˇ»xt";
 6261                }
 6262            "#},
 6263            cx,
 6264        );
 6265    });
 6266
 6267    // Trying to shrink the selected syntax node one more time has no effect.
 6268    editor.update_in(cx, |editor, window, cx| {
 6269        editor.select_smaller_syntax_node(&SelectSmallerSyntaxNode, window, cx);
 6270    });
 6271    editor.update_in(cx, |editor, _, cx| {
 6272        assert_text_with_selections(
 6273            editor,
 6274            indoc! {r#"
 6275                use mod1::mod2::{mod3, mo«ˇ»d4};
 6276
 6277                fn fn_1(para«ˇm1: bool, pa»ram2: &str) {
 6278                    let var1 = "te«ˇ»xt";
 6279                }
 6280            "#},
 6281            cx,
 6282        );
 6283    });
 6284
 6285    // Ensure that we keep expanding the selection if the larger selection starts or ends within
 6286    // a fold.
 6287    editor.update_in(cx, |editor, window, cx| {
 6288        editor.fold_creases(
 6289            vec![
 6290                Crease::simple(
 6291                    Point::new(0, 21)..Point::new(0, 24),
 6292                    FoldPlaceholder::test(),
 6293                ),
 6294                Crease::simple(
 6295                    Point::new(3, 20)..Point::new(3, 22),
 6296                    FoldPlaceholder::test(),
 6297                ),
 6298            ],
 6299            true,
 6300            window,
 6301            cx,
 6302        );
 6303        editor.select_larger_syntax_node(&SelectLargerSyntaxNode, window, cx);
 6304    });
 6305    editor.update(cx, |editor, cx| {
 6306        assert_text_with_selections(
 6307            editor,
 6308            indoc! {r#"
 6309                use mod1::mod2::«{mod3, mod4}ˇ»;
 6310
 6311                fn fn_1«ˇ(param1: bool, param2: &str)» {
 6312                    «ˇlet var1 = "text";»
 6313                }
 6314            "#},
 6315            cx,
 6316        );
 6317    });
 6318}
 6319
 6320#[gpui::test]
 6321async fn test_fold_function_bodies(cx: &mut TestAppContext) {
 6322    init_test(cx, |_| {});
 6323
 6324    let base_text = r#"
 6325        impl A {
 6326            // this is an uncommitted comment
 6327
 6328            fn b() {
 6329                c();
 6330            }
 6331
 6332            // this is another uncommitted comment
 6333
 6334            fn d() {
 6335                // e
 6336                // f
 6337            }
 6338        }
 6339
 6340        fn g() {
 6341            // h
 6342        }
 6343    "#
 6344    .unindent();
 6345
 6346    let text = r#"
 6347        ˇimpl A {
 6348
 6349            fn b() {
 6350                c();
 6351            }
 6352
 6353            fn d() {
 6354                // e
 6355                // f
 6356            }
 6357        }
 6358
 6359        fn g() {
 6360            // h
 6361        }
 6362    "#
 6363    .unindent();
 6364
 6365    let mut cx = EditorLspTestContext::new_rust(Default::default(), cx).await;
 6366    cx.set_state(&text);
 6367    cx.set_head_text(&base_text);
 6368    cx.update_editor(|editor, window, cx| {
 6369        editor.expand_all_diff_hunks(&Default::default(), window, cx);
 6370    });
 6371
 6372    cx.assert_state_with_diff(
 6373        "
 6374        ˇimpl A {
 6375      -     // this is an uncommitted comment
 6376
 6377            fn b() {
 6378                c();
 6379            }
 6380
 6381      -     // this is another uncommitted comment
 6382      -
 6383            fn d() {
 6384                // e
 6385                // f
 6386            }
 6387        }
 6388
 6389        fn g() {
 6390            // h
 6391        }
 6392    "
 6393        .unindent(),
 6394    );
 6395
 6396    let expected_display_text = "
 6397        impl A {
 6398            // this is an uncommitted comment
 6399
 6400            fn b() {
 6401 6402            }
 6403
 6404            // this is another uncommitted comment
 6405
 6406            fn d() {
 6407 6408            }
 6409        }
 6410
 6411        fn g() {
 6412 6413        }
 6414        "
 6415    .unindent();
 6416
 6417    cx.update_editor(|editor, window, cx| {
 6418        editor.fold_function_bodies(&FoldFunctionBodies, window, cx);
 6419        assert_eq!(editor.display_text(cx), expected_display_text);
 6420    });
 6421}
 6422
 6423#[gpui::test]
 6424async fn test_autoindent(cx: &mut TestAppContext) {
 6425    init_test(cx, |_| {});
 6426
 6427    let language = Arc::new(
 6428        Language::new(
 6429            LanguageConfig {
 6430                brackets: BracketPairConfig {
 6431                    pairs: vec![
 6432                        BracketPair {
 6433                            start: "{".to_string(),
 6434                            end: "}".to_string(),
 6435                            close: false,
 6436                            surround: false,
 6437                            newline: true,
 6438                        },
 6439                        BracketPair {
 6440                            start: "(".to_string(),
 6441                            end: ")".to_string(),
 6442                            close: false,
 6443                            surround: false,
 6444                            newline: true,
 6445                        },
 6446                    ],
 6447                    ..Default::default()
 6448                },
 6449                ..Default::default()
 6450            },
 6451            Some(tree_sitter_rust::LANGUAGE.into()),
 6452        )
 6453        .with_indents_query(
 6454            r#"
 6455                (_ "(" ")" @end) @indent
 6456                (_ "{" "}" @end) @indent
 6457            "#,
 6458        )
 6459        .unwrap(),
 6460    );
 6461
 6462    let text = "fn a() {}";
 6463
 6464    let buffer = cx.new(|cx| Buffer::local(text, cx).with_language(language, cx));
 6465    let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 6466    let (editor, cx) = cx.add_window_view(|window, cx| build_editor(buffer, window, cx));
 6467    editor
 6468        .condition::<crate::EditorEvent>(cx, |editor, cx| !editor.buffer.read(cx).is_parsing(cx))
 6469        .await;
 6470
 6471    editor.update_in(cx, |editor, window, cx| {
 6472        editor.change_selections(None, window, cx, |s| s.select_ranges([5..5, 8..8, 9..9]));
 6473        editor.newline(&Newline, window, cx);
 6474        assert_eq!(editor.text(cx), "fn a(\n    \n) {\n    \n}\n");
 6475        assert_eq!(
 6476            editor.selections.ranges(cx),
 6477            &[
 6478                Point::new(1, 4)..Point::new(1, 4),
 6479                Point::new(3, 4)..Point::new(3, 4),
 6480                Point::new(5, 0)..Point::new(5, 0)
 6481            ]
 6482        );
 6483    });
 6484}
 6485
 6486#[gpui::test]
 6487async fn test_autoindent_selections(cx: &mut TestAppContext) {
 6488    init_test(cx, |_| {});
 6489
 6490    {
 6491        let mut cx = EditorLspTestContext::new_rust(Default::default(), cx).await;
 6492        cx.set_state(indoc! {"
 6493            impl A {
 6494
 6495                fn b() {}
 6496
 6497            «fn c() {
 6498
 6499            }ˇ»
 6500            }
 6501        "});
 6502
 6503        cx.update_editor(|editor, window, cx| {
 6504            editor.autoindent(&Default::default(), window, cx);
 6505        });
 6506
 6507        cx.assert_editor_state(indoc! {"
 6508            impl A {
 6509
 6510                fn b() {}
 6511
 6512                «fn c() {
 6513
 6514                }ˇ»
 6515            }
 6516        "});
 6517    }
 6518
 6519    {
 6520        let mut cx = EditorTestContext::new_multibuffer(
 6521            cx,
 6522            [indoc! { "
 6523                impl A {
 6524                «
 6525                // a
 6526                fn b(){}
 6527                »
 6528                «
 6529                    }
 6530                    fn c(){}
 6531                »
 6532            "}],
 6533        );
 6534
 6535        let buffer = cx.update_editor(|editor, _, cx| {
 6536            let buffer = editor.buffer().update(cx, |buffer, _| {
 6537                buffer.all_buffers().iter().next().unwrap().clone()
 6538            });
 6539            buffer.update(cx, |buffer, cx| buffer.set_language(Some(rust_lang()), cx));
 6540            buffer
 6541        });
 6542
 6543        cx.run_until_parked();
 6544        cx.update_editor(|editor, window, cx| {
 6545            editor.select_all(&Default::default(), window, cx);
 6546            editor.autoindent(&Default::default(), window, cx)
 6547        });
 6548        cx.run_until_parked();
 6549
 6550        cx.update(|_, cx| {
 6551            assert_eq!(
 6552                buffer.read(cx).text(),
 6553                indoc! { "
 6554                    impl A {
 6555
 6556                        // a
 6557                        fn b(){}
 6558
 6559
 6560                    }
 6561                    fn c(){}
 6562
 6563                " }
 6564            )
 6565        });
 6566    }
 6567}
 6568
 6569#[gpui::test]
 6570async fn test_autoclose_and_auto_surround_pairs(cx: &mut TestAppContext) {
 6571    init_test(cx, |_| {});
 6572
 6573    let mut cx = EditorTestContext::new(cx).await;
 6574
 6575    let language = Arc::new(Language::new(
 6576        LanguageConfig {
 6577            brackets: BracketPairConfig {
 6578                pairs: vec![
 6579                    BracketPair {
 6580                        start: "{".to_string(),
 6581                        end: "}".to_string(),
 6582                        close: true,
 6583                        surround: true,
 6584                        newline: true,
 6585                    },
 6586                    BracketPair {
 6587                        start: "(".to_string(),
 6588                        end: ")".to_string(),
 6589                        close: true,
 6590                        surround: true,
 6591                        newline: true,
 6592                    },
 6593                    BracketPair {
 6594                        start: "/*".to_string(),
 6595                        end: " */".to_string(),
 6596                        close: true,
 6597                        surround: true,
 6598                        newline: true,
 6599                    },
 6600                    BracketPair {
 6601                        start: "[".to_string(),
 6602                        end: "]".to_string(),
 6603                        close: false,
 6604                        surround: false,
 6605                        newline: true,
 6606                    },
 6607                    BracketPair {
 6608                        start: "\"".to_string(),
 6609                        end: "\"".to_string(),
 6610                        close: true,
 6611                        surround: true,
 6612                        newline: false,
 6613                    },
 6614                    BracketPair {
 6615                        start: "<".to_string(),
 6616                        end: ">".to_string(),
 6617                        close: false,
 6618                        surround: true,
 6619                        newline: true,
 6620                    },
 6621                ],
 6622                ..Default::default()
 6623            },
 6624            autoclose_before: "})]".to_string(),
 6625            ..Default::default()
 6626        },
 6627        Some(tree_sitter_rust::LANGUAGE.into()),
 6628    ));
 6629
 6630    cx.language_registry().add(language.clone());
 6631    cx.update_buffer(|buffer, cx| {
 6632        buffer.set_language(Some(language), cx);
 6633    });
 6634
 6635    cx.set_state(
 6636        &r#"
 6637            🏀ˇ
 6638            εˇ
 6639            ❤️ˇ
 6640        "#
 6641        .unindent(),
 6642    );
 6643
 6644    // autoclose multiple nested brackets at multiple cursors
 6645    cx.update_editor(|editor, window, cx| {
 6646        editor.handle_input("{", window, cx);
 6647        editor.handle_input("{", window, cx);
 6648        editor.handle_input("{", window, cx);
 6649    });
 6650    cx.assert_editor_state(
 6651        &"
 6652            🏀{{{ˇ}}}
 6653            ε{{{ˇ}}}
 6654            ❤️{{{ˇ}}}
 6655        "
 6656        .unindent(),
 6657    );
 6658
 6659    // insert a different closing bracket
 6660    cx.update_editor(|editor, window, cx| {
 6661        editor.handle_input(")", window, cx);
 6662    });
 6663    cx.assert_editor_state(
 6664        &"
 6665            🏀{{{)ˇ}}}
 6666            ε{{{)ˇ}}}
 6667            ❤️{{{)ˇ}}}
 6668        "
 6669        .unindent(),
 6670    );
 6671
 6672    // skip over the auto-closed brackets when typing a closing bracket
 6673    cx.update_editor(|editor, window, cx| {
 6674        editor.move_right(&MoveRight, window, cx);
 6675        editor.handle_input("}", window, cx);
 6676        editor.handle_input("}", window, cx);
 6677        editor.handle_input("}", window, cx);
 6678    });
 6679    cx.assert_editor_state(
 6680        &"
 6681            🏀{{{)}}}}ˇ
 6682            ε{{{)}}}}ˇ
 6683            ❤️{{{)}}}}ˇ
 6684        "
 6685        .unindent(),
 6686    );
 6687
 6688    // autoclose multi-character pairs
 6689    cx.set_state(
 6690        &"
 6691            ˇ
 6692            ˇ
 6693        "
 6694        .unindent(),
 6695    );
 6696    cx.update_editor(|editor, window, cx| {
 6697        editor.handle_input("/", window, cx);
 6698        editor.handle_input("*", window, cx);
 6699    });
 6700    cx.assert_editor_state(
 6701        &"
 6702            /*ˇ */
 6703            /*ˇ */
 6704        "
 6705        .unindent(),
 6706    );
 6707
 6708    // one cursor autocloses a multi-character pair, one cursor
 6709    // does not autoclose.
 6710    cx.set_state(
 6711        &"
 6712 6713            ˇ
 6714        "
 6715        .unindent(),
 6716    );
 6717    cx.update_editor(|editor, window, cx| editor.handle_input("*", window, cx));
 6718    cx.assert_editor_state(
 6719        &"
 6720            /*ˇ */
 6721 6722        "
 6723        .unindent(),
 6724    );
 6725
 6726    // Don't autoclose if the next character isn't whitespace and isn't
 6727    // listed in the language's "autoclose_before" section.
 6728    cx.set_state("ˇa b");
 6729    cx.update_editor(|editor, window, cx| editor.handle_input("{", window, cx));
 6730    cx.assert_editor_state("{ˇa b");
 6731
 6732    // Don't autoclose if `close` is false for the bracket pair
 6733    cx.set_state("ˇ");
 6734    cx.update_editor(|editor, window, cx| editor.handle_input("[", window, cx));
 6735    cx.assert_editor_state("");
 6736
 6737    // Surround with brackets if text is selected
 6738    cx.set_state("«aˇ» b");
 6739    cx.update_editor(|editor, window, cx| editor.handle_input("{", window, cx));
 6740    cx.assert_editor_state("{«aˇ»} b");
 6741
 6742    // Autoclose when not immediately after a word character
 6743    cx.set_state("a ˇ");
 6744    cx.update_editor(|editor, window, cx| editor.handle_input("\"", window, cx));
 6745    cx.assert_editor_state("a \"ˇ\"");
 6746
 6747    // Autoclose pair where the start and end characters are the same
 6748    cx.update_editor(|editor, window, cx| editor.handle_input("\"", window, cx));
 6749    cx.assert_editor_state("a \"\"ˇ");
 6750
 6751    // Don't autoclose when immediately after a word character
 6752    cx.set_state("");
 6753    cx.update_editor(|editor, window, cx| editor.handle_input("\"", window, cx));
 6754    cx.assert_editor_state("a\"ˇ");
 6755
 6756    // Do autoclose when after a non-word character
 6757    cx.set_state("");
 6758    cx.update_editor(|editor, window, cx| editor.handle_input("\"", window, cx));
 6759    cx.assert_editor_state("{\"ˇ\"");
 6760
 6761    // Non identical pairs autoclose regardless of preceding character
 6762    cx.set_state("");
 6763    cx.update_editor(|editor, window, cx| editor.handle_input("{", window, cx));
 6764    cx.assert_editor_state("a{ˇ}");
 6765
 6766    // Don't autoclose pair if autoclose is disabled
 6767    cx.set_state("ˇ");
 6768    cx.update_editor(|editor, window, cx| editor.handle_input("<", window, cx));
 6769    cx.assert_editor_state("");
 6770
 6771    // Surround with brackets if text is selected and auto_surround is enabled, even if autoclose is disabled
 6772    cx.set_state("«aˇ» b");
 6773    cx.update_editor(|editor, window, cx| editor.handle_input("<", window, cx));
 6774    cx.assert_editor_state("<«aˇ»> b");
 6775}
 6776
 6777#[gpui::test]
 6778async fn test_always_treat_brackets_as_autoclosed_skip_over(cx: &mut TestAppContext) {
 6779    init_test(cx, |settings| {
 6780        settings.defaults.always_treat_brackets_as_autoclosed = Some(true);
 6781    });
 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: false,
 6807                        surround: false,
 6808                        newline: true,
 6809                    },
 6810                ],
 6811                ..Default::default()
 6812            },
 6813            autoclose_before: "})]".to_string(),
 6814            ..Default::default()
 6815        },
 6816        Some(tree_sitter_rust::LANGUAGE.into()),
 6817    ));
 6818
 6819    cx.language_registry().add(language.clone());
 6820    cx.update_buffer(|buffer, cx| {
 6821        buffer.set_language(Some(language), cx);
 6822    });
 6823
 6824    cx.set_state(
 6825        &"
 6826            ˇ
 6827            ˇ
 6828            ˇ
 6829        "
 6830        .unindent(),
 6831    );
 6832
 6833    // ensure only matching closing brackets are skipped over
 6834    cx.update_editor(|editor, window, cx| {
 6835        editor.handle_input("}", window, cx);
 6836        editor.move_left(&MoveLeft, window, cx);
 6837        editor.handle_input(")", window, cx);
 6838        editor.move_left(&MoveLeft, window, cx);
 6839    });
 6840    cx.assert_editor_state(
 6841        &"
 6842            ˇ)}
 6843            ˇ)}
 6844            ˇ)}
 6845        "
 6846        .unindent(),
 6847    );
 6848
 6849    // skip-over closing brackets at multiple cursors
 6850    cx.update_editor(|editor, window, cx| {
 6851        editor.handle_input(")", window, cx);
 6852        editor.handle_input("}", window, cx);
 6853    });
 6854    cx.assert_editor_state(
 6855        &"
 6856            )}ˇ
 6857            )}ˇ
 6858            )}ˇ
 6859        "
 6860        .unindent(),
 6861    );
 6862
 6863    // ignore non-close brackets
 6864    cx.update_editor(|editor, window, cx| {
 6865        editor.handle_input("]", window, cx);
 6866        editor.move_left(&MoveLeft, window, cx);
 6867        editor.handle_input("]", window, cx);
 6868    });
 6869    cx.assert_editor_state(
 6870        &"
 6871            )}]ˇ]
 6872            )}]ˇ]
 6873            )}]ˇ]
 6874        "
 6875        .unindent(),
 6876    );
 6877}
 6878
 6879#[gpui::test]
 6880async fn test_autoclose_with_embedded_language(cx: &mut TestAppContext) {
 6881    init_test(cx, |_| {});
 6882
 6883    let mut cx = EditorTestContext::new(cx).await;
 6884
 6885    let html_language = Arc::new(
 6886        Language::new(
 6887            LanguageConfig {
 6888                name: "HTML".into(),
 6889                brackets: BracketPairConfig {
 6890                    pairs: vec![
 6891                        BracketPair {
 6892                            start: "<".into(),
 6893                            end: ">".into(),
 6894                            close: true,
 6895                            ..Default::default()
 6896                        },
 6897                        BracketPair {
 6898                            start: "{".into(),
 6899                            end: "}".into(),
 6900                            close: true,
 6901                            ..Default::default()
 6902                        },
 6903                        BracketPair {
 6904                            start: "(".into(),
 6905                            end: ")".into(),
 6906                            close: true,
 6907                            ..Default::default()
 6908                        },
 6909                    ],
 6910                    ..Default::default()
 6911                },
 6912                autoclose_before: "})]>".into(),
 6913                ..Default::default()
 6914            },
 6915            Some(tree_sitter_html::LANGUAGE.into()),
 6916        )
 6917        .with_injection_query(
 6918            r#"
 6919            (script_element
 6920                (raw_text) @injection.content
 6921                (#set! injection.language "javascript"))
 6922            "#,
 6923        )
 6924        .unwrap(),
 6925    );
 6926
 6927    let javascript_language = Arc::new(Language::new(
 6928        LanguageConfig {
 6929            name: "JavaScript".into(),
 6930            brackets: BracketPairConfig {
 6931                pairs: vec![
 6932                    BracketPair {
 6933                        start: "/*".into(),
 6934                        end: " */".into(),
 6935                        close: true,
 6936                        ..Default::default()
 6937                    },
 6938                    BracketPair {
 6939                        start: "{".into(),
 6940                        end: "}".into(),
 6941                        close: true,
 6942                        ..Default::default()
 6943                    },
 6944                    BracketPair {
 6945                        start: "(".into(),
 6946                        end: ")".into(),
 6947                        close: true,
 6948                        ..Default::default()
 6949                    },
 6950                ],
 6951                ..Default::default()
 6952            },
 6953            autoclose_before: "})]>".into(),
 6954            ..Default::default()
 6955        },
 6956        Some(tree_sitter_typescript::LANGUAGE_TSX.into()),
 6957    ));
 6958
 6959    cx.language_registry().add(html_language.clone());
 6960    cx.language_registry().add(javascript_language.clone());
 6961
 6962    cx.update_buffer(|buffer, cx| {
 6963        buffer.set_language(Some(html_language), cx);
 6964    });
 6965
 6966    cx.set_state(
 6967        &r#"
 6968            <body>ˇ
 6969                <script>
 6970                    var x = 1;ˇ
 6971                </script>
 6972            </body>ˇ
 6973        "#
 6974        .unindent(),
 6975    );
 6976
 6977    // Precondition: different languages are active at different locations.
 6978    cx.update_editor(|editor, window, cx| {
 6979        let snapshot = editor.snapshot(window, cx);
 6980        let cursors = editor.selections.ranges::<usize>(cx);
 6981        let languages = cursors
 6982            .iter()
 6983            .map(|c| snapshot.language_at(c.start).unwrap().name())
 6984            .collect::<Vec<_>>();
 6985        assert_eq!(
 6986            languages,
 6987            &["HTML".into(), "JavaScript".into(), "HTML".into()]
 6988        );
 6989    });
 6990
 6991    // Angle brackets autoclose in HTML, but not JavaScript.
 6992    cx.update_editor(|editor, window, cx| {
 6993        editor.handle_input("<", window, cx);
 6994        editor.handle_input("a", window, cx);
 6995    });
 6996    cx.assert_editor_state(
 6997        &r#"
 6998            <body><aˇ>
 6999                <script>
 7000                    var x = 1;<aˇ
 7001                </script>
 7002            </body><aˇ>
 7003        "#
 7004        .unindent(),
 7005    );
 7006
 7007    // Curly braces and parens autoclose in both HTML and JavaScript.
 7008    cx.update_editor(|editor, window, cx| {
 7009        editor.handle_input(" b=", window, cx);
 7010        editor.handle_input("{", window, cx);
 7011        editor.handle_input("c", window, cx);
 7012        editor.handle_input("(", window, cx);
 7013    });
 7014    cx.assert_editor_state(
 7015        &r#"
 7016            <body><a b={c(ˇ)}>
 7017                <script>
 7018                    var x = 1;<a b={c(ˇ)}
 7019                </script>
 7020            </body><a b={c(ˇ)}>
 7021        "#
 7022        .unindent(),
 7023    );
 7024
 7025    // Brackets that were already autoclosed are skipped.
 7026    cx.update_editor(|editor, window, cx| {
 7027        editor.handle_input(")", window, cx);
 7028        editor.handle_input("d", window, cx);
 7029        editor.handle_input("}", window, cx);
 7030    });
 7031    cx.assert_editor_state(
 7032        &r#"
 7033            <body><a b={c()d}ˇ>
 7034                <script>
 7035                    var x = 1;<a b={c()d}ˇ
 7036                </script>
 7037            </body><a b={c()d}ˇ>
 7038        "#
 7039        .unindent(),
 7040    );
 7041    cx.update_editor(|editor, window, cx| {
 7042        editor.handle_input(">", window, cx);
 7043    });
 7044    cx.assert_editor_state(
 7045        &r#"
 7046            <body><a b={c()d}>ˇ
 7047                <script>
 7048                    var x = 1;<a b={c()d}>ˇ
 7049                </script>
 7050            </body><a b={c()d}>ˇ
 7051        "#
 7052        .unindent(),
 7053    );
 7054
 7055    // Reset
 7056    cx.set_state(
 7057        &r#"
 7058            <body>ˇ
 7059                <script>
 7060                    var x = 1;ˇ
 7061                </script>
 7062            </body>ˇ
 7063        "#
 7064        .unindent(),
 7065    );
 7066
 7067    cx.update_editor(|editor, window, cx| {
 7068        editor.handle_input("<", window, cx);
 7069    });
 7070    cx.assert_editor_state(
 7071        &r#"
 7072            <body><ˇ>
 7073                <script>
 7074                    var x = 1;<ˇ
 7075                </script>
 7076            </body><ˇ>
 7077        "#
 7078        .unindent(),
 7079    );
 7080
 7081    // When backspacing, the closing angle brackets are removed.
 7082    cx.update_editor(|editor, window, cx| {
 7083        editor.backspace(&Backspace, window, cx);
 7084    });
 7085    cx.assert_editor_state(
 7086        &r#"
 7087            <body>ˇ
 7088                <script>
 7089                    var x = 1;ˇ
 7090                </script>
 7091            </body>ˇ
 7092        "#
 7093        .unindent(),
 7094    );
 7095
 7096    // Block comments autoclose in JavaScript, but not HTML.
 7097    cx.update_editor(|editor, window, cx| {
 7098        editor.handle_input("/", window, cx);
 7099        editor.handle_input("*", window, cx);
 7100    });
 7101    cx.assert_editor_state(
 7102        &r#"
 7103            <body>/*ˇ
 7104                <script>
 7105                    var x = 1;/*ˇ */
 7106                </script>
 7107            </body>/*ˇ
 7108        "#
 7109        .unindent(),
 7110    );
 7111}
 7112
 7113#[gpui::test]
 7114async fn test_autoclose_with_overrides(cx: &mut TestAppContext) {
 7115    init_test(cx, |_| {});
 7116
 7117    let mut cx = EditorTestContext::new(cx).await;
 7118
 7119    let rust_language = Arc::new(
 7120        Language::new(
 7121            LanguageConfig {
 7122                name: "Rust".into(),
 7123                brackets: serde_json::from_value(json!([
 7124                    { "start": "{", "end": "}", "close": true, "newline": true },
 7125                    { "start": "\"", "end": "\"", "close": true, "newline": false, "not_in": ["string"] },
 7126                ]))
 7127                .unwrap(),
 7128                autoclose_before: "})]>".into(),
 7129                ..Default::default()
 7130            },
 7131            Some(tree_sitter_rust::LANGUAGE.into()),
 7132        )
 7133        .with_override_query("(string_literal) @string")
 7134        .unwrap(),
 7135    );
 7136
 7137    cx.language_registry().add(rust_language.clone());
 7138    cx.update_buffer(|buffer, cx| {
 7139        buffer.set_language(Some(rust_language), cx);
 7140    });
 7141
 7142    cx.set_state(
 7143        &r#"
 7144            let x = ˇ
 7145        "#
 7146        .unindent(),
 7147    );
 7148
 7149    // Inserting a quotation mark. A closing quotation mark is automatically inserted.
 7150    cx.update_editor(|editor, window, cx| {
 7151        editor.handle_input("\"", window, cx);
 7152    });
 7153    cx.assert_editor_state(
 7154        &r#"
 7155            let x = "ˇ"
 7156        "#
 7157        .unindent(),
 7158    );
 7159
 7160    // Inserting another quotation mark. The cursor moves across the existing
 7161    // automatically-inserted quotation mark.
 7162    cx.update_editor(|editor, window, cx| {
 7163        editor.handle_input("\"", window, cx);
 7164    });
 7165    cx.assert_editor_state(
 7166        &r#"
 7167            let x = ""ˇ
 7168        "#
 7169        .unindent(),
 7170    );
 7171
 7172    // Reset
 7173    cx.set_state(
 7174        &r#"
 7175            let x = ˇ
 7176        "#
 7177        .unindent(),
 7178    );
 7179
 7180    // Inserting a quotation mark inside of a string. A second quotation mark is not inserted.
 7181    cx.update_editor(|editor, window, cx| {
 7182        editor.handle_input("\"", window, cx);
 7183        editor.handle_input(" ", window, cx);
 7184        editor.move_left(&Default::default(), window, cx);
 7185        editor.handle_input("\\", window, cx);
 7186        editor.handle_input("\"", window, cx);
 7187    });
 7188    cx.assert_editor_state(
 7189        &r#"
 7190            let x = "\"ˇ "
 7191        "#
 7192        .unindent(),
 7193    );
 7194
 7195    // Inserting a closing quotation mark at the position of an automatically-inserted quotation
 7196    // mark. Nothing is inserted.
 7197    cx.update_editor(|editor, window, cx| {
 7198        editor.move_right(&Default::default(), window, cx);
 7199        editor.handle_input("\"", window, cx);
 7200    });
 7201    cx.assert_editor_state(
 7202        &r#"
 7203            let x = "\" "ˇ
 7204        "#
 7205        .unindent(),
 7206    );
 7207}
 7208
 7209#[gpui::test]
 7210async fn test_surround_with_pair(cx: &mut TestAppContext) {
 7211    init_test(cx, |_| {});
 7212
 7213    let language = Arc::new(Language::new(
 7214        LanguageConfig {
 7215            brackets: BracketPairConfig {
 7216                pairs: vec![
 7217                    BracketPair {
 7218                        start: "{".to_string(),
 7219                        end: "}".to_string(),
 7220                        close: true,
 7221                        surround: true,
 7222                        newline: true,
 7223                    },
 7224                    BracketPair {
 7225                        start: "/* ".to_string(),
 7226                        end: "*/".to_string(),
 7227                        close: true,
 7228                        surround: true,
 7229                        ..Default::default()
 7230                    },
 7231                ],
 7232                ..Default::default()
 7233            },
 7234            ..Default::default()
 7235        },
 7236        Some(tree_sitter_rust::LANGUAGE.into()),
 7237    ));
 7238
 7239    let text = r#"
 7240        a
 7241        b
 7242        c
 7243    "#
 7244    .unindent();
 7245
 7246    let buffer = cx.new(|cx| Buffer::local(text, cx).with_language(language, cx));
 7247    let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 7248    let (editor, cx) = cx.add_window_view(|window, cx| build_editor(buffer, window, cx));
 7249    editor
 7250        .condition::<crate::EditorEvent>(cx, |editor, cx| !editor.buffer.read(cx).is_parsing(cx))
 7251        .await;
 7252
 7253    editor.update_in(cx, |editor, window, cx| {
 7254        editor.change_selections(None, window, cx, |s| {
 7255            s.select_display_ranges([
 7256                DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(0), 1),
 7257                DisplayPoint::new(DisplayRow(1), 0)..DisplayPoint::new(DisplayRow(1), 1),
 7258                DisplayPoint::new(DisplayRow(2), 0)..DisplayPoint::new(DisplayRow(2), 1),
 7259            ])
 7260        });
 7261
 7262        editor.handle_input("{", window, cx);
 7263        editor.handle_input("{", window, cx);
 7264        editor.handle_input("{", window, cx);
 7265        assert_eq!(
 7266            editor.text(cx),
 7267            "
 7268                {{{a}}}
 7269                {{{b}}}
 7270                {{{c}}}
 7271            "
 7272            .unindent()
 7273        );
 7274        assert_eq!(
 7275            editor.selections.display_ranges(cx),
 7276            [
 7277                DisplayPoint::new(DisplayRow(0), 3)..DisplayPoint::new(DisplayRow(0), 4),
 7278                DisplayPoint::new(DisplayRow(1), 3)..DisplayPoint::new(DisplayRow(1), 4),
 7279                DisplayPoint::new(DisplayRow(2), 3)..DisplayPoint::new(DisplayRow(2), 4)
 7280            ]
 7281        );
 7282
 7283        editor.undo(&Undo, window, cx);
 7284        editor.undo(&Undo, window, cx);
 7285        editor.undo(&Undo, window, cx);
 7286        assert_eq!(
 7287            editor.text(cx),
 7288            "
 7289                a
 7290                b
 7291                c
 7292            "
 7293            .unindent()
 7294        );
 7295        assert_eq!(
 7296            editor.selections.display_ranges(cx),
 7297            [
 7298                DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(0), 1),
 7299                DisplayPoint::new(DisplayRow(1), 0)..DisplayPoint::new(DisplayRow(1), 1),
 7300                DisplayPoint::new(DisplayRow(2), 0)..DisplayPoint::new(DisplayRow(2), 1)
 7301            ]
 7302        );
 7303
 7304        // Ensure inserting the first character of a multi-byte bracket pair
 7305        // doesn't surround the selections with the bracket.
 7306        editor.handle_input("/", window, cx);
 7307        assert_eq!(
 7308            editor.text(cx),
 7309            "
 7310                /
 7311                /
 7312                /
 7313            "
 7314            .unindent()
 7315        );
 7316        assert_eq!(
 7317            editor.selections.display_ranges(cx),
 7318            [
 7319                DisplayPoint::new(DisplayRow(0), 1)..DisplayPoint::new(DisplayRow(0), 1),
 7320                DisplayPoint::new(DisplayRow(1), 1)..DisplayPoint::new(DisplayRow(1), 1),
 7321                DisplayPoint::new(DisplayRow(2), 1)..DisplayPoint::new(DisplayRow(2), 1)
 7322            ]
 7323        );
 7324
 7325        editor.undo(&Undo, window, cx);
 7326        assert_eq!(
 7327            editor.text(cx),
 7328            "
 7329                a
 7330                b
 7331                c
 7332            "
 7333            .unindent()
 7334        );
 7335        assert_eq!(
 7336            editor.selections.display_ranges(cx),
 7337            [
 7338                DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(0), 1),
 7339                DisplayPoint::new(DisplayRow(1), 0)..DisplayPoint::new(DisplayRow(1), 1),
 7340                DisplayPoint::new(DisplayRow(2), 0)..DisplayPoint::new(DisplayRow(2), 1)
 7341            ]
 7342        );
 7343
 7344        // Ensure inserting the last character of a multi-byte bracket pair
 7345        // doesn't surround the selections with the bracket.
 7346        editor.handle_input("*", window, cx);
 7347        assert_eq!(
 7348            editor.text(cx),
 7349            "
 7350                *
 7351                *
 7352                *
 7353            "
 7354            .unindent()
 7355        );
 7356        assert_eq!(
 7357            editor.selections.display_ranges(cx),
 7358            [
 7359                DisplayPoint::new(DisplayRow(0), 1)..DisplayPoint::new(DisplayRow(0), 1),
 7360                DisplayPoint::new(DisplayRow(1), 1)..DisplayPoint::new(DisplayRow(1), 1),
 7361                DisplayPoint::new(DisplayRow(2), 1)..DisplayPoint::new(DisplayRow(2), 1)
 7362            ]
 7363        );
 7364    });
 7365}
 7366
 7367#[gpui::test]
 7368async fn test_delete_autoclose_pair(cx: &mut TestAppContext) {
 7369    init_test(cx, |_| {});
 7370
 7371    let language = Arc::new(Language::new(
 7372        LanguageConfig {
 7373            brackets: BracketPairConfig {
 7374                pairs: vec![BracketPair {
 7375                    start: "{".to_string(),
 7376                    end: "}".to_string(),
 7377                    close: true,
 7378                    surround: true,
 7379                    newline: true,
 7380                }],
 7381                ..Default::default()
 7382            },
 7383            autoclose_before: "}".to_string(),
 7384            ..Default::default()
 7385        },
 7386        Some(tree_sitter_rust::LANGUAGE.into()),
 7387    ));
 7388
 7389    let text = r#"
 7390        a
 7391        b
 7392        c
 7393    "#
 7394    .unindent();
 7395
 7396    let buffer = cx.new(|cx| Buffer::local(text, cx).with_language(language, cx));
 7397    let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 7398    let (editor, cx) = cx.add_window_view(|window, cx| build_editor(buffer, window, cx));
 7399    editor
 7400        .condition::<crate::EditorEvent>(cx, |editor, cx| !editor.buffer.read(cx).is_parsing(cx))
 7401        .await;
 7402
 7403    editor.update_in(cx, |editor, window, cx| {
 7404        editor.change_selections(None, window, cx, |s| {
 7405            s.select_ranges([
 7406                Point::new(0, 1)..Point::new(0, 1),
 7407                Point::new(1, 1)..Point::new(1, 1),
 7408                Point::new(2, 1)..Point::new(2, 1),
 7409            ])
 7410        });
 7411
 7412        editor.handle_input("{", window, cx);
 7413        editor.handle_input("{", window, cx);
 7414        editor.handle_input("_", window, cx);
 7415        assert_eq!(
 7416            editor.text(cx),
 7417            "
 7418                a{{_}}
 7419                b{{_}}
 7420                c{{_}}
 7421            "
 7422            .unindent()
 7423        );
 7424        assert_eq!(
 7425            editor.selections.ranges::<Point>(cx),
 7426            [
 7427                Point::new(0, 4)..Point::new(0, 4),
 7428                Point::new(1, 4)..Point::new(1, 4),
 7429                Point::new(2, 4)..Point::new(2, 4)
 7430            ]
 7431        );
 7432
 7433        editor.backspace(&Default::default(), window, cx);
 7434        editor.backspace(&Default::default(), window, cx);
 7435        assert_eq!(
 7436            editor.text(cx),
 7437            "
 7438                a{}
 7439                b{}
 7440                c{}
 7441            "
 7442            .unindent()
 7443        );
 7444        assert_eq!(
 7445            editor.selections.ranges::<Point>(cx),
 7446            [
 7447                Point::new(0, 2)..Point::new(0, 2),
 7448                Point::new(1, 2)..Point::new(1, 2),
 7449                Point::new(2, 2)..Point::new(2, 2)
 7450            ]
 7451        );
 7452
 7453        editor.delete_to_previous_word_start(&Default::default(), window, cx);
 7454        assert_eq!(
 7455            editor.text(cx),
 7456            "
 7457                a
 7458                b
 7459                c
 7460            "
 7461            .unindent()
 7462        );
 7463        assert_eq!(
 7464            editor.selections.ranges::<Point>(cx),
 7465            [
 7466                Point::new(0, 1)..Point::new(0, 1),
 7467                Point::new(1, 1)..Point::new(1, 1),
 7468                Point::new(2, 1)..Point::new(2, 1)
 7469            ]
 7470        );
 7471    });
 7472}
 7473
 7474#[gpui::test]
 7475async fn test_always_treat_brackets_as_autoclosed_delete(cx: &mut TestAppContext) {
 7476    init_test(cx, |settings| {
 7477        settings.defaults.always_treat_brackets_as_autoclosed = Some(true);
 7478    });
 7479
 7480    let mut cx = EditorTestContext::new(cx).await;
 7481
 7482    let language = Arc::new(Language::new(
 7483        LanguageConfig {
 7484            brackets: BracketPairConfig {
 7485                pairs: vec![
 7486                    BracketPair {
 7487                        start: "{".to_string(),
 7488                        end: "}".to_string(),
 7489                        close: true,
 7490                        surround: true,
 7491                        newline: true,
 7492                    },
 7493                    BracketPair {
 7494                        start: "(".to_string(),
 7495                        end: ")".to_string(),
 7496                        close: true,
 7497                        surround: true,
 7498                        newline: true,
 7499                    },
 7500                    BracketPair {
 7501                        start: "[".to_string(),
 7502                        end: "]".to_string(),
 7503                        close: false,
 7504                        surround: true,
 7505                        newline: true,
 7506                    },
 7507                ],
 7508                ..Default::default()
 7509            },
 7510            autoclose_before: "})]".to_string(),
 7511            ..Default::default()
 7512        },
 7513        Some(tree_sitter_rust::LANGUAGE.into()),
 7514    ));
 7515
 7516    cx.language_registry().add(language.clone());
 7517    cx.update_buffer(|buffer, cx| {
 7518        buffer.set_language(Some(language), cx);
 7519    });
 7520
 7521    cx.set_state(
 7522        &"
 7523            {(ˇ)}
 7524            [[ˇ]]
 7525            {(ˇ)}
 7526        "
 7527        .unindent(),
 7528    );
 7529
 7530    cx.update_editor(|editor, window, cx| {
 7531        editor.backspace(&Default::default(), window, cx);
 7532        editor.backspace(&Default::default(), window, cx);
 7533    });
 7534
 7535    cx.assert_editor_state(
 7536        &"
 7537            ˇ
 7538            ˇ]]
 7539            ˇ
 7540        "
 7541        .unindent(),
 7542    );
 7543
 7544    cx.update_editor(|editor, window, cx| {
 7545        editor.handle_input("{", window, cx);
 7546        editor.handle_input("{", window, cx);
 7547        editor.move_right(&MoveRight, window, cx);
 7548        editor.move_right(&MoveRight, window, cx);
 7549        editor.move_left(&MoveLeft, window, cx);
 7550        editor.move_left(&MoveLeft, window, cx);
 7551        editor.backspace(&Default::default(), window, cx);
 7552    });
 7553
 7554    cx.assert_editor_state(
 7555        &"
 7556            {ˇ}
 7557            {ˇ}]]
 7558            {ˇ}
 7559        "
 7560        .unindent(),
 7561    );
 7562
 7563    cx.update_editor(|editor, window, cx| {
 7564        editor.backspace(&Default::default(), window, cx);
 7565    });
 7566
 7567    cx.assert_editor_state(
 7568        &"
 7569            ˇ
 7570            ˇ]]
 7571            ˇ
 7572        "
 7573        .unindent(),
 7574    );
 7575}
 7576
 7577#[gpui::test]
 7578async fn test_auto_replace_emoji_shortcode(cx: &mut TestAppContext) {
 7579    init_test(cx, |_| {});
 7580
 7581    let language = Arc::new(Language::new(
 7582        LanguageConfig::default(),
 7583        Some(tree_sitter_rust::LANGUAGE.into()),
 7584    ));
 7585
 7586    let buffer = cx.new(|cx| Buffer::local("", cx).with_language(language, cx));
 7587    let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 7588    let (editor, cx) = cx.add_window_view(|window, cx| build_editor(buffer, window, cx));
 7589    editor
 7590        .condition::<crate::EditorEvent>(cx, |editor, cx| !editor.buffer.read(cx).is_parsing(cx))
 7591        .await;
 7592
 7593    editor.update_in(cx, |editor, window, cx| {
 7594        editor.set_auto_replace_emoji_shortcode(true);
 7595
 7596        editor.handle_input("Hello ", window, cx);
 7597        editor.handle_input(":wave", window, cx);
 7598        assert_eq!(editor.text(cx), "Hello :wave".unindent());
 7599
 7600        editor.handle_input(":", window, cx);
 7601        assert_eq!(editor.text(cx), "Hello 👋".unindent());
 7602
 7603        editor.handle_input(" :smile", window, cx);
 7604        assert_eq!(editor.text(cx), "Hello 👋 :smile".unindent());
 7605
 7606        editor.handle_input(":", window, cx);
 7607        assert_eq!(editor.text(cx), "Hello 👋 😄".unindent());
 7608
 7609        // Ensure shortcode gets replaced when it is part of a word that only consists of emojis
 7610        editor.handle_input(":wave", window, cx);
 7611        assert_eq!(editor.text(cx), "Hello 👋 😄:wave".unindent());
 7612
 7613        editor.handle_input(":", window, cx);
 7614        assert_eq!(editor.text(cx), "Hello 👋 😄👋".unindent());
 7615
 7616        editor.handle_input(":1", window, cx);
 7617        assert_eq!(editor.text(cx), "Hello 👋 😄👋:1".unindent());
 7618
 7619        editor.handle_input(":", window, cx);
 7620        assert_eq!(editor.text(cx), "Hello 👋 😄👋:1:".unindent());
 7621
 7622        // Ensure shortcode does not get replaced when it is part of a word
 7623        editor.handle_input(" Test:wave", window, cx);
 7624        assert_eq!(editor.text(cx), "Hello 👋 😄👋:1: Test:wave".unindent());
 7625
 7626        editor.handle_input(":", window, cx);
 7627        assert_eq!(editor.text(cx), "Hello 👋 😄👋:1: Test:wave:".unindent());
 7628
 7629        editor.set_auto_replace_emoji_shortcode(false);
 7630
 7631        // Ensure shortcode does not get replaced when auto replace is off
 7632        editor.handle_input(" :wave", window, cx);
 7633        assert_eq!(
 7634            editor.text(cx),
 7635            "Hello 👋 😄👋:1: Test:wave: :wave".unindent()
 7636        );
 7637
 7638        editor.handle_input(":", window, cx);
 7639        assert_eq!(
 7640            editor.text(cx),
 7641            "Hello 👋 😄👋:1: Test:wave: :wave:".unindent()
 7642        );
 7643    });
 7644}
 7645
 7646#[gpui::test]
 7647async fn test_snippet_placeholder_choices(cx: &mut TestAppContext) {
 7648    init_test(cx, |_| {});
 7649
 7650    let (text, insertion_ranges) = marked_text_ranges(
 7651        indoc! {"
 7652            ˇ
 7653        "},
 7654        false,
 7655    );
 7656
 7657    let buffer = cx.update(|cx| MultiBuffer::build_simple(&text, cx));
 7658    let (editor, cx) = cx.add_window_view(|window, cx| build_editor(buffer, window, cx));
 7659
 7660    _ = editor.update_in(cx, |editor, window, cx| {
 7661        let snippet = Snippet::parse("type ${1|,i32,u32|} = $2").unwrap();
 7662
 7663        editor
 7664            .insert_snippet(&insertion_ranges, snippet, window, cx)
 7665            .unwrap();
 7666
 7667        fn assert(editor: &mut Editor, cx: &mut Context<Editor>, marked_text: &str) {
 7668            let (expected_text, selection_ranges) = marked_text_ranges(marked_text, false);
 7669            assert_eq!(editor.text(cx), expected_text);
 7670            assert_eq!(editor.selections.ranges::<usize>(cx), selection_ranges);
 7671        }
 7672
 7673        assert(
 7674            editor,
 7675            cx,
 7676            indoc! {"
 7677            type «» =•
 7678            "},
 7679        );
 7680
 7681        assert!(editor.context_menu_visible(), "There should be a matches");
 7682    });
 7683}
 7684
 7685#[gpui::test]
 7686async fn test_snippets(cx: &mut TestAppContext) {
 7687    init_test(cx, |_| {});
 7688
 7689    let (text, insertion_ranges) = marked_text_ranges(
 7690        indoc! {"
 7691            a.ˇ b
 7692            a.ˇ b
 7693            a.ˇ b
 7694        "},
 7695        false,
 7696    );
 7697
 7698    let buffer = cx.update(|cx| MultiBuffer::build_simple(&text, cx));
 7699    let (editor, cx) = cx.add_window_view(|window, cx| build_editor(buffer, window, cx));
 7700
 7701    editor.update_in(cx, |editor, window, cx| {
 7702        let snippet = Snippet::parse("f(${1:one}, ${2:two}, ${1:three})$0").unwrap();
 7703
 7704        editor
 7705            .insert_snippet(&insertion_ranges, snippet, window, cx)
 7706            .unwrap();
 7707
 7708        fn assert(editor: &mut Editor, cx: &mut Context<Editor>, marked_text: &str) {
 7709            let (expected_text, selection_ranges) = marked_text_ranges(marked_text, false);
 7710            assert_eq!(editor.text(cx), expected_text);
 7711            assert_eq!(editor.selections.ranges::<usize>(cx), selection_ranges);
 7712        }
 7713
 7714        assert(
 7715            editor,
 7716            cx,
 7717            indoc! {"
 7718                a.f(«one», two, «three») b
 7719                a.f(«one», two, «three») b
 7720                a.f(«one», two, «three») b
 7721            "},
 7722        );
 7723
 7724        // Can't move earlier than the first tab stop
 7725        assert!(!editor.move_to_prev_snippet_tabstop(window, cx));
 7726        assert(
 7727            editor,
 7728            cx,
 7729            indoc! {"
 7730                a.f(«one», two, «three») b
 7731                a.f(«one», two, «three») b
 7732                a.f(«one», two, «three») b
 7733            "},
 7734        );
 7735
 7736        assert!(editor.move_to_next_snippet_tabstop(window, cx));
 7737        assert(
 7738            editor,
 7739            cx,
 7740            indoc! {"
 7741                a.f(one, «two», three) b
 7742                a.f(one, «two», three) b
 7743                a.f(one, «two», three) b
 7744            "},
 7745        );
 7746
 7747        editor.move_to_prev_snippet_tabstop(window, cx);
 7748        assert(
 7749            editor,
 7750            cx,
 7751            indoc! {"
 7752                a.f(«one», two, «three») b
 7753                a.f(«one», two, «three») b
 7754                a.f(«one», two, «three») b
 7755            "},
 7756        );
 7757
 7758        assert!(editor.move_to_next_snippet_tabstop(window, cx));
 7759        assert(
 7760            editor,
 7761            cx,
 7762            indoc! {"
 7763                a.f(one, «two», three) b
 7764                a.f(one, «two», three) b
 7765                a.f(one, «two», three) b
 7766            "},
 7767        );
 7768        assert!(editor.move_to_next_snippet_tabstop(window, cx));
 7769        assert(
 7770            editor,
 7771            cx,
 7772            indoc! {"
 7773                a.f(one, two, three)ˇ b
 7774                a.f(one, two, three)ˇ b
 7775                a.f(one, two, three)ˇ b
 7776            "},
 7777        );
 7778
 7779        // As soon as the last tab stop is reached, snippet state is gone
 7780        editor.move_to_prev_snippet_tabstop(window, cx);
 7781        assert(
 7782            editor,
 7783            cx,
 7784            indoc! {"
 7785                a.f(one, two, three)ˇ b
 7786                a.f(one, two, three)ˇ b
 7787                a.f(one, two, three)ˇ b
 7788            "},
 7789        );
 7790    });
 7791}
 7792
 7793#[gpui::test]
 7794async fn test_document_format_during_save(cx: &mut TestAppContext) {
 7795    init_test(cx, |_| {});
 7796
 7797    let fs = FakeFs::new(cx.executor());
 7798    fs.insert_file(path!("/file.rs"), Default::default()).await;
 7799
 7800    let project = Project::test(fs, [path!("/file.rs").as_ref()], cx).await;
 7801
 7802    let language_registry = project.read_with(cx, |project, _| project.languages().clone());
 7803    language_registry.add(rust_lang());
 7804    let mut fake_servers = language_registry.register_fake_lsp(
 7805        "Rust",
 7806        FakeLspAdapter {
 7807            capabilities: lsp::ServerCapabilities {
 7808                document_formatting_provider: Some(lsp::OneOf::Left(true)),
 7809                ..Default::default()
 7810            },
 7811            ..Default::default()
 7812        },
 7813    );
 7814
 7815    let buffer = project
 7816        .update(cx, |project, cx| {
 7817            project.open_local_buffer(path!("/file.rs"), cx)
 7818        })
 7819        .await
 7820        .unwrap();
 7821
 7822    let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 7823    let (editor, cx) = cx.add_window_view(|window, cx| {
 7824        build_editor_with_project(project.clone(), buffer, window, cx)
 7825    });
 7826    editor.update_in(cx, |editor, window, cx| {
 7827        editor.set_text("one\ntwo\nthree\n", window, cx)
 7828    });
 7829    assert!(cx.read(|cx| editor.is_dirty(cx)));
 7830
 7831    cx.executor().start_waiting();
 7832    let fake_server = fake_servers.next().await.unwrap();
 7833
 7834    {
 7835        fake_server.set_request_handler::<lsp::request::Formatting, _, _>(
 7836            move |params, _| async move {
 7837                assert_eq!(
 7838                    params.text_document.uri,
 7839                    lsp::Url::from_file_path(path!("/file.rs")).unwrap()
 7840                );
 7841                assert_eq!(params.options.tab_size, 4);
 7842                Ok(Some(vec![lsp::TextEdit::new(
 7843                    lsp::Range::new(lsp::Position::new(0, 3), lsp::Position::new(1, 0)),
 7844                    ", ".to_string(),
 7845                )]))
 7846            },
 7847        );
 7848        let save = editor
 7849            .update_in(cx, |editor, window, cx| {
 7850                editor.save(true, project.clone(), window, cx)
 7851            })
 7852            .unwrap();
 7853        cx.executor().start_waiting();
 7854        save.await;
 7855
 7856        assert_eq!(
 7857            editor.update(cx, |editor, cx| editor.text(cx)),
 7858            "one, two\nthree\n"
 7859        );
 7860        assert!(!cx.read(|cx| editor.is_dirty(cx)));
 7861    }
 7862
 7863    {
 7864        editor.update_in(cx, |editor, window, cx| {
 7865            editor.set_text("one\ntwo\nthree\n", window, cx)
 7866        });
 7867        assert!(cx.read(|cx| editor.is_dirty(cx)));
 7868
 7869        // Ensure we can still save even if formatting hangs.
 7870        fake_server.set_request_handler::<lsp::request::Formatting, _, _>(
 7871            move |params, _| async move {
 7872                assert_eq!(
 7873                    params.text_document.uri,
 7874                    lsp::Url::from_file_path(path!("/file.rs")).unwrap()
 7875                );
 7876                futures::future::pending::<()>().await;
 7877                unreachable!()
 7878            },
 7879        );
 7880        let save = editor
 7881            .update_in(cx, |editor, window, cx| {
 7882                editor.save(true, project.clone(), window, cx)
 7883            })
 7884            .unwrap();
 7885        cx.executor().advance_clock(super::FORMAT_TIMEOUT);
 7886        cx.executor().start_waiting();
 7887        save.await;
 7888        assert_eq!(
 7889            editor.update(cx, |editor, cx| editor.text(cx)),
 7890            "one\ntwo\nthree\n"
 7891        );
 7892    }
 7893
 7894    // For non-dirty buffer, no formatting request should be sent
 7895    {
 7896        assert!(!cx.read(|cx| editor.is_dirty(cx)));
 7897
 7898        fake_server.set_request_handler::<lsp::request::Formatting, _, _>(move |_, _| async move {
 7899            panic!("Should not be invoked on non-dirty buffer");
 7900        });
 7901        let save = editor
 7902            .update_in(cx, |editor, window, cx| {
 7903                editor.save(true, project.clone(), window, cx)
 7904            })
 7905            .unwrap();
 7906        cx.executor().start_waiting();
 7907        save.await;
 7908    }
 7909
 7910    // Set rust language override and assert overridden tabsize is sent to language server
 7911    update_test_language_settings(cx, |settings| {
 7912        settings.languages.insert(
 7913            "Rust".into(),
 7914            LanguageSettingsContent {
 7915                tab_size: NonZeroU32::new(8),
 7916                ..Default::default()
 7917            },
 7918        );
 7919    });
 7920
 7921    {
 7922        editor.update_in(cx, |editor, window, cx| {
 7923            editor.set_text("somehting_new\n", window, cx)
 7924        });
 7925        assert!(cx.read(|cx| editor.is_dirty(cx)));
 7926        let _formatting_request_signal = fake_server
 7927            .set_request_handler::<lsp::request::Formatting, _, _>(move |params, _| async move {
 7928                assert_eq!(
 7929                    params.text_document.uri,
 7930                    lsp::Url::from_file_path(path!("/file.rs")).unwrap()
 7931                );
 7932                assert_eq!(params.options.tab_size, 8);
 7933                Ok(Some(vec![]))
 7934            });
 7935        let save = editor
 7936            .update_in(cx, |editor, window, cx| {
 7937                editor.save(true, project.clone(), window, cx)
 7938            })
 7939            .unwrap();
 7940        cx.executor().start_waiting();
 7941        save.await;
 7942    }
 7943}
 7944
 7945#[gpui::test]
 7946async fn test_multibuffer_format_during_save(cx: &mut TestAppContext) {
 7947    init_test(cx, |_| {});
 7948
 7949    let cols = 4;
 7950    let rows = 10;
 7951    let sample_text_1 = sample_text(rows, cols, 'a');
 7952    assert_eq!(
 7953        sample_text_1,
 7954        "aaaa\nbbbb\ncccc\ndddd\neeee\nffff\ngggg\nhhhh\niiii\njjjj"
 7955    );
 7956    let sample_text_2 = sample_text(rows, cols, 'l');
 7957    assert_eq!(
 7958        sample_text_2,
 7959        "llll\nmmmm\nnnnn\noooo\npppp\nqqqq\nrrrr\nssss\ntttt\nuuuu"
 7960    );
 7961    let sample_text_3 = sample_text(rows, cols, 'v');
 7962    assert_eq!(
 7963        sample_text_3,
 7964        "vvvv\nwwww\nxxxx\nyyyy\nzzzz\n{{{{\n||||\n}}}}\n~~~~\n\u{7f}\u{7f}\u{7f}\u{7f}"
 7965    );
 7966
 7967    let fs = FakeFs::new(cx.executor());
 7968    fs.insert_tree(
 7969        path!("/a"),
 7970        json!({
 7971            "main.rs": sample_text_1,
 7972            "other.rs": sample_text_2,
 7973            "lib.rs": sample_text_3,
 7974        }),
 7975    )
 7976    .await;
 7977
 7978    let project = Project::test(fs, [path!("/a").as_ref()], cx).await;
 7979    let workspace = cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
 7980    let cx = &mut VisualTestContext::from_window(*workspace.deref(), cx);
 7981
 7982    let language_registry = project.read_with(cx, |project, _| project.languages().clone());
 7983    language_registry.add(rust_lang());
 7984    let mut fake_servers = language_registry.register_fake_lsp(
 7985        "Rust",
 7986        FakeLspAdapter {
 7987            capabilities: lsp::ServerCapabilities {
 7988                document_formatting_provider: Some(lsp::OneOf::Left(true)),
 7989                ..Default::default()
 7990            },
 7991            ..Default::default()
 7992        },
 7993    );
 7994
 7995    let worktree = project.update(cx, |project, cx| {
 7996        let mut worktrees = project.worktrees(cx).collect::<Vec<_>>();
 7997        assert_eq!(worktrees.len(), 1);
 7998        worktrees.pop().unwrap()
 7999    });
 8000    let worktree_id = worktree.update(cx, |worktree, _| worktree.id());
 8001
 8002    let buffer_1 = project
 8003        .update(cx, |project, cx| {
 8004            project.open_buffer((worktree_id, "main.rs"), cx)
 8005        })
 8006        .await
 8007        .unwrap();
 8008    let buffer_2 = project
 8009        .update(cx, |project, cx| {
 8010            project.open_buffer((worktree_id, "other.rs"), cx)
 8011        })
 8012        .await
 8013        .unwrap();
 8014    let buffer_3 = project
 8015        .update(cx, |project, cx| {
 8016            project.open_buffer((worktree_id, "lib.rs"), cx)
 8017        })
 8018        .await
 8019        .unwrap();
 8020
 8021    let multi_buffer = cx.new(|cx| {
 8022        let mut multi_buffer = MultiBuffer::new(ReadWrite);
 8023        multi_buffer.push_excerpts(
 8024            buffer_1.clone(),
 8025            [
 8026                ExcerptRange::new(Point::new(0, 0)..Point::new(3, 0)),
 8027                ExcerptRange::new(Point::new(5, 0)..Point::new(7, 0)),
 8028                ExcerptRange::new(Point::new(9, 0)..Point::new(10, 4)),
 8029            ],
 8030            cx,
 8031        );
 8032        multi_buffer.push_excerpts(
 8033            buffer_2.clone(),
 8034            [
 8035                ExcerptRange::new(Point::new(0, 0)..Point::new(3, 0)),
 8036                ExcerptRange::new(Point::new(5, 0)..Point::new(7, 0)),
 8037                ExcerptRange::new(Point::new(9, 0)..Point::new(10, 4)),
 8038            ],
 8039            cx,
 8040        );
 8041        multi_buffer.push_excerpts(
 8042            buffer_3.clone(),
 8043            [
 8044                ExcerptRange::new(Point::new(0, 0)..Point::new(3, 0)),
 8045                ExcerptRange::new(Point::new(5, 0)..Point::new(7, 0)),
 8046                ExcerptRange::new(Point::new(9, 0)..Point::new(10, 4)),
 8047            ],
 8048            cx,
 8049        );
 8050        multi_buffer
 8051    });
 8052    let multi_buffer_editor = cx.new_window_entity(|window, cx| {
 8053        Editor::new(
 8054            EditorMode::full(),
 8055            multi_buffer,
 8056            Some(project.clone()),
 8057            window,
 8058            cx,
 8059        )
 8060    });
 8061
 8062    multi_buffer_editor.update_in(cx, |editor, window, cx| {
 8063        editor.change_selections(Some(Autoscroll::Next), window, cx, |s| {
 8064            s.select_ranges(Some(1..2))
 8065        });
 8066        editor.insert("|one|two|three|", window, cx);
 8067    });
 8068    assert!(cx.read(|cx| multi_buffer_editor.is_dirty(cx)));
 8069    multi_buffer_editor.update_in(cx, |editor, window, cx| {
 8070        editor.change_selections(Some(Autoscroll::Next), window, cx, |s| {
 8071            s.select_ranges(Some(60..70))
 8072        });
 8073        editor.insert("|four|five|six|", window, cx);
 8074    });
 8075    assert!(cx.read(|cx| multi_buffer_editor.is_dirty(cx)));
 8076
 8077    // First two buffers should be edited, but not the third one.
 8078    assert_eq!(
 8079        multi_buffer_editor.update(cx, |editor, cx| editor.text(cx)),
 8080        "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}",
 8081    );
 8082    buffer_1.update(cx, |buffer, _| {
 8083        assert!(buffer.is_dirty());
 8084        assert_eq!(
 8085            buffer.text(),
 8086            "a|one|two|three|aa\nbbbb\ncccc\ndddd\neeee\nffff\ngggg\nhhhh\niiii\njjjj",
 8087        )
 8088    });
 8089    buffer_2.update(cx, |buffer, _| {
 8090        assert!(buffer.is_dirty());
 8091        assert_eq!(
 8092            buffer.text(),
 8093            "llll\nmmmm\nnnnn|four|five|six|oooo\npppp\nr\nssss\ntttt\nuuuu",
 8094        )
 8095    });
 8096    buffer_3.update(cx, |buffer, _| {
 8097        assert!(!buffer.is_dirty());
 8098        assert_eq!(buffer.text(), sample_text_3,)
 8099    });
 8100    cx.executor().run_until_parked();
 8101
 8102    cx.executor().start_waiting();
 8103    let save = multi_buffer_editor
 8104        .update_in(cx, |editor, window, cx| {
 8105            editor.save(true, project.clone(), window, cx)
 8106        })
 8107        .unwrap();
 8108
 8109    let fake_server = fake_servers.next().await.unwrap();
 8110    fake_server
 8111        .server
 8112        .on_request::<lsp::request::Formatting, _, _>(move |params, _| async move {
 8113            Ok(Some(vec![lsp::TextEdit::new(
 8114                lsp::Range::new(lsp::Position::new(0, 3), lsp::Position::new(1, 0)),
 8115                format!("[{} formatted]", params.text_document.uri),
 8116            )]))
 8117        })
 8118        .detach();
 8119    save.await;
 8120
 8121    // After multibuffer saving, only first two buffers should be reformatted, but not the third one (as it was not dirty).
 8122    assert!(cx.read(|cx| !multi_buffer_editor.is_dirty(cx)));
 8123    assert_eq!(
 8124        multi_buffer_editor.update(cx, |editor, cx| editor.text(cx)),
 8125        uri!(
 8126            "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}"
 8127        ),
 8128    );
 8129    buffer_1.update(cx, |buffer, _| {
 8130        assert!(!buffer.is_dirty());
 8131        assert_eq!(
 8132            buffer.text(),
 8133            uri!("a|o[file:///a/main.rs formatted]bbbb\ncccc\ndddd\neeee\nffff\ngggg\nhhhh\niiii\njjjj\n"),
 8134        )
 8135    });
 8136    buffer_2.update(cx, |buffer, _| {
 8137        assert!(!buffer.is_dirty());
 8138        assert_eq!(
 8139            buffer.text(),
 8140            uri!("lll[file:///a/other.rs formatted]mmmm\nnnnn|four|five|six|oooo\npppp\nr\nssss\ntttt\nuuuu\n"),
 8141        )
 8142    });
 8143    buffer_3.update(cx, |buffer, _| {
 8144        assert!(!buffer.is_dirty());
 8145        assert_eq!(buffer.text(), sample_text_3,)
 8146    });
 8147}
 8148
 8149#[gpui::test]
 8150async fn test_range_format_during_save(cx: &mut TestAppContext) {
 8151    init_test(cx, |_| {});
 8152
 8153    let fs = FakeFs::new(cx.executor());
 8154    fs.insert_file(path!("/file.rs"), Default::default()).await;
 8155
 8156    let project = Project::test(fs, [path!("/").as_ref()], cx).await;
 8157
 8158    let language_registry = project.read_with(cx, |project, _| project.languages().clone());
 8159    language_registry.add(rust_lang());
 8160    let mut fake_servers = language_registry.register_fake_lsp(
 8161        "Rust",
 8162        FakeLspAdapter {
 8163            capabilities: lsp::ServerCapabilities {
 8164                document_range_formatting_provider: Some(lsp::OneOf::Left(true)),
 8165                ..Default::default()
 8166            },
 8167            ..Default::default()
 8168        },
 8169    );
 8170
 8171    let buffer = project
 8172        .update(cx, |project, cx| {
 8173            project.open_local_buffer(path!("/file.rs"), cx)
 8174        })
 8175        .await
 8176        .unwrap();
 8177
 8178    let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 8179    let (editor, cx) = cx.add_window_view(|window, cx| {
 8180        build_editor_with_project(project.clone(), buffer, window, cx)
 8181    });
 8182    editor.update_in(cx, |editor, window, cx| {
 8183        editor.set_text("one\ntwo\nthree\n", window, cx)
 8184    });
 8185    assert!(cx.read(|cx| editor.is_dirty(cx)));
 8186
 8187    cx.executor().start_waiting();
 8188    let fake_server = fake_servers.next().await.unwrap();
 8189
 8190    let save = editor
 8191        .update_in(cx, |editor, window, cx| {
 8192            editor.save(true, project.clone(), window, cx)
 8193        })
 8194        .unwrap();
 8195    fake_server
 8196        .set_request_handler::<lsp::request::RangeFormatting, _, _>(move |params, _| async move {
 8197            assert_eq!(
 8198                params.text_document.uri,
 8199                lsp::Url::from_file_path(path!("/file.rs")).unwrap()
 8200            );
 8201            assert_eq!(params.options.tab_size, 4);
 8202            Ok(Some(vec![lsp::TextEdit::new(
 8203                lsp::Range::new(lsp::Position::new(0, 3), lsp::Position::new(1, 0)),
 8204                ", ".to_string(),
 8205            )]))
 8206        })
 8207        .next()
 8208        .await;
 8209    cx.executor().start_waiting();
 8210    save.await;
 8211    assert_eq!(
 8212        editor.update(cx, |editor, cx| editor.text(cx)),
 8213        "one, two\nthree\n"
 8214    );
 8215    assert!(!cx.read(|cx| editor.is_dirty(cx)));
 8216
 8217    editor.update_in(cx, |editor, window, cx| {
 8218        editor.set_text("one\ntwo\nthree\n", window, cx)
 8219    });
 8220    assert!(cx.read(|cx| editor.is_dirty(cx)));
 8221
 8222    // Ensure we can still save even if formatting hangs.
 8223    fake_server.set_request_handler::<lsp::request::RangeFormatting, _, _>(
 8224        move |params, _| async move {
 8225            assert_eq!(
 8226                params.text_document.uri,
 8227                lsp::Url::from_file_path(path!("/file.rs")).unwrap()
 8228            );
 8229            futures::future::pending::<()>().await;
 8230            unreachable!()
 8231        },
 8232    );
 8233    let save = editor
 8234        .update_in(cx, |editor, window, cx| {
 8235            editor.save(true, project.clone(), window, cx)
 8236        })
 8237        .unwrap();
 8238    cx.executor().advance_clock(super::FORMAT_TIMEOUT);
 8239    cx.executor().start_waiting();
 8240    save.await;
 8241    assert_eq!(
 8242        editor.update(cx, |editor, cx| editor.text(cx)),
 8243        "one\ntwo\nthree\n"
 8244    );
 8245    assert!(!cx.read(|cx| editor.is_dirty(cx)));
 8246
 8247    // For non-dirty buffer, no formatting request should be sent
 8248    let save = editor
 8249        .update_in(cx, |editor, window, cx| {
 8250            editor.save(true, project.clone(), window, cx)
 8251        })
 8252        .unwrap();
 8253    let _pending_format_request = fake_server
 8254        .set_request_handler::<lsp::request::RangeFormatting, _, _>(move |_, _| async move {
 8255            panic!("Should not be invoked on non-dirty buffer");
 8256        })
 8257        .next();
 8258    cx.executor().start_waiting();
 8259    save.await;
 8260
 8261    // Set Rust language override and assert overridden tabsize is sent to language server
 8262    update_test_language_settings(cx, |settings| {
 8263        settings.languages.insert(
 8264            "Rust".into(),
 8265            LanguageSettingsContent {
 8266                tab_size: NonZeroU32::new(8),
 8267                ..Default::default()
 8268            },
 8269        );
 8270    });
 8271
 8272    editor.update_in(cx, |editor, window, cx| {
 8273        editor.set_text("somehting_new\n", window, cx)
 8274    });
 8275    assert!(cx.read(|cx| editor.is_dirty(cx)));
 8276    let save = editor
 8277        .update_in(cx, |editor, window, cx| {
 8278            editor.save(true, project.clone(), window, cx)
 8279        })
 8280        .unwrap();
 8281    fake_server
 8282        .set_request_handler::<lsp::request::RangeFormatting, _, _>(move |params, _| async move {
 8283            assert_eq!(
 8284                params.text_document.uri,
 8285                lsp::Url::from_file_path(path!("/file.rs")).unwrap()
 8286            );
 8287            assert_eq!(params.options.tab_size, 8);
 8288            Ok(Some(vec![]))
 8289        })
 8290        .next()
 8291        .await;
 8292    cx.executor().start_waiting();
 8293    save.await;
 8294}
 8295
 8296#[gpui::test]
 8297async fn test_document_format_manual_trigger(cx: &mut TestAppContext) {
 8298    init_test(cx, |settings| {
 8299        settings.defaults.formatter = Some(language_settings::SelectedFormatter::List(
 8300            FormatterList(vec![Formatter::LanguageServer { name: None }].into()),
 8301        ))
 8302    });
 8303
 8304    let fs = FakeFs::new(cx.executor());
 8305    fs.insert_file(path!("/file.rs"), Default::default()).await;
 8306
 8307    let project = Project::test(fs, [path!("/").as_ref()], cx).await;
 8308
 8309    let language_registry = project.read_with(cx, |project, _| project.languages().clone());
 8310    language_registry.add(Arc::new(Language::new(
 8311        LanguageConfig {
 8312            name: "Rust".into(),
 8313            matcher: LanguageMatcher {
 8314                path_suffixes: vec!["rs".to_string()],
 8315                ..Default::default()
 8316            },
 8317            ..LanguageConfig::default()
 8318        },
 8319        Some(tree_sitter_rust::LANGUAGE.into()),
 8320    )));
 8321    update_test_language_settings(cx, |settings| {
 8322        // Enable Prettier formatting for the same buffer, and ensure
 8323        // LSP is called instead of Prettier.
 8324        settings.defaults.prettier = Some(PrettierSettings {
 8325            allowed: true,
 8326            ..PrettierSettings::default()
 8327        });
 8328    });
 8329    let mut fake_servers = language_registry.register_fake_lsp(
 8330        "Rust",
 8331        FakeLspAdapter {
 8332            capabilities: lsp::ServerCapabilities {
 8333                document_formatting_provider: Some(lsp::OneOf::Left(true)),
 8334                ..Default::default()
 8335            },
 8336            ..Default::default()
 8337        },
 8338    );
 8339
 8340    let buffer = project
 8341        .update(cx, |project, cx| {
 8342            project.open_local_buffer(path!("/file.rs"), cx)
 8343        })
 8344        .await
 8345        .unwrap();
 8346
 8347    let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 8348    let (editor, cx) = cx.add_window_view(|window, cx| {
 8349        build_editor_with_project(project.clone(), buffer, window, cx)
 8350    });
 8351    editor.update_in(cx, |editor, window, cx| {
 8352        editor.set_text("one\ntwo\nthree\n", window, cx)
 8353    });
 8354
 8355    cx.executor().start_waiting();
 8356    let fake_server = fake_servers.next().await.unwrap();
 8357
 8358    let format = editor
 8359        .update_in(cx, |editor, window, cx| {
 8360            editor.perform_format(
 8361                project.clone(),
 8362                FormatTrigger::Manual,
 8363                FormatTarget::Buffers,
 8364                window,
 8365                cx,
 8366            )
 8367        })
 8368        .unwrap();
 8369    fake_server
 8370        .set_request_handler::<lsp::request::Formatting, _, _>(move |params, _| async move {
 8371            assert_eq!(
 8372                params.text_document.uri,
 8373                lsp::Url::from_file_path(path!("/file.rs")).unwrap()
 8374            );
 8375            assert_eq!(params.options.tab_size, 4);
 8376            Ok(Some(vec![lsp::TextEdit::new(
 8377                lsp::Range::new(lsp::Position::new(0, 3), lsp::Position::new(1, 0)),
 8378                ", ".to_string(),
 8379            )]))
 8380        })
 8381        .next()
 8382        .await;
 8383    cx.executor().start_waiting();
 8384    format.await;
 8385    assert_eq!(
 8386        editor.update(cx, |editor, cx| editor.text(cx)),
 8387        "one, two\nthree\n"
 8388    );
 8389
 8390    editor.update_in(cx, |editor, window, cx| {
 8391        editor.set_text("one\ntwo\nthree\n", window, cx)
 8392    });
 8393    // Ensure we don't lock if formatting hangs.
 8394    fake_server.set_request_handler::<lsp::request::Formatting, _, _>(
 8395        move |params, _| async move {
 8396            assert_eq!(
 8397                params.text_document.uri,
 8398                lsp::Url::from_file_path(path!("/file.rs")).unwrap()
 8399            );
 8400            futures::future::pending::<()>().await;
 8401            unreachable!()
 8402        },
 8403    );
 8404    let format = editor
 8405        .update_in(cx, |editor, window, cx| {
 8406            editor.perform_format(
 8407                project,
 8408                FormatTrigger::Manual,
 8409                FormatTarget::Buffers,
 8410                window,
 8411                cx,
 8412            )
 8413        })
 8414        .unwrap();
 8415    cx.executor().advance_clock(super::FORMAT_TIMEOUT);
 8416    cx.executor().start_waiting();
 8417    format.await;
 8418    assert_eq!(
 8419        editor.update(cx, |editor, cx| editor.text(cx)),
 8420        "one\ntwo\nthree\n"
 8421    );
 8422}
 8423
 8424#[gpui::test]
 8425async fn test_multiple_formatters(cx: &mut TestAppContext) {
 8426    init_test(cx, |settings| {
 8427        settings.defaults.remove_trailing_whitespace_on_save = Some(true);
 8428        settings.defaults.formatter =
 8429            Some(language_settings::SelectedFormatter::List(FormatterList(
 8430                vec![
 8431                    Formatter::LanguageServer { name: None },
 8432                    Formatter::CodeActions(
 8433                        [
 8434                            ("code-action-1".into(), true),
 8435                            ("code-action-2".into(), true),
 8436                        ]
 8437                        .into_iter()
 8438                        .collect(),
 8439                    ),
 8440                ]
 8441                .into(),
 8442            )))
 8443    });
 8444
 8445    let fs = FakeFs::new(cx.executor());
 8446    fs.insert_file(path!("/file.rs"), "one  \ntwo   \nthree".into())
 8447        .await;
 8448
 8449    let project = Project::test(fs, [path!("/").as_ref()], cx).await;
 8450    let language_registry = project.read_with(cx, |project, _| project.languages().clone());
 8451    language_registry.add(rust_lang());
 8452
 8453    let mut fake_servers = language_registry.register_fake_lsp(
 8454        "Rust",
 8455        FakeLspAdapter {
 8456            capabilities: lsp::ServerCapabilities {
 8457                document_formatting_provider: Some(lsp::OneOf::Left(true)),
 8458                execute_command_provider: Some(lsp::ExecuteCommandOptions {
 8459                    commands: vec!["the-command-for-code-action-1".into()],
 8460                    ..Default::default()
 8461                }),
 8462                code_action_provider: Some(lsp::CodeActionProviderCapability::Simple(true)),
 8463                ..Default::default()
 8464            },
 8465            ..Default::default()
 8466        },
 8467    );
 8468
 8469    let buffer = project
 8470        .update(cx, |project, cx| {
 8471            project.open_local_buffer(path!("/file.rs"), cx)
 8472        })
 8473        .await
 8474        .unwrap();
 8475
 8476    let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 8477    let (editor, cx) = cx.add_window_view(|window, cx| {
 8478        build_editor_with_project(project.clone(), buffer, window, cx)
 8479    });
 8480
 8481    cx.executor().start_waiting();
 8482
 8483    let fake_server = fake_servers.next().await.unwrap();
 8484    fake_server.set_request_handler::<lsp::request::Formatting, _, _>(
 8485        move |_params, _| async move {
 8486            Ok(Some(vec![lsp::TextEdit::new(
 8487                lsp::Range::new(lsp::Position::new(0, 0), lsp::Position::new(0, 0)),
 8488                "applied-formatting\n".to_string(),
 8489            )]))
 8490        },
 8491    );
 8492    fake_server.set_request_handler::<lsp::request::CodeActionRequest, _, _>(
 8493        move |params, _| async move {
 8494            assert_eq!(
 8495                params.context.only,
 8496                Some(vec!["code-action-1".into(), "code-action-2".into()])
 8497            );
 8498            let uri = lsp::Url::from_file_path(path!("/file.rs")).unwrap();
 8499            Ok(Some(vec![
 8500                lsp::CodeActionOrCommand::CodeAction(lsp::CodeAction {
 8501                    kind: Some("code-action-1".into()),
 8502                    edit: Some(lsp::WorkspaceEdit::new(
 8503                        [(
 8504                            uri.clone(),
 8505                            vec![lsp::TextEdit::new(
 8506                                lsp::Range::new(lsp::Position::new(0, 0), lsp::Position::new(0, 0)),
 8507                                "applied-code-action-1-edit\n".to_string(),
 8508                            )],
 8509                        )]
 8510                        .into_iter()
 8511                        .collect(),
 8512                    )),
 8513                    command: Some(lsp::Command {
 8514                        command: "the-command-for-code-action-1".into(),
 8515                        ..Default::default()
 8516                    }),
 8517                    ..Default::default()
 8518                }),
 8519                lsp::CodeActionOrCommand::CodeAction(lsp::CodeAction {
 8520                    kind: Some("code-action-2".into()),
 8521                    edit: Some(lsp::WorkspaceEdit::new(
 8522                        [(
 8523                            uri.clone(),
 8524                            vec![lsp::TextEdit::new(
 8525                                lsp::Range::new(lsp::Position::new(0, 0), lsp::Position::new(0, 0)),
 8526                                "applied-code-action-2-edit\n".to_string(),
 8527                            )],
 8528                        )]
 8529                        .into_iter()
 8530                        .collect(),
 8531                    )),
 8532                    ..Default::default()
 8533                }),
 8534            ]))
 8535        },
 8536    );
 8537
 8538    fake_server.set_request_handler::<lsp::request::CodeActionResolveRequest, _, _>({
 8539        move |params, _| async move { Ok(params) }
 8540    });
 8541
 8542    let command_lock = Arc::new(futures::lock::Mutex::new(()));
 8543    fake_server.set_request_handler::<lsp::request::ExecuteCommand, _, _>({
 8544        let fake = fake_server.clone();
 8545        let lock = command_lock.clone();
 8546        move |params, _| {
 8547            assert_eq!(params.command, "the-command-for-code-action-1");
 8548            let fake = fake.clone();
 8549            let lock = lock.clone();
 8550            async move {
 8551                lock.lock().await;
 8552                fake.server
 8553                    .request::<lsp::request::ApplyWorkspaceEdit>(lsp::ApplyWorkspaceEditParams {
 8554                        label: None,
 8555                        edit: lsp::WorkspaceEdit {
 8556                            changes: Some(
 8557                                [(
 8558                                    lsp::Url::from_file_path(path!("/file.rs")).unwrap(),
 8559                                    vec![lsp::TextEdit {
 8560                                        range: lsp::Range::new(
 8561                                            lsp::Position::new(0, 0),
 8562                                            lsp::Position::new(0, 0),
 8563                                        ),
 8564                                        new_text: "applied-code-action-1-command\n".into(),
 8565                                    }],
 8566                                )]
 8567                                .into_iter()
 8568                                .collect(),
 8569                            ),
 8570                            ..Default::default()
 8571                        },
 8572                    })
 8573                    .await
 8574                    .unwrap();
 8575                Ok(Some(json!(null)))
 8576            }
 8577        }
 8578    });
 8579
 8580    cx.executor().start_waiting();
 8581    editor
 8582        .update_in(cx, |editor, window, cx| {
 8583            editor.perform_format(
 8584                project.clone(),
 8585                FormatTrigger::Manual,
 8586                FormatTarget::Buffers,
 8587                window,
 8588                cx,
 8589            )
 8590        })
 8591        .unwrap()
 8592        .await;
 8593    editor.update(cx, |editor, cx| {
 8594        assert_eq!(
 8595            editor.text(cx),
 8596            r#"
 8597                applied-code-action-2-edit
 8598                applied-code-action-1-command
 8599                applied-code-action-1-edit
 8600                applied-formatting
 8601                one
 8602                two
 8603                three
 8604            "#
 8605            .unindent()
 8606        );
 8607    });
 8608
 8609    editor.update_in(cx, |editor, window, cx| {
 8610        editor.undo(&Default::default(), window, cx);
 8611        assert_eq!(editor.text(cx), "one  \ntwo   \nthree");
 8612    });
 8613
 8614    // Perform a manual edit while waiting for an LSP command
 8615    // that's being run as part of a formatting code action.
 8616    let lock_guard = command_lock.lock().await;
 8617    let format = editor
 8618        .update_in(cx, |editor, window, cx| {
 8619            editor.perform_format(
 8620                project.clone(),
 8621                FormatTrigger::Manual,
 8622                FormatTarget::Buffers,
 8623                window,
 8624                cx,
 8625            )
 8626        })
 8627        .unwrap();
 8628    cx.run_until_parked();
 8629    editor.update(cx, |editor, cx| {
 8630        assert_eq!(
 8631            editor.text(cx),
 8632            r#"
 8633                applied-code-action-1-edit
 8634                applied-formatting
 8635                one
 8636                two
 8637                three
 8638            "#
 8639            .unindent()
 8640        );
 8641
 8642        editor.buffer.update(cx, |buffer, cx| {
 8643            let ix = buffer.len(cx);
 8644            buffer.edit([(ix..ix, "edited\n")], None, cx);
 8645        });
 8646    });
 8647
 8648    // Allow the LSP command to proceed. Because the buffer was edited,
 8649    // the second code action will not be run.
 8650    drop(lock_guard);
 8651    format.await;
 8652    editor.update_in(cx, |editor, window, cx| {
 8653        assert_eq!(
 8654            editor.text(cx),
 8655            r#"
 8656                applied-code-action-1-command
 8657                applied-code-action-1-edit
 8658                applied-formatting
 8659                one
 8660                two
 8661                three
 8662                edited
 8663            "#
 8664            .unindent()
 8665        );
 8666
 8667        // The manual edit is undone first, because it is the last thing the user did
 8668        // (even though the command completed afterwards).
 8669        editor.undo(&Default::default(), window, cx);
 8670        assert_eq!(
 8671            editor.text(cx),
 8672            r#"
 8673                applied-code-action-1-command
 8674                applied-code-action-1-edit
 8675                applied-formatting
 8676                one
 8677                two
 8678                three
 8679            "#
 8680            .unindent()
 8681        );
 8682
 8683        // All the formatting (including the command, which completed after the manual edit)
 8684        // is undone together.
 8685        editor.undo(&Default::default(), window, cx);
 8686        assert_eq!(editor.text(cx), "one  \ntwo   \nthree");
 8687    });
 8688}
 8689
 8690#[gpui::test]
 8691async fn test_organize_imports_manual_trigger(cx: &mut TestAppContext) {
 8692    init_test(cx, |settings| {
 8693        settings.defaults.formatter = Some(language_settings::SelectedFormatter::List(
 8694            FormatterList(vec![Formatter::LanguageServer { name: None }].into()),
 8695        ))
 8696    });
 8697
 8698    let fs = FakeFs::new(cx.executor());
 8699    fs.insert_file(path!("/file.ts"), Default::default()).await;
 8700
 8701    let project = Project::test(fs, [path!("/").as_ref()], cx).await;
 8702
 8703    let language_registry = project.read_with(cx, |project, _| project.languages().clone());
 8704    language_registry.add(Arc::new(Language::new(
 8705        LanguageConfig {
 8706            name: "TypeScript".into(),
 8707            matcher: LanguageMatcher {
 8708                path_suffixes: vec!["ts".to_string()],
 8709                ..Default::default()
 8710            },
 8711            ..LanguageConfig::default()
 8712        },
 8713        Some(tree_sitter_typescript::LANGUAGE_TYPESCRIPT.into()),
 8714    )));
 8715    update_test_language_settings(cx, |settings| {
 8716        settings.defaults.prettier = Some(PrettierSettings {
 8717            allowed: true,
 8718            ..PrettierSettings::default()
 8719        });
 8720    });
 8721    let mut fake_servers = language_registry.register_fake_lsp(
 8722        "TypeScript",
 8723        FakeLspAdapter {
 8724            capabilities: lsp::ServerCapabilities {
 8725                code_action_provider: Some(lsp::CodeActionProviderCapability::Simple(true)),
 8726                ..Default::default()
 8727            },
 8728            ..Default::default()
 8729        },
 8730    );
 8731
 8732    let buffer = project
 8733        .update(cx, |project, cx| {
 8734            project.open_local_buffer(path!("/file.ts"), cx)
 8735        })
 8736        .await
 8737        .unwrap();
 8738
 8739    let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 8740    let (editor, cx) = cx.add_window_view(|window, cx| {
 8741        build_editor_with_project(project.clone(), buffer, window, cx)
 8742    });
 8743    editor.update_in(cx, |editor, window, cx| {
 8744        editor.set_text(
 8745            "import { a } from 'module';\nimport { b } from 'module';\n\nconst x = a;\n",
 8746            window,
 8747            cx,
 8748        )
 8749    });
 8750
 8751    cx.executor().start_waiting();
 8752    let fake_server = fake_servers.next().await.unwrap();
 8753
 8754    let format = editor
 8755        .update_in(cx, |editor, window, cx| {
 8756            editor.perform_code_action_kind(
 8757                project.clone(),
 8758                CodeActionKind::SOURCE_ORGANIZE_IMPORTS,
 8759                window,
 8760                cx,
 8761            )
 8762        })
 8763        .unwrap();
 8764    fake_server
 8765        .set_request_handler::<lsp::request::CodeActionRequest, _, _>(move |params, _| async move {
 8766            assert_eq!(
 8767                params.text_document.uri,
 8768                lsp::Url::from_file_path(path!("/file.ts")).unwrap()
 8769            );
 8770            Ok(Some(vec![lsp::CodeActionOrCommand::CodeAction(
 8771                lsp::CodeAction {
 8772                    title: "Organize Imports".to_string(),
 8773                    kind: Some(lsp::CodeActionKind::SOURCE_ORGANIZE_IMPORTS),
 8774                    edit: Some(lsp::WorkspaceEdit {
 8775                        changes: Some(
 8776                            [(
 8777                                params.text_document.uri.clone(),
 8778                                vec![lsp::TextEdit::new(
 8779                                    lsp::Range::new(
 8780                                        lsp::Position::new(1, 0),
 8781                                        lsp::Position::new(2, 0),
 8782                                    ),
 8783                                    "".to_string(),
 8784                                )],
 8785                            )]
 8786                            .into_iter()
 8787                            .collect(),
 8788                        ),
 8789                        ..Default::default()
 8790                    }),
 8791                    ..Default::default()
 8792                },
 8793            )]))
 8794        })
 8795        .next()
 8796        .await;
 8797    cx.executor().start_waiting();
 8798    format.await;
 8799    assert_eq!(
 8800        editor.update(cx, |editor, cx| editor.text(cx)),
 8801        "import { a } from 'module';\n\nconst x = a;\n"
 8802    );
 8803
 8804    editor.update_in(cx, |editor, window, cx| {
 8805        editor.set_text(
 8806            "import { a } from 'module';\nimport { b } from 'module';\n\nconst x = a;\n",
 8807            window,
 8808            cx,
 8809        )
 8810    });
 8811    // Ensure we don't lock if code action hangs.
 8812    fake_server.set_request_handler::<lsp::request::CodeActionRequest, _, _>(
 8813        move |params, _| async move {
 8814            assert_eq!(
 8815                params.text_document.uri,
 8816                lsp::Url::from_file_path(path!("/file.ts")).unwrap()
 8817            );
 8818            futures::future::pending::<()>().await;
 8819            unreachable!()
 8820        },
 8821    );
 8822    let format = editor
 8823        .update_in(cx, |editor, window, cx| {
 8824            editor.perform_code_action_kind(
 8825                project,
 8826                CodeActionKind::SOURCE_ORGANIZE_IMPORTS,
 8827                window,
 8828                cx,
 8829            )
 8830        })
 8831        .unwrap();
 8832    cx.executor().advance_clock(super::CODE_ACTION_TIMEOUT);
 8833    cx.executor().start_waiting();
 8834    format.await;
 8835    assert_eq!(
 8836        editor.update(cx, |editor, cx| editor.text(cx)),
 8837        "import { a } from 'module';\nimport { b } from 'module';\n\nconst x = a;\n"
 8838    );
 8839}
 8840
 8841#[gpui::test]
 8842async fn test_concurrent_format_requests(cx: &mut TestAppContext) {
 8843    init_test(cx, |_| {});
 8844
 8845    let mut cx = EditorLspTestContext::new_rust(
 8846        lsp::ServerCapabilities {
 8847            document_formatting_provider: Some(lsp::OneOf::Left(true)),
 8848            ..Default::default()
 8849        },
 8850        cx,
 8851    )
 8852    .await;
 8853
 8854    cx.set_state(indoc! {"
 8855        one.twoˇ
 8856    "});
 8857
 8858    // The format request takes a long time. When it completes, it inserts
 8859    // a newline and an indent before the `.`
 8860    cx.lsp
 8861        .set_request_handler::<lsp::request::Formatting, _, _>(move |_, cx| {
 8862            let executor = cx.background_executor().clone();
 8863            async move {
 8864                executor.timer(Duration::from_millis(100)).await;
 8865                Ok(Some(vec![lsp::TextEdit {
 8866                    range: lsp::Range::new(lsp::Position::new(0, 3), lsp::Position::new(0, 3)),
 8867                    new_text: "\n    ".into(),
 8868                }]))
 8869            }
 8870        });
 8871
 8872    // Submit a format request.
 8873    let format_1 = cx
 8874        .update_editor(|editor, window, cx| editor.format(&Format, window, cx))
 8875        .unwrap();
 8876    cx.executor().run_until_parked();
 8877
 8878    // Submit a second format request.
 8879    let format_2 = cx
 8880        .update_editor(|editor, window, cx| editor.format(&Format, window, cx))
 8881        .unwrap();
 8882    cx.executor().run_until_parked();
 8883
 8884    // Wait for both format requests to complete
 8885    cx.executor().advance_clock(Duration::from_millis(200));
 8886    cx.executor().start_waiting();
 8887    format_1.await.unwrap();
 8888    cx.executor().start_waiting();
 8889    format_2.await.unwrap();
 8890
 8891    // The formatting edits only happens once.
 8892    cx.assert_editor_state(indoc! {"
 8893        one
 8894            .twoˇ
 8895    "});
 8896}
 8897
 8898#[gpui::test]
 8899async fn test_strip_whitespace_and_format_via_lsp(cx: &mut TestAppContext) {
 8900    init_test(cx, |settings| {
 8901        settings.defaults.formatter = Some(language_settings::SelectedFormatter::Auto)
 8902    });
 8903
 8904    let mut cx = EditorLspTestContext::new_rust(
 8905        lsp::ServerCapabilities {
 8906            document_formatting_provider: Some(lsp::OneOf::Left(true)),
 8907            ..Default::default()
 8908        },
 8909        cx,
 8910    )
 8911    .await;
 8912
 8913    // Set up a buffer white some trailing whitespace and no trailing newline.
 8914    cx.set_state(
 8915        &[
 8916            "one ",   //
 8917            "twoˇ",   //
 8918            "three ", //
 8919            "four",   //
 8920        ]
 8921        .join("\n"),
 8922    );
 8923
 8924    // Submit a format request.
 8925    let format = cx
 8926        .update_editor(|editor, window, cx| editor.format(&Format, window, cx))
 8927        .unwrap();
 8928
 8929    // Record which buffer changes have been sent to the language server
 8930    let buffer_changes = Arc::new(Mutex::new(Vec::new()));
 8931    cx.lsp
 8932        .handle_notification::<lsp::notification::DidChangeTextDocument, _>({
 8933            let buffer_changes = buffer_changes.clone();
 8934            move |params, _| {
 8935                buffer_changes.lock().extend(
 8936                    params
 8937                        .content_changes
 8938                        .into_iter()
 8939                        .map(|e| (e.range.unwrap(), e.text)),
 8940                );
 8941            }
 8942        });
 8943
 8944    // Handle formatting requests to the language server.
 8945    cx.lsp
 8946        .set_request_handler::<lsp::request::Formatting, _, _>({
 8947            let buffer_changes = buffer_changes.clone();
 8948            move |_, _| {
 8949                // When formatting is requested, trailing whitespace has already been stripped,
 8950                // and the trailing newline has already been added.
 8951                assert_eq!(
 8952                    &buffer_changes.lock()[1..],
 8953                    &[
 8954                        (
 8955                            lsp::Range::new(lsp::Position::new(0, 3), lsp::Position::new(0, 4)),
 8956                            "".into()
 8957                        ),
 8958                        (
 8959                            lsp::Range::new(lsp::Position::new(2, 5), lsp::Position::new(2, 6)),
 8960                            "".into()
 8961                        ),
 8962                        (
 8963                            lsp::Range::new(lsp::Position::new(3, 4), lsp::Position::new(3, 4)),
 8964                            "\n".into()
 8965                        ),
 8966                    ]
 8967                );
 8968
 8969                // Insert blank lines between each line of the buffer.
 8970                async move {
 8971                    Ok(Some(vec![
 8972                        lsp::TextEdit {
 8973                            range: lsp::Range::new(
 8974                                lsp::Position::new(1, 0),
 8975                                lsp::Position::new(1, 0),
 8976                            ),
 8977                            new_text: "\n".into(),
 8978                        },
 8979                        lsp::TextEdit {
 8980                            range: lsp::Range::new(
 8981                                lsp::Position::new(2, 0),
 8982                                lsp::Position::new(2, 0),
 8983                            ),
 8984                            new_text: "\n".into(),
 8985                        },
 8986                    ]))
 8987                }
 8988            }
 8989        });
 8990
 8991    // After formatting the buffer, the trailing whitespace is stripped,
 8992    // a newline is appended, and the edits provided by the language server
 8993    // have been applied.
 8994    format.await.unwrap();
 8995    cx.assert_editor_state(
 8996        &[
 8997            "one",   //
 8998            "",      //
 8999            "twoˇ",  //
 9000            "",      //
 9001            "three", //
 9002            "four",  //
 9003            "",      //
 9004        ]
 9005        .join("\n"),
 9006    );
 9007
 9008    // Undoing the formatting undoes the trailing whitespace removal, the
 9009    // trailing newline, and the LSP edits.
 9010    cx.update_buffer(|buffer, cx| buffer.undo(cx));
 9011    cx.assert_editor_state(
 9012        &[
 9013            "one ",   //
 9014            "twoˇ",   //
 9015            "three ", //
 9016            "four",   //
 9017        ]
 9018        .join("\n"),
 9019    );
 9020}
 9021
 9022#[gpui::test]
 9023async fn test_handle_input_for_show_signature_help_auto_signature_help_true(
 9024    cx: &mut TestAppContext,
 9025) {
 9026    init_test(cx, |_| {});
 9027
 9028    cx.update(|cx| {
 9029        cx.update_global::<SettingsStore, _>(|settings, cx| {
 9030            settings.update_user_settings::<EditorSettings>(cx, |settings| {
 9031                settings.auto_signature_help = Some(true);
 9032            });
 9033        });
 9034    });
 9035
 9036    let mut cx = EditorLspTestContext::new_rust(
 9037        lsp::ServerCapabilities {
 9038            signature_help_provider: Some(lsp::SignatureHelpOptions {
 9039                ..Default::default()
 9040            }),
 9041            ..Default::default()
 9042        },
 9043        cx,
 9044    )
 9045    .await;
 9046
 9047    let language = Language::new(
 9048        LanguageConfig {
 9049            name: "Rust".into(),
 9050            brackets: BracketPairConfig {
 9051                pairs: vec![
 9052                    BracketPair {
 9053                        start: "{".to_string(),
 9054                        end: "}".to_string(),
 9055                        close: true,
 9056                        surround: true,
 9057                        newline: true,
 9058                    },
 9059                    BracketPair {
 9060                        start: "(".to_string(),
 9061                        end: ")".to_string(),
 9062                        close: true,
 9063                        surround: true,
 9064                        newline: true,
 9065                    },
 9066                    BracketPair {
 9067                        start: "/*".to_string(),
 9068                        end: " */".to_string(),
 9069                        close: true,
 9070                        surround: true,
 9071                        newline: true,
 9072                    },
 9073                    BracketPair {
 9074                        start: "[".to_string(),
 9075                        end: "]".to_string(),
 9076                        close: false,
 9077                        surround: false,
 9078                        newline: true,
 9079                    },
 9080                    BracketPair {
 9081                        start: "\"".to_string(),
 9082                        end: "\"".to_string(),
 9083                        close: true,
 9084                        surround: true,
 9085                        newline: false,
 9086                    },
 9087                    BracketPair {
 9088                        start: "<".to_string(),
 9089                        end: ">".to_string(),
 9090                        close: false,
 9091                        surround: true,
 9092                        newline: true,
 9093                    },
 9094                ],
 9095                ..Default::default()
 9096            },
 9097            autoclose_before: "})]".to_string(),
 9098            ..Default::default()
 9099        },
 9100        Some(tree_sitter_rust::LANGUAGE.into()),
 9101    );
 9102    let language = Arc::new(language);
 9103
 9104    cx.language_registry().add(language.clone());
 9105    cx.update_buffer(|buffer, cx| {
 9106        buffer.set_language(Some(language), cx);
 9107    });
 9108
 9109    cx.set_state(
 9110        &r#"
 9111            fn main() {
 9112                sampleˇ
 9113            }
 9114        "#
 9115        .unindent(),
 9116    );
 9117
 9118    cx.update_editor(|editor, window, cx| {
 9119        editor.handle_input("(", window, cx);
 9120    });
 9121    cx.assert_editor_state(
 9122        &"
 9123            fn main() {
 9124                sample(ˇ)
 9125            }
 9126        "
 9127        .unindent(),
 9128    );
 9129
 9130    let mocked_response = lsp::SignatureHelp {
 9131        signatures: vec![lsp::SignatureInformation {
 9132            label: "fn sample(param1: u8, param2: u8)".to_string(),
 9133            documentation: None,
 9134            parameters: Some(vec![
 9135                lsp::ParameterInformation {
 9136                    label: lsp::ParameterLabel::Simple("param1: u8".to_string()),
 9137                    documentation: None,
 9138                },
 9139                lsp::ParameterInformation {
 9140                    label: lsp::ParameterLabel::Simple("param2: u8".to_string()),
 9141                    documentation: None,
 9142                },
 9143            ]),
 9144            active_parameter: None,
 9145        }],
 9146        active_signature: Some(0),
 9147        active_parameter: Some(0),
 9148    };
 9149    handle_signature_help_request(&mut cx, mocked_response).await;
 9150
 9151    cx.condition(|editor, _| editor.signature_help_state.is_shown())
 9152        .await;
 9153
 9154    cx.editor(|editor, _, _| {
 9155        let signature_help_state = editor.signature_help_state.popover().cloned();
 9156        assert_eq!(
 9157            signature_help_state.unwrap().label,
 9158            "param1: u8, param2: u8"
 9159        );
 9160    });
 9161}
 9162
 9163#[gpui::test]
 9164async fn test_handle_input_with_different_show_signature_settings(cx: &mut TestAppContext) {
 9165    init_test(cx, |_| {});
 9166
 9167    cx.update(|cx| {
 9168        cx.update_global::<SettingsStore, _>(|settings, cx| {
 9169            settings.update_user_settings::<EditorSettings>(cx, |settings| {
 9170                settings.auto_signature_help = Some(false);
 9171                settings.show_signature_help_after_edits = Some(false);
 9172            });
 9173        });
 9174    });
 9175
 9176    let mut cx = EditorLspTestContext::new_rust(
 9177        lsp::ServerCapabilities {
 9178            signature_help_provider: Some(lsp::SignatureHelpOptions {
 9179                ..Default::default()
 9180            }),
 9181            ..Default::default()
 9182        },
 9183        cx,
 9184    )
 9185    .await;
 9186
 9187    let language = Language::new(
 9188        LanguageConfig {
 9189            name: "Rust".into(),
 9190            brackets: BracketPairConfig {
 9191                pairs: vec![
 9192                    BracketPair {
 9193                        start: "{".to_string(),
 9194                        end: "}".to_string(),
 9195                        close: true,
 9196                        surround: true,
 9197                        newline: true,
 9198                    },
 9199                    BracketPair {
 9200                        start: "(".to_string(),
 9201                        end: ")".to_string(),
 9202                        close: true,
 9203                        surround: true,
 9204                        newline: true,
 9205                    },
 9206                    BracketPair {
 9207                        start: "/*".to_string(),
 9208                        end: " */".to_string(),
 9209                        close: true,
 9210                        surround: true,
 9211                        newline: true,
 9212                    },
 9213                    BracketPair {
 9214                        start: "[".to_string(),
 9215                        end: "]".to_string(),
 9216                        close: false,
 9217                        surround: false,
 9218                        newline: true,
 9219                    },
 9220                    BracketPair {
 9221                        start: "\"".to_string(),
 9222                        end: "\"".to_string(),
 9223                        close: true,
 9224                        surround: true,
 9225                        newline: false,
 9226                    },
 9227                    BracketPair {
 9228                        start: "<".to_string(),
 9229                        end: ">".to_string(),
 9230                        close: false,
 9231                        surround: true,
 9232                        newline: true,
 9233                    },
 9234                ],
 9235                ..Default::default()
 9236            },
 9237            autoclose_before: "})]".to_string(),
 9238            ..Default::default()
 9239        },
 9240        Some(tree_sitter_rust::LANGUAGE.into()),
 9241    );
 9242    let language = Arc::new(language);
 9243
 9244    cx.language_registry().add(language.clone());
 9245    cx.update_buffer(|buffer, cx| {
 9246        buffer.set_language(Some(language), cx);
 9247    });
 9248
 9249    // Ensure that signature_help is not called when no signature help is enabled.
 9250    cx.set_state(
 9251        &r#"
 9252            fn main() {
 9253                sampleˇ
 9254            }
 9255        "#
 9256        .unindent(),
 9257    );
 9258    cx.update_editor(|editor, window, cx| {
 9259        editor.handle_input("(", window, cx);
 9260    });
 9261    cx.assert_editor_state(
 9262        &"
 9263            fn main() {
 9264                sample(ˇ)
 9265            }
 9266        "
 9267        .unindent(),
 9268    );
 9269    cx.editor(|editor, _, _| {
 9270        assert!(editor.signature_help_state.task().is_none());
 9271    });
 9272
 9273    let mocked_response = lsp::SignatureHelp {
 9274        signatures: vec![lsp::SignatureInformation {
 9275            label: "fn sample(param1: u8, param2: u8)".to_string(),
 9276            documentation: None,
 9277            parameters: Some(vec![
 9278                lsp::ParameterInformation {
 9279                    label: lsp::ParameterLabel::Simple("param1: u8".to_string()),
 9280                    documentation: None,
 9281                },
 9282                lsp::ParameterInformation {
 9283                    label: lsp::ParameterLabel::Simple("param2: u8".to_string()),
 9284                    documentation: None,
 9285                },
 9286            ]),
 9287            active_parameter: None,
 9288        }],
 9289        active_signature: Some(0),
 9290        active_parameter: Some(0),
 9291    };
 9292
 9293    // Ensure that signature_help is called when enabled afte edits
 9294    cx.update(|_, cx| {
 9295        cx.update_global::<SettingsStore, _>(|settings, cx| {
 9296            settings.update_user_settings::<EditorSettings>(cx, |settings| {
 9297                settings.auto_signature_help = Some(false);
 9298                settings.show_signature_help_after_edits = Some(true);
 9299            });
 9300        });
 9301    });
 9302    cx.set_state(
 9303        &r#"
 9304            fn main() {
 9305                sampleˇ
 9306            }
 9307        "#
 9308        .unindent(),
 9309    );
 9310    cx.update_editor(|editor, window, cx| {
 9311        editor.handle_input("(", window, cx);
 9312    });
 9313    cx.assert_editor_state(
 9314        &"
 9315            fn main() {
 9316                sample(ˇ)
 9317            }
 9318        "
 9319        .unindent(),
 9320    );
 9321    handle_signature_help_request(&mut cx, mocked_response.clone()).await;
 9322    cx.condition(|editor, _| editor.signature_help_state.is_shown())
 9323        .await;
 9324    cx.update_editor(|editor, _, _| {
 9325        let signature_help_state = editor.signature_help_state.popover().cloned();
 9326        assert!(signature_help_state.is_some());
 9327        assert_eq!(
 9328            signature_help_state.unwrap().label,
 9329            "param1: u8, param2: u8"
 9330        );
 9331        editor.signature_help_state = SignatureHelpState::default();
 9332    });
 9333
 9334    // Ensure that signature_help is called when auto signature help override is enabled
 9335    cx.update(|_, cx| {
 9336        cx.update_global::<SettingsStore, _>(|settings, cx| {
 9337            settings.update_user_settings::<EditorSettings>(cx, |settings| {
 9338                settings.auto_signature_help = Some(true);
 9339                settings.show_signature_help_after_edits = Some(false);
 9340            });
 9341        });
 9342    });
 9343    cx.set_state(
 9344        &r#"
 9345            fn main() {
 9346                sampleˇ
 9347            }
 9348        "#
 9349        .unindent(),
 9350    );
 9351    cx.update_editor(|editor, window, cx| {
 9352        editor.handle_input("(", window, cx);
 9353    });
 9354    cx.assert_editor_state(
 9355        &"
 9356            fn main() {
 9357                sample(ˇ)
 9358            }
 9359        "
 9360        .unindent(),
 9361    );
 9362    handle_signature_help_request(&mut cx, mocked_response).await;
 9363    cx.condition(|editor, _| editor.signature_help_state.is_shown())
 9364        .await;
 9365    cx.editor(|editor, _, _| {
 9366        let signature_help_state = editor.signature_help_state.popover().cloned();
 9367        assert!(signature_help_state.is_some());
 9368        assert_eq!(
 9369            signature_help_state.unwrap().label,
 9370            "param1: u8, param2: u8"
 9371        );
 9372    });
 9373}
 9374
 9375#[gpui::test]
 9376async fn test_signature_help(cx: &mut TestAppContext) {
 9377    init_test(cx, |_| {});
 9378    cx.update(|cx| {
 9379        cx.update_global::<SettingsStore, _>(|settings, cx| {
 9380            settings.update_user_settings::<EditorSettings>(cx, |settings| {
 9381                settings.auto_signature_help = Some(true);
 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    // A test that directly calls `show_signature_help`
 9398    cx.update_editor(|editor, window, cx| {
 9399        editor.show_signature_help(&ShowSignatureHelp, window, cx);
 9400    });
 9401
 9402    let mocked_response = lsp::SignatureHelp {
 9403        signatures: vec![lsp::SignatureInformation {
 9404            label: "fn sample(param1: u8, param2: u8)".to_string(),
 9405            documentation: None,
 9406            parameters: Some(vec![
 9407                lsp::ParameterInformation {
 9408                    label: lsp::ParameterLabel::Simple("param1: u8".to_string()),
 9409                    documentation: None,
 9410                },
 9411                lsp::ParameterInformation {
 9412                    label: lsp::ParameterLabel::Simple("param2: u8".to_string()),
 9413                    documentation: None,
 9414                },
 9415            ]),
 9416            active_parameter: None,
 9417        }],
 9418        active_signature: Some(0),
 9419        active_parameter: Some(0),
 9420    };
 9421    handle_signature_help_request(&mut cx, mocked_response).await;
 9422
 9423    cx.condition(|editor, _| editor.signature_help_state.is_shown())
 9424        .await;
 9425
 9426    cx.editor(|editor, _, _| {
 9427        let signature_help_state = editor.signature_help_state.popover().cloned();
 9428        assert!(signature_help_state.is_some());
 9429        assert_eq!(
 9430            signature_help_state.unwrap().label,
 9431            "param1: u8, param2: u8"
 9432        );
 9433    });
 9434
 9435    // When exiting outside from inside the brackets, `signature_help` is closed.
 9436    cx.set_state(indoc! {"
 9437        fn main() {
 9438            sample(ˇ);
 9439        }
 9440
 9441        fn sample(param1: u8, param2: u8) {}
 9442    "});
 9443
 9444    cx.update_editor(|editor, window, cx| {
 9445        editor.change_selections(None, window, cx, |s| s.select_ranges([0..0]));
 9446    });
 9447
 9448    let mocked_response = lsp::SignatureHelp {
 9449        signatures: Vec::new(),
 9450        active_signature: None,
 9451        active_parameter: None,
 9452    };
 9453    handle_signature_help_request(&mut cx, mocked_response).await;
 9454
 9455    cx.condition(|editor, _| !editor.signature_help_state.is_shown())
 9456        .await;
 9457
 9458    cx.editor(|editor, _, _| {
 9459        assert!(!editor.signature_help_state.is_shown());
 9460    });
 9461
 9462    // When entering inside the brackets from outside, `show_signature_help` is automatically called.
 9463    cx.set_state(indoc! {"
 9464        fn main() {
 9465            sample(ˇ);
 9466        }
 9467
 9468        fn sample(param1: u8, param2: u8) {}
 9469    "});
 9470
 9471    let mocked_response = lsp::SignatureHelp {
 9472        signatures: vec![lsp::SignatureInformation {
 9473            label: "fn sample(param1: u8, param2: u8)".to_string(),
 9474            documentation: None,
 9475            parameters: Some(vec![
 9476                lsp::ParameterInformation {
 9477                    label: lsp::ParameterLabel::Simple("param1: u8".to_string()),
 9478                    documentation: None,
 9479                },
 9480                lsp::ParameterInformation {
 9481                    label: lsp::ParameterLabel::Simple("param2: u8".to_string()),
 9482                    documentation: None,
 9483                },
 9484            ]),
 9485            active_parameter: None,
 9486        }],
 9487        active_signature: Some(0),
 9488        active_parameter: Some(0),
 9489    };
 9490    handle_signature_help_request(&mut cx, mocked_response.clone()).await;
 9491    cx.condition(|editor, _| editor.signature_help_state.is_shown())
 9492        .await;
 9493    cx.editor(|editor, _, _| {
 9494        assert!(editor.signature_help_state.is_shown());
 9495    });
 9496
 9497    // Restore the popover with more parameter input
 9498    cx.set_state(indoc! {"
 9499        fn main() {
 9500            sample(param1, param2ˇ);
 9501        }
 9502
 9503        fn sample(param1: u8, param2: u8) {}
 9504    "});
 9505
 9506    let mocked_response = lsp::SignatureHelp {
 9507        signatures: vec![lsp::SignatureInformation {
 9508            label: "fn sample(param1: u8, param2: u8)".to_string(),
 9509            documentation: None,
 9510            parameters: Some(vec![
 9511                lsp::ParameterInformation {
 9512                    label: lsp::ParameterLabel::Simple("param1: u8".to_string()),
 9513                    documentation: None,
 9514                },
 9515                lsp::ParameterInformation {
 9516                    label: lsp::ParameterLabel::Simple("param2: u8".to_string()),
 9517                    documentation: None,
 9518                },
 9519            ]),
 9520            active_parameter: None,
 9521        }],
 9522        active_signature: Some(0),
 9523        active_parameter: Some(1),
 9524    };
 9525    handle_signature_help_request(&mut cx, mocked_response.clone()).await;
 9526    cx.condition(|editor, _| editor.signature_help_state.is_shown())
 9527        .await;
 9528
 9529    // When selecting a range, the popover is gone.
 9530    // Avoid using `cx.set_state` to not actually edit the document, just change its selections.
 9531    cx.update_editor(|editor, window, cx| {
 9532        editor.change_selections(None, window, cx, |s| {
 9533            s.select_ranges(Some(Point::new(1, 25)..Point::new(1, 19)));
 9534        })
 9535    });
 9536    cx.assert_editor_state(indoc! {"
 9537        fn main() {
 9538            sample(param1, «ˇparam2»);
 9539        }
 9540
 9541        fn sample(param1: u8, param2: u8) {}
 9542    "});
 9543    cx.editor(|editor, _, _| {
 9544        assert!(!editor.signature_help_state.is_shown());
 9545    });
 9546
 9547    // When unselecting again, the popover is back if within the brackets.
 9548    cx.update_editor(|editor, window, cx| {
 9549        editor.change_selections(None, window, cx, |s| {
 9550            s.select_ranges(Some(Point::new(1, 19)..Point::new(1, 19)));
 9551        })
 9552    });
 9553    cx.assert_editor_state(indoc! {"
 9554        fn main() {
 9555            sample(param1, ˇparam2);
 9556        }
 9557
 9558        fn sample(param1: u8, param2: u8) {}
 9559    "});
 9560    handle_signature_help_request(&mut cx, mocked_response).await;
 9561    cx.condition(|editor, _| editor.signature_help_state.is_shown())
 9562        .await;
 9563    cx.editor(|editor, _, _| {
 9564        assert!(editor.signature_help_state.is_shown());
 9565    });
 9566
 9567    // Test to confirm that SignatureHelp does not appear after deselecting multiple ranges when it was hidden by pressing Escape.
 9568    cx.update_editor(|editor, window, cx| {
 9569        editor.change_selections(None, window, cx, |s| {
 9570            s.select_ranges(Some(Point::new(0, 0)..Point::new(0, 0)));
 9571            s.select_ranges(Some(Point::new(1, 19)..Point::new(1, 19)));
 9572        })
 9573    });
 9574    cx.assert_editor_state(indoc! {"
 9575        fn main() {
 9576            sample(param1, ˇparam2);
 9577        }
 9578
 9579        fn sample(param1: u8, param2: u8) {}
 9580    "});
 9581
 9582    let mocked_response = lsp::SignatureHelp {
 9583        signatures: vec![lsp::SignatureInformation {
 9584            label: "fn sample(param1: u8, param2: u8)".to_string(),
 9585            documentation: None,
 9586            parameters: Some(vec![
 9587                lsp::ParameterInformation {
 9588                    label: lsp::ParameterLabel::Simple("param1: u8".to_string()),
 9589                    documentation: None,
 9590                },
 9591                lsp::ParameterInformation {
 9592                    label: lsp::ParameterLabel::Simple("param2: u8".to_string()),
 9593                    documentation: None,
 9594                },
 9595            ]),
 9596            active_parameter: None,
 9597        }],
 9598        active_signature: Some(0),
 9599        active_parameter: Some(1),
 9600    };
 9601    handle_signature_help_request(&mut cx, mocked_response.clone()).await;
 9602    cx.condition(|editor, _| editor.signature_help_state.is_shown())
 9603        .await;
 9604    cx.update_editor(|editor, _, cx| {
 9605        editor.hide_signature_help(cx, SignatureHelpHiddenBy::Escape);
 9606    });
 9607    cx.condition(|editor, _| !editor.signature_help_state.is_shown())
 9608        .await;
 9609    cx.update_editor(|editor, window, cx| {
 9610        editor.change_selections(None, window, cx, |s| {
 9611            s.select_ranges(Some(Point::new(1, 25)..Point::new(1, 19)));
 9612        })
 9613    });
 9614    cx.assert_editor_state(indoc! {"
 9615        fn main() {
 9616            sample(param1, «ˇparam2»);
 9617        }
 9618
 9619        fn sample(param1: u8, param2: u8) {}
 9620    "});
 9621    cx.update_editor(|editor, window, cx| {
 9622        editor.change_selections(None, window, cx, |s| {
 9623            s.select_ranges(Some(Point::new(1, 19)..Point::new(1, 19)));
 9624        })
 9625    });
 9626    cx.assert_editor_state(indoc! {"
 9627        fn main() {
 9628            sample(param1, ˇparam2);
 9629        }
 9630
 9631        fn sample(param1: u8, param2: u8) {}
 9632    "});
 9633    cx.condition(|editor, _| !editor.signature_help_state.is_shown()) // because hidden by escape
 9634        .await;
 9635}
 9636
 9637#[gpui::test]
 9638async fn test_completion_mode(cx: &mut TestAppContext) {
 9639    init_test(cx, |_| {});
 9640    let mut cx = EditorLspTestContext::new_rust(
 9641        lsp::ServerCapabilities {
 9642            completion_provider: Some(lsp::CompletionOptions {
 9643                resolve_provider: Some(true),
 9644                ..Default::default()
 9645            }),
 9646            ..Default::default()
 9647        },
 9648        cx,
 9649    )
 9650    .await;
 9651
 9652    struct Run {
 9653        run_description: &'static str,
 9654        initial_state: String,
 9655        buffer_marked_text: String,
 9656        completion_text: &'static str,
 9657        expected_with_insert_mode: String,
 9658        expected_with_replace_mode: String,
 9659        expected_with_replace_subsequence_mode: String,
 9660        expected_with_replace_suffix_mode: String,
 9661    }
 9662
 9663    let runs = [
 9664        Run {
 9665            run_description: "Start of word matches completion text",
 9666            initial_state: "before ediˇ after".into(),
 9667            buffer_marked_text: "before <edi|> after".into(),
 9668            completion_text: "editor",
 9669            expected_with_insert_mode: "before editorˇ after".into(),
 9670            expected_with_replace_mode: "before editorˇ after".into(),
 9671            expected_with_replace_subsequence_mode: "before editorˇ after".into(),
 9672            expected_with_replace_suffix_mode: "before editorˇ after".into(),
 9673        },
 9674        Run {
 9675            run_description: "Accept same text at the middle of the word",
 9676            initial_state: "before ediˇtor after".into(),
 9677            buffer_marked_text: "before <edi|tor> after".into(),
 9678            completion_text: "editor",
 9679            expected_with_insert_mode: "before editorˇtor after".into(),
 9680            expected_with_replace_mode: "before editorˇ after".into(),
 9681            expected_with_replace_subsequence_mode: "before editorˇ after".into(),
 9682            expected_with_replace_suffix_mode: "before editorˇ after".into(),
 9683        },
 9684        Run {
 9685            run_description: "End of word matches completion text -- cursor at end",
 9686            initial_state: "before torˇ after".into(),
 9687            buffer_marked_text: "before <tor|> after".into(),
 9688            completion_text: "editor",
 9689            expected_with_insert_mode: "before editorˇ after".into(),
 9690            expected_with_replace_mode: "before editorˇ after".into(),
 9691            expected_with_replace_subsequence_mode: "before editorˇ after".into(),
 9692            expected_with_replace_suffix_mode: "before editorˇ after".into(),
 9693        },
 9694        Run {
 9695            run_description: "End of word matches completion text -- cursor at start",
 9696            initial_state: "before ˇtor after".into(),
 9697            buffer_marked_text: "before <|tor> after".into(),
 9698            completion_text: "editor",
 9699            expected_with_insert_mode: "before editorˇtor after".into(),
 9700            expected_with_replace_mode: "before editorˇ after".into(),
 9701            expected_with_replace_subsequence_mode: "before editorˇ after".into(),
 9702            expected_with_replace_suffix_mode: "before editorˇ after".into(),
 9703        },
 9704        Run {
 9705            run_description: "Prepend text containing whitespace",
 9706            initial_state: "pˇfield: bool".into(),
 9707            buffer_marked_text: "<p|field>: bool".into(),
 9708            completion_text: "pub ",
 9709            expected_with_insert_mode: "pub ˇfield: bool".into(),
 9710            expected_with_replace_mode: "pub ˇ: bool".into(),
 9711            expected_with_replace_subsequence_mode: "pub ˇfield: bool".into(),
 9712            expected_with_replace_suffix_mode: "pub ˇfield: bool".into(),
 9713        },
 9714        Run {
 9715            run_description: "Add element to start of list",
 9716            initial_state: "[element_ˇelement_2]".into(),
 9717            buffer_marked_text: "[<element_|element_2>]".into(),
 9718            completion_text: "element_1",
 9719            expected_with_insert_mode: "[element_1ˇelement_2]".into(),
 9720            expected_with_replace_mode: "[element_1ˇ]".into(),
 9721            expected_with_replace_subsequence_mode: "[element_1ˇelement_2]".into(),
 9722            expected_with_replace_suffix_mode: "[element_1ˇelement_2]".into(),
 9723        },
 9724        Run {
 9725            run_description: "Add element to start of list -- first and second elements are equal",
 9726            initial_state: "[elˇelement]".into(),
 9727            buffer_marked_text: "[<el|element>]".into(),
 9728            completion_text: "element",
 9729            expected_with_insert_mode: "[elementˇelement]".into(),
 9730            expected_with_replace_mode: "[elementˇ]".into(),
 9731            expected_with_replace_subsequence_mode: "[elementˇelement]".into(),
 9732            expected_with_replace_suffix_mode: "[elementˇ]".into(),
 9733        },
 9734        Run {
 9735            run_description: "Ends with matching suffix",
 9736            initial_state: "SubˇError".into(),
 9737            buffer_marked_text: "<Sub|Error>".into(),
 9738            completion_text: "SubscriptionError",
 9739            expected_with_insert_mode: "SubscriptionErrorˇError".into(),
 9740            expected_with_replace_mode: "SubscriptionErrorˇ".into(),
 9741            expected_with_replace_subsequence_mode: "SubscriptionErrorˇ".into(),
 9742            expected_with_replace_suffix_mode: "SubscriptionErrorˇ".into(),
 9743        },
 9744        Run {
 9745            run_description: "Suffix is a subsequence -- contiguous",
 9746            initial_state: "SubˇErr".into(),
 9747            buffer_marked_text: "<Sub|Err>".into(),
 9748            completion_text: "SubscriptionError",
 9749            expected_with_insert_mode: "SubscriptionErrorˇErr".into(),
 9750            expected_with_replace_mode: "SubscriptionErrorˇ".into(),
 9751            expected_with_replace_subsequence_mode: "SubscriptionErrorˇ".into(),
 9752            expected_with_replace_suffix_mode: "SubscriptionErrorˇErr".into(),
 9753        },
 9754        Run {
 9755            run_description: "Suffix is a subsequence -- non-contiguous -- replace intended",
 9756            initial_state: "Suˇscrirr".into(),
 9757            buffer_marked_text: "<Su|scrirr>".into(),
 9758            completion_text: "SubscriptionError",
 9759            expected_with_insert_mode: "SubscriptionErrorˇscrirr".into(),
 9760            expected_with_replace_mode: "SubscriptionErrorˇ".into(),
 9761            expected_with_replace_subsequence_mode: "SubscriptionErrorˇ".into(),
 9762            expected_with_replace_suffix_mode: "SubscriptionErrorˇscrirr".into(),
 9763        },
 9764        Run {
 9765            run_description: "Suffix is a subsequence -- non-contiguous -- replace unintended",
 9766            initial_state: "foo(indˇix)".into(),
 9767            buffer_marked_text: "foo(<ind|ix>)".into(),
 9768            completion_text: "node_index",
 9769            expected_with_insert_mode: "foo(node_indexˇix)".into(),
 9770            expected_with_replace_mode: "foo(node_indexˇ)".into(),
 9771            expected_with_replace_subsequence_mode: "foo(node_indexˇix)".into(),
 9772            expected_with_replace_suffix_mode: "foo(node_indexˇix)".into(),
 9773        },
 9774    ];
 9775
 9776    for run in runs {
 9777        let run_variations = [
 9778            (LspInsertMode::Insert, run.expected_with_insert_mode),
 9779            (LspInsertMode::Replace, run.expected_with_replace_mode),
 9780            (
 9781                LspInsertMode::ReplaceSubsequence,
 9782                run.expected_with_replace_subsequence_mode,
 9783            ),
 9784            (
 9785                LspInsertMode::ReplaceSuffix,
 9786                run.expected_with_replace_suffix_mode,
 9787            ),
 9788        ];
 9789
 9790        for (lsp_insert_mode, expected_text) in run_variations {
 9791            eprintln!(
 9792                "run = {:?}, mode = {lsp_insert_mode:.?}",
 9793                run.run_description,
 9794            );
 9795
 9796            update_test_language_settings(&mut cx, |settings| {
 9797                settings.defaults.completions = Some(CompletionSettings {
 9798                    lsp_insert_mode,
 9799                    words: WordsCompletionMode::Disabled,
 9800                    lsp: true,
 9801                    lsp_fetch_timeout_ms: 0,
 9802                });
 9803            });
 9804
 9805            cx.set_state(&run.initial_state);
 9806            cx.update_editor(|editor, window, cx| {
 9807                editor.show_completions(&ShowCompletions { trigger: None }, window, cx);
 9808            });
 9809
 9810            let counter = Arc::new(AtomicUsize::new(0));
 9811            handle_completion_request_with_insert_and_replace(
 9812                &mut cx,
 9813                &run.buffer_marked_text,
 9814                vec![run.completion_text],
 9815                counter.clone(),
 9816            )
 9817            .await;
 9818            cx.condition(|editor, _| editor.context_menu_visible())
 9819                .await;
 9820            assert_eq!(counter.load(atomic::Ordering::Acquire), 1);
 9821
 9822            let apply_additional_edits = cx.update_editor(|editor, window, cx| {
 9823                editor
 9824                    .confirm_completion(&ConfirmCompletion::default(), window, cx)
 9825                    .unwrap()
 9826            });
 9827            cx.assert_editor_state(&expected_text);
 9828            handle_resolve_completion_request(&mut cx, None).await;
 9829            apply_additional_edits.await.unwrap();
 9830        }
 9831    }
 9832}
 9833
 9834#[gpui::test]
 9835async fn test_completion_with_mode_specified_by_action(cx: &mut TestAppContext) {
 9836    init_test(cx, |_| {});
 9837    let mut cx = EditorLspTestContext::new_rust(
 9838        lsp::ServerCapabilities {
 9839            completion_provider: Some(lsp::CompletionOptions {
 9840                resolve_provider: Some(true),
 9841                ..Default::default()
 9842            }),
 9843            ..Default::default()
 9844        },
 9845        cx,
 9846    )
 9847    .await;
 9848
 9849    let initial_state = "SubˇError";
 9850    let buffer_marked_text = "<Sub|Error>";
 9851    let completion_text = "SubscriptionError";
 9852    let expected_with_insert_mode = "SubscriptionErrorˇError";
 9853    let expected_with_replace_mode = "SubscriptionErrorˇ";
 9854
 9855    update_test_language_settings(&mut cx, |settings| {
 9856        settings.defaults.completions = Some(CompletionSettings {
 9857            words: WordsCompletionMode::Disabled,
 9858            // set the opposite here to ensure that the action is overriding the default behavior
 9859            lsp_insert_mode: LspInsertMode::Insert,
 9860            lsp: true,
 9861            lsp_fetch_timeout_ms: 0,
 9862        });
 9863    });
 9864
 9865    cx.set_state(initial_state);
 9866    cx.update_editor(|editor, window, cx| {
 9867        editor.show_completions(&ShowCompletions { trigger: None }, window, cx);
 9868    });
 9869
 9870    let counter = Arc::new(AtomicUsize::new(0));
 9871    handle_completion_request_with_insert_and_replace(
 9872        &mut cx,
 9873        &buffer_marked_text,
 9874        vec![completion_text],
 9875        counter.clone(),
 9876    )
 9877    .await;
 9878    cx.condition(|editor, _| editor.context_menu_visible())
 9879        .await;
 9880    assert_eq!(counter.load(atomic::Ordering::Acquire), 1);
 9881
 9882    let apply_additional_edits = cx.update_editor(|editor, window, cx| {
 9883        editor
 9884            .confirm_completion_replace(&ConfirmCompletionReplace, window, cx)
 9885            .unwrap()
 9886    });
 9887    cx.assert_editor_state(&expected_with_replace_mode);
 9888    handle_resolve_completion_request(&mut cx, None).await;
 9889    apply_additional_edits.await.unwrap();
 9890
 9891    update_test_language_settings(&mut cx, |settings| {
 9892        settings.defaults.completions = Some(CompletionSettings {
 9893            words: WordsCompletionMode::Disabled,
 9894            // set the opposite here to ensure that the action is overriding the default behavior
 9895            lsp_insert_mode: LspInsertMode::Replace,
 9896            lsp: true,
 9897            lsp_fetch_timeout_ms: 0,
 9898        });
 9899    });
 9900
 9901    cx.set_state(initial_state);
 9902    cx.update_editor(|editor, window, cx| {
 9903        editor.show_completions(&ShowCompletions { trigger: None }, window, cx);
 9904    });
 9905    handle_completion_request_with_insert_and_replace(
 9906        &mut cx,
 9907        &buffer_marked_text,
 9908        vec![completion_text],
 9909        counter.clone(),
 9910    )
 9911    .await;
 9912    cx.condition(|editor, _| editor.context_menu_visible())
 9913        .await;
 9914    assert_eq!(counter.load(atomic::Ordering::Acquire), 2);
 9915
 9916    let apply_additional_edits = cx.update_editor(|editor, window, cx| {
 9917        editor
 9918            .confirm_completion_insert(&ConfirmCompletionInsert, window, cx)
 9919            .unwrap()
 9920    });
 9921    cx.assert_editor_state(&expected_with_insert_mode);
 9922    handle_resolve_completion_request(&mut cx, None).await;
 9923    apply_additional_edits.await.unwrap();
 9924}
 9925
 9926#[gpui::test]
 9927async fn test_completion_replacing_suffix_in_multicursors(cx: &mut TestAppContext) {
 9928    init_test(cx, |_| {});
 9929    let mut cx = EditorLspTestContext::new_rust(
 9930        lsp::ServerCapabilities {
 9931            completion_provider: Some(lsp::CompletionOptions {
 9932                resolve_provider: Some(true),
 9933                ..Default::default()
 9934            }),
 9935            ..Default::default()
 9936        },
 9937        cx,
 9938    )
 9939    .await;
 9940
 9941    let initial_state = indoc! {"
 9942        1. buf.to_offˇsuffix
 9943        2. buf.to_offˇsuf
 9944        3. buf.to_offˇfix
 9945        4. buf.to_offˇ
 9946        5. into_offˇensive
 9947        6. ˇsuffix
 9948        7. let ˇ //
 9949        8. aaˇzz
 9950        9. buf.to_off«zzzzzˇ»suffix
 9951        10. buf.«ˇzzzzz»suffix
 9952        11. to_off«ˇzzzzz»
 9953
 9954        buf.to_offˇsuffix  // newest cursor
 9955    "};
 9956    let completion_marked_buffer = indoc! {"
 9957        1. buf.to_offsuffix
 9958        2. buf.to_offsuf
 9959        3. buf.to_offfix
 9960        4. buf.to_off
 9961        5. into_offensive
 9962        6. suffix
 9963        7. let  //
 9964        8. aazz
 9965        9. buf.to_offzzzzzsuffix
 9966        10. buf.zzzzzsuffix
 9967        11. to_offzzzzz
 9968
 9969        buf.<to_off|suffix>  // newest cursor
 9970    "};
 9971    let completion_text = "to_offset";
 9972    let expected = indoc! {"
 9973        1. buf.to_offsetˇ
 9974        2. buf.to_offsetˇsuf
 9975        3. buf.to_offsetˇfix
 9976        4. buf.to_offsetˇ
 9977        5. into_offsetˇensive
 9978        6. to_offsetˇsuffix
 9979        7. let to_offsetˇ //
 9980        8. aato_offsetˇzz
 9981        9. buf.to_offsetˇ
 9982        10. buf.to_offsetˇsuffix
 9983        11. to_offsetˇ
 9984
 9985        buf.to_offsetˇ  // newest cursor
 9986    "};
 9987
 9988    cx.set_state(initial_state);
 9989    cx.update_editor(|editor, window, cx| {
 9990        editor.show_completions(&ShowCompletions { trigger: None }, window, cx);
 9991    });
 9992
 9993    let counter = Arc::new(AtomicUsize::new(0));
 9994    handle_completion_request_with_insert_and_replace(
 9995        &mut cx,
 9996        completion_marked_buffer,
 9997        vec![completion_text],
 9998        counter.clone(),
 9999    )
10000    .await;
10001    cx.condition(|editor, _| editor.context_menu_visible())
10002        .await;
10003    assert_eq!(counter.load(atomic::Ordering::Acquire), 1);
10004
10005    let apply_additional_edits = cx.update_editor(|editor, window, cx| {
10006        editor
10007            .confirm_completion_replace(&ConfirmCompletionReplace, window, cx)
10008            .unwrap()
10009    });
10010    cx.assert_editor_state(expected);
10011    handle_resolve_completion_request(&mut cx, None).await;
10012    apply_additional_edits.await.unwrap();
10013}
10014
10015// This used to crash
10016#[gpui::test]
10017async fn test_completion_in_multibuffer_with_replace_range(cx: &mut TestAppContext) {
10018    init_test(cx, |_| {});
10019
10020    let buffer_text = indoc! {"
10021        fn main() {
10022            10.satu;
10023
10024            //
10025            // separate cursors so they open in different excerpts (manually reproducible)
10026            //
10027
10028            10.satu20;
10029        }
10030    "};
10031    let multibuffer_text_with_selections = indoc! {"
10032        fn main() {
10033            10.satuˇ;
10034
10035            //
10036
10037            //
10038
10039            10.satuˇ20;
10040        }
10041    "};
10042    let expected_multibuffer = indoc! {"
10043        fn main() {
10044            10.saturating_sub()ˇ;
10045
10046            //
10047
10048            //
10049
10050            10.saturating_sub()ˇ;
10051        }
10052    "};
10053
10054    let first_excerpt_end = buffer_text.find("//").unwrap() + 3;
10055    let second_excerpt_end = buffer_text.rfind("//").unwrap() - 4;
10056
10057    let fs = FakeFs::new(cx.executor());
10058    fs.insert_tree(
10059        path!("/a"),
10060        json!({
10061            "main.rs": buffer_text,
10062        }),
10063    )
10064    .await;
10065
10066    let project = Project::test(fs, [path!("/a").as_ref()], cx).await;
10067    let language_registry = project.read_with(cx, |project, _| project.languages().clone());
10068    language_registry.add(rust_lang());
10069    let mut fake_servers = language_registry.register_fake_lsp(
10070        "Rust",
10071        FakeLspAdapter {
10072            capabilities: lsp::ServerCapabilities {
10073                completion_provider: Some(lsp::CompletionOptions {
10074                    resolve_provider: None,
10075                    ..lsp::CompletionOptions::default()
10076                }),
10077                ..lsp::ServerCapabilities::default()
10078            },
10079            ..FakeLspAdapter::default()
10080        },
10081    );
10082    let workspace = cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
10083    let cx = &mut VisualTestContext::from_window(*workspace, cx);
10084    let buffer = project
10085        .update(cx, |project, cx| {
10086            project.open_local_buffer(path!("/a/main.rs"), cx)
10087        })
10088        .await
10089        .unwrap();
10090
10091    let multi_buffer = cx.new(|cx| {
10092        let mut multi_buffer = MultiBuffer::new(Capability::ReadWrite);
10093        multi_buffer.push_excerpts(
10094            buffer.clone(),
10095            [ExcerptRange::new(0..first_excerpt_end)],
10096            cx,
10097        );
10098        multi_buffer.push_excerpts(
10099            buffer.clone(),
10100            [ExcerptRange::new(second_excerpt_end..buffer_text.len())],
10101            cx,
10102        );
10103        multi_buffer
10104    });
10105
10106    let editor = workspace
10107        .update(cx, |_, window, cx| {
10108            cx.new(|cx| {
10109                Editor::new(
10110                    EditorMode::Full {
10111                        scale_ui_elements_with_buffer_font_size: false,
10112                        show_active_line_background: false,
10113                    },
10114                    multi_buffer.clone(),
10115                    Some(project.clone()),
10116                    window,
10117                    cx,
10118                )
10119            })
10120        })
10121        .unwrap();
10122
10123    let pane = workspace
10124        .update(cx, |workspace, _, _| workspace.active_pane().clone())
10125        .unwrap();
10126    pane.update_in(cx, |pane, window, cx| {
10127        pane.add_item(Box::new(editor.clone()), true, true, None, window, cx);
10128    });
10129
10130    let fake_server = fake_servers.next().await.unwrap();
10131
10132    editor.update_in(cx, |editor, window, cx| {
10133        editor.change_selections(None, window, cx, |s| {
10134            s.select_ranges([
10135                Point::new(1, 11)..Point::new(1, 11),
10136                Point::new(7, 11)..Point::new(7, 11),
10137            ])
10138        });
10139
10140        assert_text_with_selections(editor, multibuffer_text_with_selections, cx);
10141    });
10142
10143    editor.update_in(cx, |editor, window, cx| {
10144        editor.show_completions(&ShowCompletions { trigger: None }, window, cx);
10145    });
10146
10147    fake_server
10148        .set_request_handler::<lsp::request::Completion, _, _>(move |_, _| async move {
10149            let completion_item = lsp::CompletionItem {
10150                label: "saturating_sub()".into(),
10151                text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
10152                    lsp::InsertReplaceEdit {
10153                        new_text: "saturating_sub()".to_owned(),
10154                        insert: lsp::Range::new(
10155                            lsp::Position::new(7, 7),
10156                            lsp::Position::new(7, 11),
10157                        ),
10158                        replace: lsp::Range::new(
10159                            lsp::Position::new(7, 7),
10160                            lsp::Position::new(7, 13),
10161                        ),
10162                    },
10163                )),
10164                ..lsp::CompletionItem::default()
10165            };
10166
10167            Ok(Some(lsp::CompletionResponse::Array(vec![completion_item])))
10168        })
10169        .next()
10170        .await
10171        .unwrap();
10172
10173    cx.condition(&editor, |editor, _| editor.context_menu_visible())
10174        .await;
10175
10176    editor
10177        .update_in(cx, |editor, window, cx| {
10178            editor
10179                .confirm_completion_replace(&ConfirmCompletionReplace, window, cx)
10180                .unwrap()
10181        })
10182        .await
10183        .unwrap();
10184
10185    editor.update(cx, |editor, cx| {
10186        assert_text_with_selections(editor, expected_multibuffer, cx);
10187    })
10188}
10189
10190#[gpui::test]
10191async fn test_completion(cx: &mut TestAppContext) {
10192    init_test(cx, |_| {});
10193
10194    let mut cx = EditorLspTestContext::new_rust(
10195        lsp::ServerCapabilities {
10196            completion_provider: Some(lsp::CompletionOptions {
10197                trigger_characters: Some(vec![".".to_string(), ":".to_string()]),
10198                resolve_provider: Some(true),
10199                ..Default::default()
10200            }),
10201            signature_help_provider: Some(lsp::SignatureHelpOptions::default()),
10202            ..Default::default()
10203        },
10204        cx,
10205    )
10206    .await;
10207    let counter = Arc::new(AtomicUsize::new(0));
10208
10209    cx.set_state(indoc! {"
10210        oneˇ
10211        two
10212        three
10213    "});
10214    cx.simulate_keystroke(".");
10215    handle_completion_request(
10216        &mut cx,
10217        indoc! {"
10218            one.|<>
10219            two
10220            three
10221        "},
10222        vec!["first_completion", "second_completion"],
10223        counter.clone(),
10224    )
10225    .await;
10226    cx.condition(|editor, _| editor.context_menu_visible())
10227        .await;
10228    assert_eq!(counter.load(atomic::Ordering::Acquire), 1);
10229
10230    let _handler = handle_signature_help_request(
10231        &mut cx,
10232        lsp::SignatureHelp {
10233            signatures: vec![lsp::SignatureInformation {
10234                label: "test signature".to_string(),
10235                documentation: None,
10236                parameters: Some(vec![lsp::ParameterInformation {
10237                    label: lsp::ParameterLabel::Simple("foo: u8".to_string()),
10238                    documentation: None,
10239                }]),
10240                active_parameter: None,
10241            }],
10242            active_signature: None,
10243            active_parameter: None,
10244        },
10245    );
10246    cx.update_editor(|editor, window, cx| {
10247        assert!(
10248            !editor.signature_help_state.is_shown(),
10249            "No signature help was called for"
10250        );
10251        editor.show_signature_help(&ShowSignatureHelp, window, cx);
10252    });
10253    cx.run_until_parked();
10254    cx.update_editor(|editor, _, _| {
10255        assert!(
10256            !editor.signature_help_state.is_shown(),
10257            "No signature help should be shown when completions menu is open"
10258        );
10259    });
10260
10261    let apply_additional_edits = cx.update_editor(|editor, window, cx| {
10262        editor.context_menu_next(&Default::default(), window, cx);
10263        editor
10264            .confirm_completion(&ConfirmCompletion::default(), window, cx)
10265            .unwrap()
10266    });
10267    cx.assert_editor_state(indoc! {"
10268        one.second_completionˇ
10269        two
10270        three
10271    "});
10272
10273    handle_resolve_completion_request(
10274        &mut cx,
10275        Some(vec![
10276            (
10277                //This overlaps with the primary completion edit which is
10278                //misbehavior from the LSP spec, test that we filter it out
10279                indoc! {"
10280                    one.second_ˇcompletion
10281                    two
10282                    threeˇ
10283                "},
10284                "overlapping additional edit",
10285            ),
10286            (
10287                indoc! {"
10288                    one.second_completion
10289                    two
10290                    threeˇ
10291                "},
10292                "\nadditional edit",
10293            ),
10294        ]),
10295    )
10296    .await;
10297    apply_additional_edits.await.unwrap();
10298    cx.assert_editor_state(indoc! {"
10299        one.second_completionˇ
10300        two
10301        three
10302        additional edit
10303    "});
10304
10305    cx.set_state(indoc! {"
10306        one.second_completion
10307        twoˇ
10308        threeˇ
10309        additional edit
10310    "});
10311    cx.simulate_keystroke(" ");
10312    assert!(cx.editor(|e, _, _| e.context_menu.borrow_mut().is_none()));
10313    cx.simulate_keystroke("s");
10314    assert!(cx.editor(|e, _, _| e.context_menu.borrow_mut().is_none()));
10315
10316    cx.assert_editor_state(indoc! {"
10317        one.second_completion
10318        two sˇ
10319        three sˇ
10320        additional edit
10321    "});
10322    handle_completion_request(
10323        &mut cx,
10324        indoc! {"
10325            one.second_completion
10326            two s
10327            three <s|>
10328            additional edit
10329        "},
10330        vec!["fourth_completion", "fifth_completion", "sixth_completion"],
10331        counter.clone(),
10332    )
10333    .await;
10334    cx.condition(|editor, _| editor.context_menu_visible())
10335        .await;
10336    assert_eq!(counter.load(atomic::Ordering::Acquire), 2);
10337
10338    cx.simulate_keystroke("i");
10339
10340    handle_completion_request(
10341        &mut cx,
10342        indoc! {"
10343            one.second_completion
10344            two si
10345            three <si|>
10346            additional edit
10347        "},
10348        vec!["fourth_completion", "fifth_completion", "sixth_completion"],
10349        counter.clone(),
10350    )
10351    .await;
10352    cx.condition(|editor, _| editor.context_menu_visible())
10353        .await;
10354    assert_eq!(counter.load(atomic::Ordering::Acquire), 3);
10355
10356    let apply_additional_edits = cx.update_editor(|editor, window, cx| {
10357        editor
10358            .confirm_completion(&ConfirmCompletion::default(), window, cx)
10359            .unwrap()
10360    });
10361    cx.assert_editor_state(indoc! {"
10362        one.second_completion
10363        two sixth_completionˇ
10364        three sixth_completionˇ
10365        additional edit
10366    "});
10367
10368    apply_additional_edits.await.unwrap();
10369
10370    update_test_language_settings(&mut cx, |settings| {
10371        settings.defaults.show_completions_on_input = Some(false);
10372    });
10373    cx.set_state("editorˇ");
10374    cx.simulate_keystroke(".");
10375    assert!(cx.editor(|e, _, _| e.context_menu.borrow_mut().is_none()));
10376    cx.simulate_keystrokes("c l o");
10377    cx.assert_editor_state("editor.cloˇ");
10378    assert!(cx.editor(|e, _, _| e.context_menu.borrow_mut().is_none()));
10379    cx.update_editor(|editor, window, cx| {
10380        editor.show_completions(&ShowCompletions { trigger: None }, window, cx);
10381    });
10382    handle_completion_request(
10383        &mut cx,
10384        "editor.<clo|>",
10385        vec!["close", "clobber"],
10386        counter.clone(),
10387    )
10388    .await;
10389    cx.condition(|editor, _| editor.context_menu_visible())
10390        .await;
10391    assert_eq!(counter.load(atomic::Ordering::Acquire), 4);
10392
10393    let apply_additional_edits = cx.update_editor(|editor, window, cx| {
10394        editor
10395            .confirm_completion(&ConfirmCompletion::default(), window, cx)
10396            .unwrap()
10397    });
10398    cx.assert_editor_state("editor.closeˇ");
10399    handle_resolve_completion_request(&mut cx, None).await;
10400    apply_additional_edits.await.unwrap();
10401}
10402
10403#[gpui::test]
10404async fn test_word_completion(cx: &mut TestAppContext) {
10405    let lsp_fetch_timeout_ms = 10;
10406    init_test(cx, |language_settings| {
10407        language_settings.defaults.completions = Some(CompletionSettings {
10408            words: WordsCompletionMode::Fallback,
10409            lsp: true,
10410            lsp_fetch_timeout_ms: 10,
10411            lsp_insert_mode: LspInsertMode::Insert,
10412        });
10413    });
10414
10415    let mut cx = EditorLspTestContext::new_rust(
10416        lsp::ServerCapabilities {
10417            completion_provider: Some(lsp::CompletionOptions {
10418                trigger_characters: Some(vec![".".to_string(), ":".to_string()]),
10419                ..lsp::CompletionOptions::default()
10420            }),
10421            signature_help_provider: Some(lsp::SignatureHelpOptions::default()),
10422            ..lsp::ServerCapabilities::default()
10423        },
10424        cx,
10425    )
10426    .await;
10427
10428    let throttle_completions = Arc::new(AtomicBool::new(false));
10429
10430    let lsp_throttle_completions = throttle_completions.clone();
10431    let _completion_requests_handler =
10432        cx.lsp
10433            .server
10434            .on_request::<lsp::request::Completion, _, _>(move |_, cx| {
10435                let lsp_throttle_completions = lsp_throttle_completions.clone();
10436                let cx = cx.clone();
10437                async move {
10438                    if lsp_throttle_completions.load(atomic::Ordering::Acquire) {
10439                        cx.background_executor()
10440                            .timer(Duration::from_millis(lsp_fetch_timeout_ms * 10))
10441                            .await;
10442                    }
10443                    Ok(Some(lsp::CompletionResponse::Array(vec![
10444                        lsp::CompletionItem {
10445                            label: "first".into(),
10446                            ..lsp::CompletionItem::default()
10447                        },
10448                        lsp::CompletionItem {
10449                            label: "last".into(),
10450                            ..lsp::CompletionItem::default()
10451                        },
10452                    ])))
10453                }
10454            });
10455
10456    cx.set_state(indoc! {"
10457        oneˇ
10458        two
10459        three
10460    "});
10461    cx.simulate_keystroke(".");
10462    cx.executor().run_until_parked();
10463    cx.condition(|editor, _| editor.context_menu_visible())
10464        .await;
10465    cx.update_editor(|editor, window, cx| {
10466        if let Some(CodeContextMenu::Completions(menu)) = editor.context_menu.borrow_mut().as_ref()
10467        {
10468            assert_eq!(
10469                completion_menu_entries(&menu),
10470                &["first", "last"],
10471                "When LSP server is fast to reply, no fallback word completions are used"
10472            );
10473        } else {
10474            panic!("expected completion menu to be open");
10475        }
10476        editor.cancel(&Cancel, window, cx);
10477    });
10478    cx.executor().run_until_parked();
10479    cx.condition(|editor, _| !editor.context_menu_visible())
10480        .await;
10481
10482    throttle_completions.store(true, atomic::Ordering::Release);
10483    cx.simulate_keystroke(".");
10484    cx.executor()
10485        .advance_clock(Duration::from_millis(lsp_fetch_timeout_ms * 2));
10486    cx.executor().run_until_parked();
10487    cx.condition(|editor, _| editor.context_menu_visible())
10488        .await;
10489    cx.update_editor(|editor, _, _| {
10490        if let Some(CodeContextMenu::Completions(menu)) = editor.context_menu.borrow_mut().as_ref()
10491        {
10492            assert_eq!(completion_menu_entries(&menu), &["one", "three", "two"],
10493                "When LSP server is slow, document words can be shown instead, if configured accordingly");
10494        } else {
10495            panic!("expected completion menu to be open");
10496        }
10497    });
10498}
10499
10500#[gpui::test]
10501async fn test_word_completions_do_not_duplicate_lsp_ones(cx: &mut TestAppContext) {
10502    init_test(cx, |language_settings| {
10503        language_settings.defaults.completions = Some(CompletionSettings {
10504            words: WordsCompletionMode::Enabled,
10505            lsp: true,
10506            lsp_fetch_timeout_ms: 0,
10507            lsp_insert_mode: LspInsertMode::Insert,
10508        });
10509    });
10510
10511    let mut cx = EditorLspTestContext::new_rust(
10512        lsp::ServerCapabilities {
10513            completion_provider: Some(lsp::CompletionOptions {
10514                trigger_characters: Some(vec![".".to_string(), ":".to_string()]),
10515                ..lsp::CompletionOptions::default()
10516            }),
10517            signature_help_provider: Some(lsp::SignatureHelpOptions::default()),
10518            ..lsp::ServerCapabilities::default()
10519        },
10520        cx,
10521    )
10522    .await;
10523
10524    let _completion_requests_handler =
10525        cx.lsp
10526            .server
10527            .on_request::<lsp::request::Completion, _, _>(move |_, _| async move {
10528                Ok(Some(lsp::CompletionResponse::Array(vec![
10529                    lsp::CompletionItem {
10530                        label: "first".into(),
10531                        ..lsp::CompletionItem::default()
10532                    },
10533                    lsp::CompletionItem {
10534                        label: "last".into(),
10535                        ..lsp::CompletionItem::default()
10536                    },
10537                ])))
10538            });
10539
10540    cx.set_state(indoc! {"ˇ
10541        first
10542        last
10543        second
10544    "});
10545    cx.simulate_keystroke(".");
10546    cx.executor().run_until_parked();
10547    cx.condition(|editor, _| editor.context_menu_visible())
10548        .await;
10549    cx.update_editor(|editor, _, _| {
10550        if let Some(CodeContextMenu::Completions(menu)) = editor.context_menu.borrow_mut().as_ref()
10551        {
10552            assert_eq!(
10553                completion_menu_entries(&menu),
10554                &["first", "last", "second"],
10555                "Word completions that has the same edit as the any of the LSP ones, should not be proposed"
10556            );
10557        } else {
10558            panic!("expected completion menu to be open");
10559        }
10560    });
10561}
10562
10563#[gpui::test]
10564async fn test_word_completions_continue_on_typing(cx: &mut TestAppContext) {
10565    init_test(cx, |language_settings| {
10566        language_settings.defaults.completions = Some(CompletionSettings {
10567            words: WordsCompletionMode::Disabled,
10568            lsp: true,
10569            lsp_fetch_timeout_ms: 0,
10570            lsp_insert_mode: LspInsertMode::Insert,
10571        });
10572    });
10573
10574    let mut cx = EditorLspTestContext::new_rust(
10575        lsp::ServerCapabilities {
10576            completion_provider: Some(lsp::CompletionOptions {
10577                trigger_characters: Some(vec![".".to_string(), ":".to_string()]),
10578                ..lsp::CompletionOptions::default()
10579            }),
10580            signature_help_provider: Some(lsp::SignatureHelpOptions::default()),
10581            ..lsp::ServerCapabilities::default()
10582        },
10583        cx,
10584    )
10585    .await;
10586
10587    let _completion_requests_handler =
10588        cx.lsp
10589            .server
10590            .on_request::<lsp::request::Completion, _, _>(move |_, _| async move {
10591                panic!("LSP completions should not be queried when dealing with word completions")
10592            });
10593
10594    cx.set_state(indoc! {"ˇ
10595        first
10596        last
10597        second
10598    "});
10599    cx.update_editor(|editor, window, cx| {
10600        editor.show_word_completions(&ShowWordCompletions, window, cx);
10601    });
10602    cx.executor().run_until_parked();
10603    cx.condition(|editor, _| editor.context_menu_visible())
10604        .await;
10605    cx.update_editor(|editor, _, _| {
10606        if let Some(CodeContextMenu::Completions(menu)) = editor.context_menu.borrow_mut().as_ref()
10607        {
10608            assert_eq!(
10609                completion_menu_entries(&menu),
10610                &["first", "last", "second"],
10611                "`ShowWordCompletions` action should show word completions"
10612            );
10613        } else {
10614            panic!("expected completion menu to be open");
10615        }
10616    });
10617
10618    cx.simulate_keystroke("l");
10619    cx.executor().run_until_parked();
10620    cx.condition(|editor, _| editor.context_menu_visible())
10621        .await;
10622    cx.update_editor(|editor, _, _| {
10623        if let Some(CodeContextMenu::Completions(menu)) = editor.context_menu.borrow_mut().as_ref()
10624        {
10625            assert_eq!(
10626                completion_menu_entries(&menu),
10627                &["last"],
10628                "After showing word completions, further editing should filter them and not query the LSP"
10629            );
10630        } else {
10631            panic!("expected completion menu to be open");
10632        }
10633    });
10634}
10635
10636#[gpui::test]
10637async fn test_word_completions_usually_skip_digits(cx: &mut TestAppContext) {
10638    init_test(cx, |language_settings| {
10639        language_settings.defaults.completions = Some(CompletionSettings {
10640            words: WordsCompletionMode::Fallback,
10641            lsp: false,
10642            lsp_fetch_timeout_ms: 0,
10643            lsp_insert_mode: LspInsertMode::Insert,
10644        });
10645    });
10646
10647    let mut cx = EditorLspTestContext::new_rust(lsp::ServerCapabilities::default(), cx).await;
10648
10649    cx.set_state(indoc! {"ˇ
10650        0_usize
10651        let
10652        33
10653        4.5f32
10654    "});
10655    cx.update_editor(|editor, window, cx| {
10656        editor.show_completions(&ShowCompletions::default(), window, cx);
10657    });
10658    cx.executor().run_until_parked();
10659    cx.condition(|editor, _| editor.context_menu_visible())
10660        .await;
10661    cx.update_editor(|editor, window, cx| {
10662        if let Some(CodeContextMenu::Completions(menu)) = editor.context_menu.borrow_mut().as_ref()
10663        {
10664            assert_eq!(
10665                completion_menu_entries(&menu),
10666                &["let"],
10667                "With no digits in the completion query, no digits should be in the word completions"
10668            );
10669        } else {
10670            panic!("expected completion menu to be open");
10671        }
10672        editor.cancel(&Cancel, window, cx);
10673    });
10674
10675    cx.set_state(indoc! {"10676        0_usize
10677        let
10678        3
10679        33.35f32
10680    "});
10681    cx.update_editor(|editor, window, cx| {
10682        editor.show_completions(&ShowCompletions::default(), window, cx);
10683    });
10684    cx.executor().run_until_parked();
10685    cx.condition(|editor, _| editor.context_menu_visible())
10686        .await;
10687    cx.update_editor(|editor, _, _| {
10688        if let Some(CodeContextMenu::Completions(menu)) = editor.context_menu.borrow_mut().as_ref()
10689        {
10690            assert_eq!(completion_menu_entries(&menu), &["33", "35f32"], "The digit is in the completion query, \
10691                return matching words with digits (`33`, `35f32`) but exclude query duplicates (`3`)");
10692        } else {
10693            panic!("expected completion menu to be open");
10694        }
10695    });
10696}
10697
10698fn gen_text_edit(params: &CompletionParams, text: &str) -> Option<lsp::CompletionTextEdit> {
10699    let position = || lsp::Position {
10700        line: params.text_document_position.position.line,
10701        character: params.text_document_position.position.character,
10702    };
10703    Some(lsp::CompletionTextEdit::Edit(lsp::TextEdit {
10704        range: lsp::Range {
10705            start: position(),
10706            end: position(),
10707        },
10708        new_text: text.to_string(),
10709    }))
10710}
10711
10712#[gpui::test]
10713async fn test_multiline_completion(cx: &mut TestAppContext) {
10714    init_test(cx, |_| {});
10715
10716    let fs = FakeFs::new(cx.executor());
10717    fs.insert_tree(
10718        path!("/a"),
10719        json!({
10720            "main.ts": "a",
10721        }),
10722    )
10723    .await;
10724
10725    let project = Project::test(fs, [path!("/a").as_ref()], cx).await;
10726    let language_registry = project.read_with(cx, |project, _| project.languages().clone());
10727    let typescript_language = Arc::new(Language::new(
10728        LanguageConfig {
10729            name: "TypeScript".into(),
10730            matcher: LanguageMatcher {
10731                path_suffixes: vec!["ts".to_string()],
10732                ..LanguageMatcher::default()
10733            },
10734            line_comments: vec!["// ".into()],
10735            ..LanguageConfig::default()
10736        },
10737        Some(tree_sitter_typescript::LANGUAGE_TYPESCRIPT.into()),
10738    ));
10739    language_registry.add(typescript_language.clone());
10740    let mut fake_servers = language_registry.register_fake_lsp(
10741        "TypeScript",
10742        FakeLspAdapter {
10743            capabilities: lsp::ServerCapabilities {
10744                completion_provider: Some(lsp::CompletionOptions {
10745                    trigger_characters: Some(vec![".".to_string(), ":".to_string()]),
10746                    ..lsp::CompletionOptions::default()
10747                }),
10748                signature_help_provider: Some(lsp::SignatureHelpOptions::default()),
10749                ..lsp::ServerCapabilities::default()
10750            },
10751            // Emulate vtsls label generation
10752            label_for_completion: Some(Box::new(|item, _| {
10753                let text = if let Some(description) = item
10754                    .label_details
10755                    .as_ref()
10756                    .and_then(|label_details| label_details.description.as_ref())
10757                {
10758                    format!("{} {}", item.label, description)
10759                } else if let Some(detail) = &item.detail {
10760                    format!("{} {}", item.label, detail)
10761                } else {
10762                    item.label.clone()
10763                };
10764                let len = text.len();
10765                Some(language::CodeLabel {
10766                    text,
10767                    runs: Vec::new(),
10768                    filter_range: 0..len,
10769                })
10770            })),
10771            ..FakeLspAdapter::default()
10772        },
10773    );
10774    let workspace = cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
10775    let cx = &mut VisualTestContext::from_window(*workspace, cx);
10776    let worktree_id = workspace
10777        .update(cx, |workspace, _window, cx| {
10778            workspace.project().update(cx, |project, cx| {
10779                project.worktrees(cx).next().unwrap().read(cx).id()
10780            })
10781        })
10782        .unwrap();
10783    let _buffer = project
10784        .update(cx, |project, cx| {
10785            project.open_local_buffer_with_lsp(path!("/a/main.ts"), cx)
10786        })
10787        .await
10788        .unwrap();
10789    let editor = workspace
10790        .update(cx, |workspace, window, cx| {
10791            workspace.open_path((worktree_id, "main.ts"), None, true, window, cx)
10792        })
10793        .unwrap()
10794        .await
10795        .unwrap()
10796        .downcast::<Editor>()
10797        .unwrap();
10798    let fake_server = fake_servers.next().await.unwrap();
10799
10800    let multiline_label = "StickyHeaderExcerpt {\n            excerpt,\n            next_excerpt_controls_present,\n            next_buffer_row,\n        }: StickyHeaderExcerpt<'_>,";
10801    let multiline_label_2 = "a\nb\nc\n";
10802    let multiline_detail = "[]struct {\n\tSignerId\tstruct {\n\t\tIssuer\t\t\tstring\t`json:\"issuer\"`\n\t\tSubjectSerialNumber\"`\n}}";
10803    let multiline_description = "d\ne\nf\n";
10804    let multiline_detail_2 = "g\nh\ni\n";
10805
10806    let mut completion_handle = fake_server.set_request_handler::<lsp::request::Completion, _, _>(
10807        move |params, _| async move {
10808            Ok(Some(lsp::CompletionResponse::Array(vec![
10809                lsp::CompletionItem {
10810                    label: multiline_label.to_string(),
10811                    text_edit: gen_text_edit(&params, "new_text_1"),
10812                    ..lsp::CompletionItem::default()
10813                },
10814                lsp::CompletionItem {
10815                    label: "single line label 1".to_string(),
10816                    detail: Some(multiline_detail.to_string()),
10817                    text_edit: gen_text_edit(&params, "new_text_2"),
10818                    ..lsp::CompletionItem::default()
10819                },
10820                lsp::CompletionItem {
10821                    label: "single line label 2".to_string(),
10822                    label_details: Some(lsp::CompletionItemLabelDetails {
10823                        description: Some(multiline_description.to_string()),
10824                        detail: None,
10825                    }),
10826                    text_edit: gen_text_edit(&params, "new_text_2"),
10827                    ..lsp::CompletionItem::default()
10828                },
10829                lsp::CompletionItem {
10830                    label: multiline_label_2.to_string(),
10831                    detail: Some(multiline_detail_2.to_string()),
10832                    text_edit: gen_text_edit(&params, "new_text_3"),
10833                    ..lsp::CompletionItem::default()
10834                },
10835                lsp::CompletionItem {
10836                    label: "Label with many     spaces and \t but without newlines".to_string(),
10837                    detail: Some(
10838                        "Details with many     spaces and \t but without newlines".to_string(),
10839                    ),
10840                    text_edit: gen_text_edit(&params, "new_text_4"),
10841                    ..lsp::CompletionItem::default()
10842                },
10843            ])))
10844        },
10845    );
10846
10847    editor.update_in(cx, |editor, window, cx| {
10848        cx.focus_self(window);
10849        editor.move_to_end(&MoveToEnd, window, cx);
10850        editor.handle_input(".", window, cx);
10851    });
10852    cx.run_until_parked();
10853    completion_handle.next().await.unwrap();
10854
10855    editor.update(cx, |editor, _| {
10856        assert!(editor.context_menu_visible());
10857        if let Some(CodeContextMenu::Completions(menu)) = editor.context_menu.borrow_mut().as_ref()
10858        {
10859            let completion_labels = menu
10860                .completions
10861                .borrow()
10862                .iter()
10863                .map(|c| c.label.text.clone())
10864                .collect::<Vec<_>>();
10865            assert_eq!(
10866                completion_labels,
10867                &[
10868                    "StickyHeaderExcerpt { excerpt, next_excerpt_controls_present, next_buffer_row, }: StickyHeaderExcerpt<'_>,",
10869                    "single line label 1 []struct { SignerId struct { Issuer string `json:\"issuer\"` SubjectSerialNumber\"` }}",
10870                    "single line label 2 d e f ",
10871                    "a b c g h i ",
10872                    "Label with many     spaces and \t but without newlines Details with many     spaces and \t but without newlines",
10873                ],
10874                "Completion items should have their labels without newlines, also replacing excessive whitespaces. Completion items without newlines should not be altered.",
10875            );
10876
10877            for completion in menu
10878                .completions
10879                .borrow()
10880                .iter() {
10881                    assert_eq!(
10882                        completion.label.filter_range,
10883                        0..completion.label.text.len(),
10884                        "Adjusted completion items should still keep their filter ranges for the entire label. Item: {completion:?}"
10885                    );
10886                }
10887        } else {
10888            panic!("expected completion menu to be open");
10889        }
10890    });
10891}
10892
10893#[gpui::test]
10894async fn test_completion_page_up_down_keys(cx: &mut TestAppContext) {
10895    init_test(cx, |_| {});
10896    let mut cx = EditorLspTestContext::new_rust(
10897        lsp::ServerCapabilities {
10898            completion_provider: Some(lsp::CompletionOptions {
10899                trigger_characters: Some(vec![".".to_string()]),
10900                ..Default::default()
10901            }),
10902            ..Default::default()
10903        },
10904        cx,
10905    )
10906    .await;
10907    cx.lsp
10908        .set_request_handler::<lsp::request::Completion, _, _>(move |_, _| async move {
10909            Ok(Some(lsp::CompletionResponse::Array(vec![
10910                lsp::CompletionItem {
10911                    label: "first".into(),
10912                    ..Default::default()
10913                },
10914                lsp::CompletionItem {
10915                    label: "last".into(),
10916                    ..Default::default()
10917                },
10918            ])))
10919        });
10920    cx.set_state("variableˇ");
10921    cx.simulate_keystroke(".");
10922    cx.executor().run_until_parked();
10923
10924    cx.update_editor(|editor, _, _| {
10925        if let Some(CodeContextMenu::Completions(menu)) = editor.context_menu.borrow_mut().as_ref()
10926        {
10927            assert_eq!(completion_menu_entries(&menu), &["first", "last"]);
10928        } else {
10929            panic!("expected completion menu to be open");
10930        }
10931    });
10932
10933    cx.update_editor(|editor, window, cx| {
10934        editor.move_page_down(&MovePageDown::default(), window, cx);
10935        if let Some(CodeContextMenu::Completions(menu)) = editor.context_menu.borrow_mut().as_ref()
10936        {
10937            assert!(
10938                menu.selected_item == 1,
10939                "expected PageDown to select the last item from the context menu"
10940            );
10941        } else {
10942            panic!("expected completion menu to stay open after PageDown");
10943        }
10944    });
10945
10946    cx.update_editor(|editor, window, cx| {
10947        editor.move_page_up(&MovePageUp::default(), window, cx);
10948        if let Some(CodeContextMenu::Completions(menu)) = editor.context_menu.borrow_mut().as_ref()
10949        {
10950            assert!(
10951                menu.selected_item == 0,
10952                "expected PageUp to select the first item from the context menu"
10953            );
10954        } else {
10955            panic!("expected completion menu to stay open after PageUp");
10956        }
10957    });
10958}
10959
10960#[gpui::test]
10961async fn test_completion_sort(cx: &mut TestAppContext) {
10962    init_test(cx, |_| {});
10963    let mut cx = EditorLspTestContext::new_rust(
10964        lsp::ServerCapabilities {
10965            completion_provider: Some(lsp::CompletionOptions {
10966                trigger_characters: Some(vec![".".to_string()]),
10967                ..Default::default()
10968            }),
10969            ..Default::default()
10970        },
10971        cx,
10972    )
10973    .await;
10974    cx.lsp
10975        .set_request_handler::<lsp::request::Completion, _, _>(move |_, _| async move {
10976            Ok(Some(lsp::CompletionResponse::Array(vec![
10977                lsp::CompletionItem {
10978                    label: "Range".into(),
10979                    sort_text: Some("a".into()),
10980                    ..Default::default()
10981                },
10982                lsp::CompletionItem {
10983                    label: "r".into(),
10984                    sort_text: Some("b".into()),
10985                    ..Default::default()
10986                },
10987                lsp::CompletionItem {
10988                    label: "ret".into(),
10989                    sort_text: Some("c".into()),
10990                    ..Default::default()
10991                },
10992                lsp::CompletionItem {
10993                    label: "return".into(),
10994                    sort_text: Some("d".into()),
10995                    ..Default::default()
10996                },
10997                lsp::CompletionItem {
10998                    label: "slice".into(),
10999                    sort_text: Some("d".into()),
11000                    ..Default::default()
11001                },
11002            ])))
11003        });
11004    cx.set_state("");
11005    cx.executor().run_until_parked();
11006    cx.update_editor(|editor, window, cx| {
11007        editor.show_completions(
11008            &ShowCompletions {
11009                trigger: Some("r".into()),
11010            },
11011            window,
11012            cx,
11013        );
11014    });
11015    cx.executor().run_until_parked();
11016
11017    cx.update_editor(|editor, _, _| {
11018        if let Some(CodeContextMenu::Completions(menu)) = editor.context_menu.borrow_mut().as_ref()
11019        {
11020            assert_eq!(
11021                completion_menu_entries(&menu),
11022                &["r", "ret", "Range", "return"]
11023            );
11024        } else {
11025            panic!("expected completion menu to be open");
11026        }
11027    });
11028}
11029
11030#[gpui::test]
11031async fn test_as_is_completions(cx: &mut TestAppContext) {
11032    init_test(cx, |_| {});
11033    let mut cx = EditorLspTestContext::new_rust(
11034        lsp::ServerCapabilities {
11035            completion_provider: Some(lsp::CompletionOptions {
11036                ..Default::default()
11037            }),
11038            ..Default::default()
11039        },
11040        cx,
11041    )
11042    .await;
11043    cx.lsp
11044        .set_request_handler::<lsp::request::Completion, _, _>(move |_, _| async move {
11045            Ok(Some(lsp::CompletionResponse::Array(vec![
11046                lsp::CompletionItem {
11047                    label: "unsafe".into(),
11048                    text_edit: Some(lsp::CompletionTextEdit::Edit(lsp::TextEdit {
11049                        range: lsp::Range {
11050                            start: lsp::Position {
11051                                line: 1,
11052                                character: 2,
11053                            },
11054                            end: lsp::Position {
11055                                line: 1,
11056                                character: 3,
11057                            },
11058                        },
11059                        new_text: "unsafe".to_string(),
11060                    })),
11061                    insert_text_mode: Some(lsp::InsertTextMode::AS_IS),
11062                    ..Default::default()
11063                },
11064            ])))
11065        });
11066    cx.set_state("fn a() {}\n");
11067    cx.executor().run_until_parked();
11068    cx.update_editor(|editor, window, cx| {
11069        editor.show_completions(
11070            &ShowCompletions {
11071                trigger: Some("\n".into()),
11072            },
11073            window,
11074            cx,
11075        );
11076    });
11077    cx.executor().run_until_parked();
11078
11079    cx.update_editor(|editor, window, cx| {
11080        editor.confirm_completion(&Default::default(), window, cx)
11081    });
11082    cx.executor().run_until_parked();
11083    cx.assert_editor_state("fn a() {}\n  unsafeˇ");
11084}
11085
11086#[gpui::test]
11087async fn test_no_duplicated_completion_requests(cx: &mut TestAppContext) {
11088    init_test(cx, |_| {});
11089
11090    let mut cx = EditorLspTestContext::new_rust(
11091        lsp::ServerCapabilities {
11092            completion_provider: Some(lsp::CompletionOptions {
11093                trigger_characters: Some(vec![".".to_string()]),
11094                resolve_provider: Some(true),
11095                ..Default::default()
11096            }),
11097            ..Default::default()
11098        },
11099        cx,
11100    )
11101    .await;
11102
11103    cx.set_state("fn main() { let a = 2ˇ; }");
11104    cx.simulate_keystroke(".");
11105    let completion_item = lsp::CompletionItem {
11106        label: "Some".into(),
11107        kind: Some(lsp::CompletionItemKind::SNIPPET),
11108        detail: Some("Wrap the expression in an `Option::Some`".to_string()),
11109        documentation: Some(lsp::Documentation::MarkupContent(lsp::MarkupContent {
11110            kind: lsp::MarkupKind::Markdown,
11111            value: "```rust\nSome(2)\n```".to_string(),
11112        })),
11113        deprecated: Some(false),
11114        sort_text: Some("Some".to_string()),
11115        filter_text: Some("Some".to_string()),
11116        insert_text_format: Some(lsp::InsertTextFormat::SNIPPET),
11117        text_edit: Some(lsp::CompletionTextEdit::Edit(lsp::TextEdit {
11118            range: lsp::Range {
11119                start: lsp::Position {
11120                    line: 0,
11121                    character: 22,
11122                },
11123                end: lsp::Position {
11124                    line: 0,
11125                    character: 22,
11126                },
11127            },
11128            new_text: "Some(2)".to_string(),
11129        })),
11130        additional_text_edits: Some(vec![lsp::TextEdit {
11131            range: lsp::Range {
11132                start: lsp::Position {
11133                    line: 0,
11134                    character: 20,
11135                },
11136                end: lsp::Position {
11137                    line: 0,
11138                    character: 22,
11139                },
11140            },
11141            new_text: "".to_string(),
11142        }]),
11143        ..Default::default()
11144    };
11145
11146    let closure_completion_item = completion_item.clone();
11147    let counter = Arc::new(AtomicUsize::new(0));
11148    let counter_clone = counter.clone();
11149    let mut request = cx.set_request_handler::<lsp::request::Completion, _, _>(move |_, _, _| {
11150        let task_completion_item = closure_completion_item.clone();
11151        counter_clone.fetch_add(1, atomic::Ordering::Release);
11152        async move {
11153            Ok(Some(lsp::CompletionResponse::Array(vec![
11154                task_completion_item,
11155            ])))
11156        }
11157    });
11158
11159    cx.condition(|editor, _| editor.context_menu_visible())
11160        .await;
11161    cx.assert_editor_state("fn main() { let a = 2.ˇ; }");
11162    assert!(request.next().await.is_some());
11163    assert_eq!(counter.load(atomic::Ordering::Acquire), 1);
11164
11165    cx.simulate_keystrokes("S o m");
11166    cx.condition(|editor, _| editor.context_menu_visible())
11167        .await;
11168    cx.assert_editor_state("fn main() { let a = 2.Somˇ; }");
11169    assert!(request.next().await.is_some());
11170    assert!(request.next().await.is_some());
11171    assert!(request.next().await.is_some());
11172    request.close();
11173    assert!(request.next().await.is_none());
11174    assert_eq!(
11175        counter.load(atomic::Ordering::Acquire),
11176        4,
11177        "With the completions menu open, only one LSP request should happen per input"
11178    );
11179}
11180
11181#[gpui::test]
11182async fn test_toggle_comment(cx: &mut TestAppContext) {
11183    init_test(cx, |_| {});
11184    let mut cx = EditorTestContext::new(cx).await;
11185    let language = Arc::new(Language::new(
11186        LanguageConfig {
11187            line_comments: vec!["// ".into(), "//! ".into(), "/// ".into()],
11188            ..Default::default()
11189        },
11190        Some(tree_sitter_rust::LANGUAGE.into()),
11191    ));
11192    cx.update_buffer(|buffer, cx| buffer.set_language(Some(language), cx));
11193
11194    // If multiple selections intersect a line, the line is only toggled once.
11195    cx.set_state(indoc! {"
11196        fn a() {
11197            «//b();
11198            ˇ»// «c();
11199            //ˇ»  d();
11200        }
11201    "});
11202
11203    cx.update_editor(|e, window, cx| e.toggle_comments(&ToggleComments::default(), window, cx));
11204
11205    cx.assert_editor_state(indoc! {"
11206        fn a() {
11207            «b();
11208            c();
11209            ˇ» d();
11210        }
11211    "});
11212
11213    // The comment prefix is inserted at the same column for every line in a
11214    // selection.
11215    cx.update_editor(|e, window, cx| e.toggle_comments(&ToggleComments::default(), window, cx));
11216
11217    cx.assert_editor_state(indoc! {"
11218        fn a() {
11219            // «b();
11220            // c();
11221            ˇ»//  d();
11222        }
11223    "});
11224
11225    // If a selection ends at the beginning of a line, that line is not toggled.
11226    cx.set_selections_state(indoc! {"
11227        fn a() {
11228            // b();
11229            «// c();
11230        ˇ»    //  d();
11231        }
11232    "});
11233
11234    cx.update_editor(|e, window, cx| e.toggle_comments(&ToggleComments::default(), window, cx));
11235
11236    cx.assert_editor_state(indoc! {"
11237        fn a() {
11238            // b();
11239            «c();
11240        ˇ»    //  d();
11241        }
11242    "});
11243
11244    // If a selection span a single line and is empty, the line is toggled.
11245    cx.set_state(indoc! {"
11246        fn a() {
11247            a();
11248            b();
11249        ˇ
11250        }
11251    "});
11252
11253    cx.update_editor(|e, window, cx| e.toggle_comments(&ToggleComments::default(), window, cx));
11254
11255    cx.assert_editor_state(indoc! {"
11256        fn a() {
11257            a();
11258            b();
11259        //•ˇ
11260        }
11261    "});
11262
11263    // If a selection span multiple lines, empty lines are not toggled.
11264    cx.set_state(indoc! {"
11265        fn a() {
11266            «a();
11267
11268            c();ˇ»
11269        }
11270    "});
11271
11272    cx.update_editor(|e, window, cx| e.toggle_comments(&ToggleComments::default(), window, cx));
11273
11274    cx.assert_editor_state(indoc! {"
11275        fn a() {
11276            // «a();
11277
11278            // c();ˇ»
11279        }
11280    "});
11281
11282    // If a selection includes multiple comment prefixes, all lines are uncommented.
11283    cx.set_state(indoc! {"
11284        fn a() {
11285            «// a();
11286            /// b();
11287            //! c();ˇ»
11288        }
11289    "});
11290
11291    cx.update_editor(|e, window, cx| e.toggle_comments(&ToggleComments::default(), window, cx));
11292
11293    cx.assert_editor_state(indoc! {"
11294        fn a() {
11295            «a();
11296            b();
11297            c();ˇ»
11298        }
11299    "});
11300}
11301
11302#[gpui::test]
11303async fn test_toggle_comment_ignore_indent(cx: &mut TestAppContext) {
11304    init_test(cx, |_| {});
11305    let mut cx = EditorTestContext::new(cx).await;
11306    let language = Arc::new(Language::new(
11307        LanguageConfig {
11308            line_comments: vec!["// ".into(), "//! ".into(), "/// ".into()],
11309            ..Default::default()
11310        },
11311        Some(tree_sitter_rust::LANGUAGE.into()),
11312    ));
11313    cx.update_buffer(|buffer, cx| buffer.set_language(Some(language), cx));
11314
11315    let toggle_comments = &ToggleComments {
11316        advance_downwards: false,
11317        ignore_indent: true,
11318    };
11319
11320    // If multiple selections intersect a line, the line is only toggled once.
11321    cx.set_state(indoc! {"
11322        fn a() {
11323        //    «b();
11324        //    c();
11325        //    ˇ» d();
11326        }
11327    "});
11328
11329    cx.update_editor(|e, window, cx| e.toggle_comments(toggle_comments, window, cx));
11330
11331    cx.assert_editor_state(indoc! {"
11332        fn a() {
11333            «b();
11334            c();
11335            ˇ» d();
11336        }
11337    "});
11338
11339    // The comment prefix is inserted at the beginning of each line
11340    cx.update_editor(|e, window, cx| e.toggle_comments(toggle_comments, window, cx));
11341
11342    cx.assert_editor_state(indoc! {"
11343        fn a() {
11344        //    «b();
11345        //    c();
11346        //    ˇ» d();
11347        }
11348    "});
11349
11350    // If a selection ends at the beginning of a line, that line is not toggled.
11351    cx.set_selections_state(indoc! {"
11352        fn a() {
11353        //    b();
11354        //    «c();
11355        ˇ»//     d();
11356        }
11357    "});
11358
11359    cx.update_editor(|e, window, cx| e.toggle_comments(toggle_comments, window, cx));
11360
11361    cx.assert_editor_state(indoc! {"
11362        fn a() {
11363        //    b();
11364            «c();
11365        ˇ»//     d();
11366        }
11367    "});
11368
11369    // If a selection span a single line and is empty, the line is toggled.
11370    cx.set_state(indoc! {"
11371        fn a() {
11372            a();
11373            b();
11374        ˇ
11375        }
11376    "});
11377
11378    cx.update_editor(|e, window, cx| e.toggle_comments(toggle_comments, window, cx));
11379
11380    cx.assert_editor_state(indoc! {"
11381        fn a() {
11382            a();
11383            b();
11384        //ˇ
11385        }
11386    "});
11387
11388    // If a selection span multiple lines, empty lines are not toggled.
11389    cx.set_state(indoc! {"
11390        fn a() {
11391            «a();
11392
11393            c();ˇ»
11394        }
11395    "});
11396
11397    cx.update_editor(|e, window, cx| e.toggle_comments(toggle_comments, window, cx));
11398
11399    cx.assert_editor_state(indoc! {"
11400        fn a() {
11401        //    «a();
11402
11403        //    c();ˇ»
11404        }
11405    "});
11406
11407    // If a selection includes multiple comment prefixes, all lines are uncommented.
11408    cx.set_state(indoc! {"
11409        fn a() {
11410        //    «a();
11411        ///    b();
11412        //!    c();ˇ»
11413        }
11414    "});
11415
11416    cx.update_editor(|e, window, cx| e.toggle_comments(toggle_comments, window, cx));
11417
11418    cx.assert_editor_state(indoc! {"
11419        fn a() {
11420            «a();
11421            b();
11422            c();ˇ»
11423        }
11424    "});
11425}
11426
11427#[gpui::test]
11428async fn test_advance_downward_on_toggle_comment(cx: &mut TestAppContext) {
11429    init_test(cx, |_| {});
11430
11431    let language = Arc::new(Language::new(
11432        LanguageConfig {
11433            line_comments: vec!["// ".into()],
11434            ..Default::default()
11435        },
11436        Some(tree_sitter_rust::LANGUAGE.into()),
11437    ));
11438
11439    let mut cx = EditorTestContext::new(cx).await;
11440
11441    cx.language_registry().add(language.clone());
11442    cx.update_buffer(|buffer, cx| {
11443        buffer.set_language(Some(language), cx);
11444    });
11445
11446    let toggle_comments = &ToggleComments {
11447        advance_downwards: true,
11448        ignore_indent: false,
11449    };
11450
11451    // Single cursor on one line -> advance
11452    // Cursor moves horizontally 3 characters as well on non-blank line
11453    cx.set_state(indoc!(
11454        "fn a() {
11455             ˇdog();
11456             cat();
11457        }"
11458    ));
11459    cx.update_editor(|editor, window, cx| {
11460        editor.toggle_comments(toggle_comments, window, cx);
11461    });
11462    cx.assert_editor_state(indoc!(
11463        "fn a() {
11464             // dog();
11465             catˇ();
11466        }"
11467    ));
11468
11469    // Single selection on one line -> don't advance
11470    cx.set_state(indoc!(
11471        "fn a() {
11472             «dog()ˇ»;
11473             cat();
11474        }"
11475    ));
11476    cx.update_editor(|editor, window, cx| {
11477        editor.toggle_comments(toggle_comments, window, cx);
11478    });
11479    cx.assert_editor_state(indoc!(
11480        "fn a() {
11481             // «dog()ˇ»;
11482             cat();
11483        }"
11484    ));
11485
11486    // Multiple cursors on one line -> advance
11487    cx.set_state(indoc!(
11488        "fn a() {
11489             ˇdˇog();
11490             cat();
11491        }"
11492    ));
11493    cx.update_editor(|editor, window, cx| {
11494        editor.toggle_comments(toggle_comments, window, cx);
11495    });
11496    cx.assert_editor_state(indoc!(
11497        "fn a() {
11498             // dog();
11499             catˇ(ˇ);
11500        }"
11501    ));
11502
11503    // Multiple cursors on one line, with selection -> don't advance
11504    cx.set_state(indoc!(
11505        "fn a() {
11506             ˇdˇog«()ˇ»;
11507             cat();
11508        }"
11509    ));
11510    cx.update_editor(|editor, window, cx| {
11511        editor.toggle_comments(toggle_comments, window, cx);
11512    });
11513    cx.assert_editor_state(indoc!(
11514        "fn a() {
11515             // ˇdˇog«()ˇ»;
11516             cat();
11517        }"
11518    ));
11519
11520    // Single cursor on one line -> advance
11521    // Cursor moves to column 0 on blank line
11522    cx.set_state(indoc!(
11523        "fn a() {
11524             ˇdog();
11525
11526             cat();
11527        }"
11528    ));
11529    cx.update_editor(|editor, window, cx| {
11530        editor.toggle_comments(toggle_comments, window, cx);
11531    });
11532    cx.assert_editor_state(indoc!(
11533        "fn a() {
11534             // dog();
11535        ˇ
11536             cat();
11537        }"
11538    ));
11539
11540    // Single cursor on one line -> advance
11541    // Cursor starts and ends at column 0
11542    cx.set_state(indoc!(
11543        "fn a() {
11544         ˇ    dog();
11545             cat();
11546        }"
11547    ));
11548    cx.update_editor(|editor, window, cx| {
11549        editor.toggle_comments(toggle_comments, window, cx);
11550    });
11551    cx.assert_editor_state(indoc!(
11552        "fn a() {
11553             // dog();
11554         ˇ    cat();
11555        }"
11556    ));
11557}
11558
11559#[gpui::test]
11560async fn test_toggle_block_comment(cx: &mut TestAppContext) {
11561    init_test(cx, |_| {});
11562
11563    let mut cx = EditorTestContext::new(cx).await;
11564
11565    let html_language = Arc::new(
11566        Language::new(
11567            LanguageConfig {
11568                name: "HTML".into(),
11569                block_comment: Some(("<!-- ".into(), " -->".into())),
11570                ..Default::default()
11571            },
11572            Some(tree_sitter_html::LANGUAGE.into()),
11573        )
11574        .with_injection_query(
11575            r#"
11576            (script_element
11577                (raw_text) @injection.content
11578                (#set! injection.language "javascript"))
11579            "#,
11580        )
11581        .unwrap(),
11582    );
11583
11584    let javascript_language = Arc::new(Language::new(
11585        LanguageConfig {
11586            name: "JavaScript".into(),
11587            line_comments: vec!["// ".into()],
11588            ..Default::default()
11589        },
11590        Some(tree_sitter_typescript::LANGUAGE_TSX.into()),
11591    ));
11592
11593    cx.language_registry().add(html_language.clone());
11594    cx.language_registry().add(javascript_language.clone());
11595    cx.update_buffer(|buffer, cx| {
11596        buffer.set_language(Some(html_language), cx);
11597    });
11598
11599    // Toggle comments for empty selections
11600    cx.set_state(
11601        &r#"
11602            <p>A</p>ˇ
11603            <p>B</p>ˇ
11604            <p>C</p>ˇ
11605        "#
11606        .unindent(),
11607    );
11608    cx.update_editor(|editor, window, cx| {
11609        editor.toggle_comments(&ToggleComments::default(), window, cx)
11610    });
11611    cx.assert_editor_state(
11612        &r#"
11613            <!-- <p>A</p>ˇ -->
11614            <!-- <p>B</p>ˇ -->
11615            <!-- <p>C</p>ˇ -->
11616        "#
11617        .unindent(),
11618    );
11619    cx.update_editor(|editor, window, cx| {
11620        editor.toggle_comments(&ToggleComments::default(), window, cx)
11621    });
11622    cx.assert_editor_state(
11623        &r#"
11624            <p>A</p>ˇ
11625            <p>B</p>ˇ
11626            <p>C</p>ˇ
11627        "#
11628        .unindent(),
11629    );
11630
11631    // Toggle comments for mixture of empty and non-empty selections, where
11632    // multiple selections occupy a given line.
11633    cx.set_state(
11634        &r#"
11635            <p>A«</p>
11636            <p>ˇ»B</p>ˇ
11637            <p>C«</p>
11638            <p>ˇ»D</p>ˇ
11639        "#
11640        .unindent(),
11641    );
11642
11643    cx.update_editor(|editor, window, cx| {
11644        editor.toggle_comments(&ToggleComments::default(), window, cx)
11645    });
11646    cx.assert_editor_state(
11647        &r#"
11648            <!-- <p>A«</p>
11649            <p>ˇ»B</p>ˇ -->
11650            <!-- <p>C«</p>
11651            <p>ˇ»D</p>ˇ -->
11652        "#
11653        .unindent(),
11654    );
11655    cx.update_editor(|editor, window, cx| {
11656        editor.toggle_comments(&ToggleComments::default(), window, cx)
11657    });
11658    cx.assert_editor_state(
11659        &r#"
11660            <p>A«</p>
11661            <p>ˇ»B</p>ˇ
11662            <p>C«</p>
11663            <p>ˇ»D</p>ˇ
11664        "#
11665        .unindent(),
11666    );
11667
11668    // Toggle comments when different languages are active for different
11669    // selections.
11670    cx.set_state(
11671        &r#"
11672            ˇ<script>
11673                ˇvar x = new Y();
11674            ˇ</script>
11675        "#
11676        .unindent(),
11677    );
11678    cx.executor().run_until_parked();
11679    cx.update_editor(|editor, window, cx| {
11680        editor.toggle_comments(&ToggleComments::default(), window, cx)
11681    });
11682    // TODO this is how it actually worked in Zed Stable, which is not very ergonomic.
11683    // Uncommenting and commenting from this position brings in even more wrong artifacts.
11684    cx.assert_editor_state(
11685        &r#"
11686            <!-- ˇ<script> -->
11687                // ˇvar x = new Y();
11688            <!-- ˇ</script> -->
11689        "#
11690        .unindent(),
11691    );
11692}
11693
11694#[gpui::test]
11695fn test_editing_disjoint_excerpts(cx: &mut TestAppContext) {
11696    init_test(cx, |_| {});
11697
11698    let buffer = cx.new(|cx| Buffer::local(sample_text(3, 4, 'a'), cx));
11699    let multibuffer = cx.new(|cx| {
11700        let mut multibuffer = MultiBuffer::new(ReadWrite);
11701        multibuffer.push_excerpts(
11702            buffer.clone(),
11703            [
11704                ExcerptRange::new(Point::new(0, 0)..Point::new(0, 4)),
11705                ExcerptRange::new(Point::new(1, 0)..Point::new(1, 4)),
11706            ],
11707            cx,
11708        );
11709        assert_eq!(multibuffer.read(cx).text(), "aaaa\nbbbb");
11710        multibuffer
11711    });
11712
11713    let (editor, cx) = cx.add_window_view(|window, cx| build_editor(multibuffer, window, cx));
11714    editor.update_in(cx, |editor, window, cx| {
11715        assert_eq!(editor.text(cx), "aaaa\nbbbb");
11716        editor.change_selections(None, window, cx, |s| {
11717            s.select_ranges([
11718                Point::new(0, 0)..Point::new(0, 0),
11719                Point::new(1, 0)..Point::new(1, 0),
11720            ])
11721        });
11722
11723        editor.handle_input("X", window, cx);
11724        assert_eq!(editor.text(cx), "Xaaaa\nXbbbb");
11725        assert_eq!(
11726            editor.selections.ranges(cx),
11727            [
11728                Point::new(0, 1)..Point::new(0, 1),
11729                Point::new(1, 1)..Point::new(1, 1),
11730            ]
11731        );
11732
11733        // Ensure the cursor's head is respected when deleting across an excerpt boundary.
11734        editor.change_selections(None, window, cx, |s| {
11735            s.select_ranges([Point::new(0, 2)..Point::new(1, 2)])
11736        });
11737        editor.backspace(&Default::default(), window, cx);
11738        assert_eq!(editor.text(cx), "Xa\nbbb");
11739        assert_eq!(
11740            editor.selections.ranges(cx),
11741            [Point::new(1, 0)..Point::new(1, 0)]
11742        );
11743
11744        editor.change_selections(None, window, cx, |s| {
11745            s.select_ranges([Point::new(1, 1)..Point::new(0, 1)])
11746        });
11747        editor.backspace(&Default::default(), window, cx);
11748        assert_eq!(editor.text(cx), "X\nbb");
11749        assert_eq!(
11750            editor.selections.ranges(cx),
11751            [Point::new(0, 1)..Point::new(0, 1)]
11752        );
11753    });
11754}
11755
11756#[gpui::test]
11757fn test_editing_overlapping_excerpts(cx: &mut TestAppContext) {
11758    init_test(cx, |_| {});
11759
11760    let markers = vec![('[', ']').into(), ('(', ')').into()];
11761    let (initial_text, mut excerpt_ranges) = marked_text_ranges_by(
11762        indoc! {"
11763            [aaaa
11764            (bbbb]
11765            cccc)",
11766        },
11767        markers.clone(),
11768    );
11769    let excerpt_ranges = markers.into_iter().map(|marker| {
11770        let context = excerpt_ranges.remove(&marker).unwrap()[0].clone();
11771        ExcerptRange::new(context.clone())
11772    });
11773    let buffer = cx.new(|cx| Buffer::local(initial_text, cx));
11774    let multibuffer = cx.new(|cx| {
11775        let mut multibuffer = MultiBuffer::new(ReadWrite);
11776        multibuffer.push_excerpts(buffer, excerpt_ranges, cx);
11777        multibuffer
11778    });
11779
11780    let (editor, cx) = cx.add_window_view(|window, cx| build_editor(multibuffer, window, cx));
11781    editor.update_in(cx, |editor, window, cx| {
11782        let (expected_text, selection_ranges) = marked_text_ranges(
11783            indoc! {"
11784                aaaa
11785                bˇbbb
11786                bˇbbˇb
11787                cccc"
11788            },
11789            true,
11790        );
11791        assert_eq!(editor.text(cx), expected_text);
11792        editor.change_selections(None, window, cx, |s| s.select_ranges(selection_ranges));
11793
11794        editor.handle_input("X", window, cx);
11795
11796        let (expected_text, expected_selections) = marked_text_ranges(
11797            indoc! {"
11798                aaaa
11799                bXˇbbXb
11800                bXˇbbXˇb
11801                cccc"
11802            },
11803            false,
11804        );
11805        assert_eq!(editor.text(cx), expected_text);
11806        assert_eq!(editor.selections.ranges(cx), expected_selections);
11807
11808        editor.newline(&Newline, window, cx);
11809        let (expected_text, expected_selections) = marked_text_ranges(
11810            indoc! {"
11811                aaaa
11812                bX
11813                ˇbbX
11814                b
11815                bX
11816                ˇbbX
11817                ˇb
11818                cccc"
11819            },
11820            false,
11821        );
11822        assert_eq!(editor.text(cx), expected_text);
11823        assert_eq!(editor.selections.ranges(cx), expected_selections);
11824    });
11825}
11826
11827#[gpui::test]
11828fn test_refresh_selections(cx: &mut TestAppContext) {
11829    init_test(cx, |_| {});
11830
11831    let buffer = cx.new(|cx| Buffer::local(sample_text(3, 4, 'a'), cx));
11832    let mut excerpt1_id = None;
11833    let multibuffer = cx.new(|cx| {
11834        let mut multibuffer = MultiBuffer::new(ReadWrite);
11835        excerpt1_id = multibuffer
11836            .push_excerpts(
11837                buffer.clone(),
11838                [
11839                    ExcerptRange::new(Point::new(0, 0)..Point::new(1, 4)),
11840                    ExcerptRange::new(Point::new(1, 0)..Point::new(2, 4)),
11841                ],
11842                cx,
11843            )
11844            .into_iter()
11845            .next();
11846        assert_eq!(multibuffer.read(cx).text(), "aaaa\nbbbb\nbbbb\ncccc");
11847        multibuffer
11848    });
11849
11850    let editor = cx.add_window(|window, cx| {
11851        let mut editor = build_editor(multibuffer.clone(), window, cx);
11852        let snapshot = editor.snapshot(window, cx);
11853        editor.change_selections(None, window, cx, |s| {
11854            s.select_ranges([Point::new(1, 3)..Point::new(1, 3)])
11855        });
11856        editor.begin_selection(
11857            Point::new(2, 1).to_display_point(&snapshot),
11858            true,
11859            1,
11860            window,
11861            cx,
11862        );
11863        assert_eq!(
11864            editor.selections.ranges(cx),
11865            [
11866                Point::new(1, 3)..Point::new(1, 3),
11867                Point::new(2, 1)..Point::new(2, 1),
11868            ]
11869        );
11870        editor
11871    });
11872
11873    // Refreshing selections is a no-op when excerpts haven't changed.
11874    _ = editor.update(cx, |editor, window, cx| {
11875        editor.change_selections(None, window, cx, |s| s.refresh());
11876        assert_eq!(
11877            editor.selections.ranges(cx),
11878            [
11879                Point::new(1, 3)..Point::new(1, 3),
11880                Point::new(2, 1)..Point::new(2, 1),
11881            ]
11882        );
11883    });
11884
11885    multibuffer.update(cx, |multibuffer, cx| {
11886        multibuffer.remove_excerpts([excerpt1_id.unwrap()], cx);
11887    });
11888    _ = editor.update(cx, |editor, window, cx| {
11889        // Removing an excerpt causes the first selection to become degenerate.
11890        assert_eq!(
11891            editor.selections.ranges(cx),
11892            [
11893                Point::new(0, 0)..Point::new(0, 0),
11894                Point::new(0, 1)..Point::new(0, 1)
11895            ]
11896        );
11897
11898        // Refreshing selections will relocate the first selection to the original buffer
11899        // location.
11900        editor.change_selections(None, window, cx, |s| s.refresh());
11901        assert_eq!(
11902            editor.selections.ranges(cx),
11903            [
11904                Point::new(0, 1)..Point::new(0, 1),
11905                Point::new(0, 3)..Point::new(0, 3)
11906            ]
11907        );
11908        assert!(editor.selections.pending_anchor().is_some());
11909    });
11910}
11911
11912#[gpui::test]
11913fn test_refresh_selections_while_selecting_with_mouse(cx: &mut TestAppContext) {
11914    init_test(cx, |_| {});
11915
11916    let buffer = cx.new(|cx| Buffer::local(sample_text(3, 4, 'a'), cx));
11917    let mut excerpt1_id = None;
11918    let multibuffer = cx.new(|cx| {
11919        let mut multibuffer = MultiBuffer::new(ReadWrite);
11920        excerpt1_id = multibuffer
11921            .push_excerpts(
11922                buffer.clone(),
11923                [
11924                    ExcerptRange::new(Point::new(0, 0)..Point::new(1, 4)),
11925                    ExcerptRange::new(Point::new(1, 0)..Point::new(2, 4)),
11926                ],
11927                cx,
11928            )
11929            .into_iter()
11930            .next();
11931        assert_eq!(multibuffer.read(cx).text(), "aaaa\nbbbb\nbbbb\ncccc");
11932        multibuffer
11933    });
11934
11935    let editor = cx.add_window(|window, cx| {
11936        let mut editor = build_editor(multibuffer.clone(), window, cx);
11937        let snapshot = editor.snapshot(window, cx);
11938        editor.begin_selection(
11939            Point::new(1, 3).to_display_point(&snapshot),
11940            false,
11941            1,
11942            window,
11943            cx,
11944        );
11945        assert_eq!(
11946            editor.selections.ranges(cx),
11947            [Point::new(1, 3)..Point::new(1, 3)]
11948        );
11949        editor
11950    });
11951
11952    multibuffer.update(cx, |multibuffer, cx| {
11953        multibuffer.remove_excerpts([excerpt1_id.unwrap()], cx);
11954    });
11955    _ = editor.update(cx, |editor, window, cx| {
11956        assert_eq!(
11957            editor.selections.ranges(cx),
11958            [Point::new(0, 0)..Point::new(0, 0)]
11959        );
11960
11961        // Ensure we don't panic when selections are refreshed and that the pending selection is finalized.
11962        editor.change_selections(None, window, cx, |s| s.refresh());
11963        assert_eq!(
11964            editor.selections.ranges(cx),
11965            [Point::new(0, 3)..Point::new(0, 3)]
11966        );
11967        assert!(editor.selections.pending_anchor().is_some());
11968    });
11969}
11970
11971#[gpui::test]
11972async fn test_extra_newline_insertion(cx: &mut TestAppContext) {
11973    init_test(cx, |_| {});
11974
11975    let language = Arc::new(
11976        Language::new(
11977            LanguageConfig {
11978                brackets: BracketPairConfig {
11979                    pairs: vec![
11980                        BracketPair {
11981                            start: "{".to_string(),
11982                            end: "}".to_string(),
11983                            close: true,
11984                            surround: true,
11985                            newline: true,
11986                        },
11987                        BracketPair {
11988                            start: "/* ".to_string(),
11989                            end: " */".to_string(),
11990                            close: true,
11991                            surround: true,
11992                            newline: true,
11993                        },
11994                    ],
11995                    ..Default::default()
11996                },
11997                ..Default::default()
11998            },
11999            Some(tree_sitter_rust::LANGUAGE.into()),
12000        )
12001        .with_indents_query("")
12002        .unwrap(),
12003    );
12004
12005    let text = concat!(
12006        "{   }\n",     //
12007        "  x\n",       //
12008        "  /*   */\n", //
12009        "x\n",         //
12010        "{{} }\n",     //
12011    );
12012
12013    let buffer = cx.new(|cx| Buffer::local(text, cx).with_language(language, cx));
12014    let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
12015    let (editor, cx) = cx.add_window_view(|window, cx| build_editor(buffer, window, cx));
12016    editor
12017        .condition::<crate::EditorEvent>(cx, |editor, cx| !editor.buffer.read(cx).is_parsing(cx))
12018        .await;
12019
12020    editor.update_in(cx, |editor, window, cx| {
12021        editor.change_selections(None, window, cx, |s| {
12022            s.select_display_ranges([
12023                DisplayPoint::new(DisplayRow(0), 2)..DisplayPoint::new(DisplayRow(0), 3),
12024                DisplayPoint::new(DisplayRow(2), 5)..DisplayPoint::new(DisplayRow(2), 5),
12025                DisplayPoint::new(DisplayRow(4), 4)..DisplayPoint::new(DisplayRow(4), 4),
12026            ])
12027        });
12028        editor.newline(&Newline, window, cx);
12029
12030        assert_eq!(
12031            editor.buffer().read(cx).read(cx).text(),
12032            concat!(
12033                "{ \n",    // Suppress rustfmt
12034                "\n",      //
12035                "}\n",     //
12036                "  x\n",   //
12037                "  /* \n", //
12038                "  \n",    //
12039                "  */\n",  //
12040                "x\n",     //
12041                "{{} \n",  //
12042                "}\n",     //
12043            )
12044        );
12045    });
12046}
12047
12048#[gpui::test]
12049fn test_highlighted_ranges(cx: &mut TestAppContext) {
12050    init_test(cx, |_| {});
12051
12052    let editor = cx.add_window(|window, cx| {
12053        let buffer = MultiBuffer::build_simple(&sample_text(16, 8, 'a'), cx);
12054        build_editor(buffer.clone(), window, cx)
12055    });
12056
12057    _ = editor.update(cx, |editor, window, cx| {
12058        struct Type1;
12059        struct Type2;
12060
12061        let buffer = editor.buffer.read(cx).snapshot(cx);
12062
12063        let anchor_range =
12064            |range: Range<Point>| buffer.anchor_after(range.start)..buffer.anchor_after(range.end);
12065
12066        editor.highlight_background::<Type1>(
12067            &[
12068                anchor_range(Point::new(2, 1)..Point::new(2, 3)),
12069                anchor_range(Point::new(4, 2)..Point::new(4, 4)),
12070                anchor_range(Point::new(6, 3)..Point::new(6, 5)),
12071                anchor_range(Point::new(8, 4)..Point::new(8, 6)),
12072            ],
12073            |_| Hsla::red(),
12074            cx,
12075        );
12076        editor.highlight_background::<Type2>(
12077            &[
12078                anchor_range(Point::new(3, 2)..Point::new(3, 5)),
12079                anchor_range(Point::new(5, 3)..Point::new(5, 6)),
12080                anchor_range(Point::new(7, 4)..Point::new(7, 7)),
12081                anchor_range(Point::new(9, 5)..Point::new(9, 8)),
12082            ],
12083            |_| Hsla::green(),
12084            cx,
12085        );
12086
12087        let snapshot = editor.snapshot(window, cx);
12088        let mut highlighted_ranges = editor.background_highlights_in_range(
12089            anchor_range(Point::new(3, 4)..Point::new(7, 4)),
12090            &snapshot,
12091            cx.theme().colors(),
12092        );
12093        // Enforce a consistent ordering based on color without relying on the ordering of the
12094        // highlight's `TypeId` which is non-executor.
12095        highlighted_ranges.sort_unstable_by_key(|(_, color)| *color);
12096        assert_eq!(
12097            highlighted_ranges,
12098            &[
12099                (
12100                    DisplayPoint::new(DisplayRow(4), 2)..DisplayPoint::new(DisplayRow(4), 4),
12101                    Hsla::red(),
12102                ),
12103                (
12104                    DisplayPoint::new(DisplayRow(6), 3)..DisplayPoint::new(DisplayRow(6), 5),
12105                    Hsla::red(),
12106                ),
12107                (
12108                    DisplayPoint::new(DisplayRow(3), 2)..DisplayPoint::new(DisplayRow(3), 5),
12109                    Hsla::green(),
12110                ),
12111                (
12112                    DisplayPoint::new(DisplayRow(5), 3)..DisplayPoint::new(DisplayRow(5), 6),
12113                    Hsla::green(),
12114                ),
12115            ]
12116        );
12117        assert_eq!(
12118            editor.background_highlights_in_range(
12119                anchor_range(Point::new(5, 6)..Point::new(6, 4)),
12120                &snapshot,
12121                cx.theme().colors(),
12122            ),
12123            &[(
12124                DisplayPoint::new(DisplayRow(6), 3)..DisplayPoint::new(DisplayRow(6), 5),
12125                Hsla::red(),
12126            )]
12127        );
12128    });
12129}
12130
12131#[gpui::test]
12132async fn test_following(cx: &mut TestAppContext) {
12133    init_test(cx, |_| {});
12134
12135    let fs = FakeFs::new(cx.executor());
12136    let project = Project::test(fs, ["/file.rs".as_ref()], cx).await;
12137
12138    let buffer = project.update(cx, |project, cx| {
12139        let buffer = project.create_local_buffer(&sample_text(16, 8, 'a'), None, cx);
12140        cx.new(|cx| MultiBuffer::singleton(buffer, cx))
12141    });
12142    let leader = cx.add_window(|window, cx| build_editor(buffer.clone(), window, cx));
12143    let follower = cx.update(|cx| {
12144        cx.open_window(
12145            WindowOptions {
12146                window_bounds: Some(WindowBounds::Windowed(Bounds::from_corners(
12147                    gpui::Point::new(px(0.), px(0.)),
12148                    gpui::Point::new(px(10.), px(80.)),
12149                ))),
12150                ..Default::default()
12151            },
12152            |window, cx| cx.new(|cx| build_editor(buffer.clone(), window, cx)),
12153        )
12154        .unwrap()
12155    });
12156
12157    let is_still_following = Rc::new(RefCell::new(true));
12158    let follower_edit_event_count = Rc::new(RefCell::new(0));
12159    let pending_update = Rc::new(RefCell::new(None));
12160    let leader_entity = leader.root(cx).unwrap();
12161    let follower_entity = follower.root(cx).unwrap();
12162    _ = follower.update(cx, {
12163        let update = pending_update.clone();
12164        let is_still_following = is_still_following.clone();
12165        let follower_edit_event_count = follower_edit_event_count.clone();
12166        |_, window, cx| {
12167            cx.subscribe_in(
12168                &leader_entity,
12169                window,
12170                move |_, leader, event, window, cx| {
12171                    leader.read(cx).add_event_to_update_proto(
12172                        event,
12173                        &mut update.borrow_mut(),
12174                        window,
12175                        cx,
12176                    );
12177                },
12178            )
12179            .detach();
12180
12181            cx.subscribe_in(
12182                &follower_entity,
12183                window,
12184                move |_, _, event: &EditorEvent, _window, _cx| {
12185                    if matches!(Editor::to_follow_event(event), Some(FollowEvent::Unfollow)) {
12186                        *is_still_following.borrow_mut() = false;
12187                    }
12188
12189                    if let EditorEvent::BufferEdited = event {
12190                        *follower_edit_event_count.borrow_mut() += 1;
12191                    }
12192                },
12193            )
12194            .detach();
12195        }
12196    });
12197
12198    // Update the selections only
12199    _ = leader.update(cx, |leader, window, cx| {
12200        leader.change_selections(None, window, cx, |s| s.select_ranges([1..1]));
12201    });
12202    follower
12203        .update(cx, |follower, window, cx| {
12204            follower.apply_update_proto(
12205                &project,
12206                pending_update.borrow_mut().take().unwrap(),
12207                window,
12208                cx,
12209            )
12210        })
12211        .unwrap()
12212        .await
12213        .unwrap();
12214    _ = follower.update(cx, |follower, _, cx| {
12215        assert_eq!(follower.selections.ranges(cx), vec![1..1]);
12216    });
12217    assert!(*is_still_following.borrow());
12218    assert_eq!(*follower_edit_event_count.borrow(), 0);
12219
12220    // Update the scroll position only
12221    _ = leader.update(cx, |leader, window, cx| {
12222        leader.set_scroll_position(gpui::Point::new(1.5, 3.5), window, cx);
12223    });
12224    follower
12225        .update(cx, |follower, window, cx| {
12226            follower.apply_update_proto(
12227                &project,
12228                pending_update.borrow_mut().take().unwrap(),
12229                window,
12230                cx,
12231            )
12232        })
12233        .unwrap()
12234        .await
12235        .unwrap();
12236    assert_eq!(
12237        follower
12238            .update(cx, |follower, _, cx| follower.scroll_position(cx))
12239            .unwrap(),
12240        gpui::Point::new(1.5, 3.5)
12241    );
12242    assert!(*is_still_following.borrow());
12243    assert_eq!(*follower_edit_event_count.borrow(), 0);
12244
12245    // Update the selections and scroll position. The follower's scroll position is updated
12246    // via autoscroll, not via the leader's exact scroll position.
12247    _ = leader.update(cx, |leader, window, cx| {
12248        leader.change_selections(None, window, cx, |s| s.select_ranges([0..0]));
12249        leader.request_autoscroll(Autoscroll::newest(), cx);
12250        leader.set_scroll_position(gpui::Point::new(1.5, 3.5), window, cx);
12251    });
12252    follower
12253        .update(cx, |follower, window, cx| {
12254            follower.apply_update_proto(
12255                &project,
12256                pending_update.borrow_mut().take().unwrap(),
12257                window,
12258                cx,
12259            )
12260        })
12261        .unwrap()
12262        .await
12263        .unwrap();
12264    _ = follower.update(cx, |follower, _, cx| {
12265        assert_eq!(follower.scroll_position(cx), gpui::Point::new(1.5, 0.0));
12266        assert_eq!(follower.selections.ranges(cx), vec![0..0]);
12267    });
12268    assert!(*is_still_following.borrow());
12269
12270    // Creating a pending selection that precedes another selection
12271    _ = leader.update(cx, |leader, window, cx| {
12272        leader.change_selections(None, window, cx, |s| s.select_ranges([1..1]));
12273        leader.begin_selection(DisplayPoint::new(DisplayRow(0), 0), true, 1, window, cx);
12274    });
12275    follower
12276        .update(cx, |follower, window, cx| {
12277            follower.apply_update_proto(
12278                &project,
12279                pending_update.borrow_mut().take().unwrap(),
12280                window,
12281                cx,
12282            )
12283        })
12284        .unwrap()
12285        .await
12286        .unwrap();
12287    _ = follower.update(cx, |follower, _, cx| {
12288        assert_eq!(follower.selections.ranges(cx), vec![0..0, 1..1]);
12289    });
12290    assert!(*is_still_following.borrow());
12291
12292    // Extend the pending selection so that it surrounds another selection
12293    _ = leader.update(cx, |leader, window, cx| {
12294        leader.extend_selection(DisplayPoint::new(DisplayRow(0), 2), 1, window, cx);
12295    });
12296    follower
12297        .update(cx, |follower, window, cx| {
12298            follower.apply_update_proto(
12299                &project,
12300                pending_update.borrow_mut().take().unwrap(),
12301                window,
12302                cx,
12303            )
12304        })
12305        .unwrap()
12306        .await
12307        .unwrap();
12308    _ = follower.update(cx, |follower, _, cx| {
12309        assert_eq!(follower.selections.ranges(cx), vec![0..2]);
12310    });
12311
12312    // Scrolling locally breaks the follow
12313    _ = follower.update(cx, |follower, window, cx| {
12314        let top_anchor = follower.buffer().read(cx).read(cx).anchor_after(0);
12315        follower.set_scroll_anchor(
12316            ScrollAnchor {
12317                anchor: top_anchor,
12318                offset: gpui::Point::new(0.0, 0.5),
12319            },
12320            window,
12321            cx,
12322        );
12323    });
12324    assert!(!(*is_still_following.borrow()));
12325}
12326
12327#[gpui::test]
12328async fn test_following_with_multiple_excerpts(cx: &mut TestAppContext) {
12329    init_test(cx, |_| {});
12330
12331    let fs = FakeFs::new(cx.executor());
12332    let project = Project::test(fs, ["/file.rs".as_ref()], cx).await;
12333    let workspace = cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
12334    let pane = workspace
12335        .update(cx, |workspace, _, _| workspace.active_pane().clone())
12336        .unwrap();
12337
12338    let cx = &mut VisualTestContext::from_window(*workspace.deref(), cx);
12339
12340    let leader = pane.update_in(cx, |_, window, cx| {
12341        let multibuffer = cx.new(|_| MultiBuffer::new(ReadWrite));
12342        cx.new(|cx| build_editor(multibuffer.clone(), window, cx))
12343    });
12344
12345    // Start following the editor when it has no excerpts.
12346    let mut state_message =
12347        leader.update_in(cx, |leader, window, cx| leader.to_state_proto(window, cx));
12348    let workspace_entity = workspace.root(cx).unwrap();
12349    let follower_1 = cx
12350        .update_window(*workspace.deref(), |_, window, cx| {
12351            Editor::from_state_proto(
12352                workspace_entity,
12353                ViewId {
12354                    creator: Default::default(),
12355                    id: 0,
12356                },
12357                &mut state_message,
12358                window,
12359                cx,
12360            )
12361        })
12362        .unwrap()
12363        .unwrap()
12364        .await
12365        .unwrap();
12366
12367    let update_message = Rc::new(RefCell::new(None));
12368    follower_1.update_in(cx, {
12369        let update = update_message.clone();
12370        |_, window, cx| {
12371            cx.subscribe_in(&leader, window, move |_, leader, event, window, cx| {
12372                leader.read(cx).add_event_to_update_proto(
12373                    event,
12374                    &mut update.borrow_mut(),
12375                    window,
12376                    cx,
12377                );
12378            })
12379            .detach();
12380        }
12381    });
12382
12383    let (buffer_1, buffer_2) = project.update(cx, |project, cx| {
12384        (
12385            project.create_local_buffer("abc\ndef\nghi\njkl\n", None, cx),
12386            project.create_local_buffer("mno\npqr\nstu\nvwx\n", None, cx),
12387        )
12388    });
12389
12390    // Insert some excerpts.
12391    leader.update(cx, |leader, cx| {
12392        leader.buffer.update(cx, |multibuffer, cx| {
12393            let excerpt_ids = multibuffer.push_excerpts(
12394                buffer_1.clone(),
12395                [
12396                    ExcerptRange::new(1..6),
12397                    ExcerptRange::new(12..15),
12398                    ExcerptRange::new(0..3),
12399                ],
12400                cx,
12401            );
12402            multibuffer.insert_excerpts_after(
12403                excerpt_ids[0],
12404                buffer_2.clone(),
12405                [ExcerptRange::new(8..12), ExcerptRange::new(0..6)],
12406                cx,
12407            );
12408        });
12409    });
12410
12411    // Apply the update of adding the excerpts.
12412    follower_1
12413        .update_in(cx, |follower, window, cx| {
12414            follower.apply_update_proto(
12415                &project,
12416                update_message.borrow().clone().unwrap(),
12417                window,
12418                cx,
12419            )
12420        })
12421        .await
12422        .unwrap();
12423    assert_eq!(
12424        follower_1.update(cx, |editor, cx| editor.text(cx)),
12425        leader.update(cx, |editor, cx| editor.text(cx))
12426    );
12427    update_message.borrow_mut().take();
12428
12429    // Start following separately after it already has excerpts.
12430    let mut state_message =
12431        leader.update_in(cx, |leader, window, cx| leader.to_state_proto(window, cx));
12432    let workspace_entity = workspace.root(cx).unwrap();
12433    let follower_2 = cx
12434        .update_window(*workspace.deref(), |_, window, cx| {
12435            Editor::from_state_proto(
12436                workspace_entity,
12437                ViewId {
12438                    creator: Default::default(),
12439                    id: 0,
12440                },
12441                &mut state_message,
12442                window,
12443                cx,
12444            )
12445        })
12446        .unwrap()
12447        .unwrap()
12448        .await
12449        .unwrap();
12450    assert_eq!(
12451        follower_2.update(cx, |editor, cx| editor.text(cx)),
12452        leader.update(cx, |editor, cx| editor.text(cx))
12453    );
12454
12455    // Remove some excerpts.
12456    leader.update(cx, |leader, cx| {
12457        leader.buffer.update(cx, |multibuffer, cx| {
12458            let excerpt_ids = multibuffer.excerpt_ids();
12459            multibuffer.remove_excerpts([excerpt_ids[1], excerpt_ids[2]], cx);
12460            multibuffer.remove_excerpts([excerpt_ids[0]], cx);
12461        });
12462    });
12463
12464    // Apply the update of removing the excerpts.
12465    follower_1
12466        .update_in(cx, |follower, window, cx| {
12467            follower.apply_update_proto(
12468                &project,
12469                update_message.borrow().clone().unwrap(),
12470                window,
12471                cx,
12472            )
12473        })
12474        .await
12475        .unwrap();
12476    follower_2
12477        .update_in(cx, |follower, window, cx| {
12478            follower.apply_update_proto(
12479                &project,
12480                update_message.borrow().clone().unwrap(),
12481                window,
12482                cx,
12483            )
12484        })
12485        .await
12486        .unwrap();
12487    update_message.borrow_mut().take();
12488    assert_eq!(
12489        follower_1.update(cx, |editor, cx| editor.text(cx)),
12490        leader.update(cx, |editor, cx| editor.text(cx))
12491    );
12492}
12493
12494#[gpui::test]
12495async fn go_to_prev_overlapping_diagnostic(executor: BackgroundExecutor, cx: &mut TestAppContext) {
12496    init_test(cx, |_| {});
12497
12498    let mut cx = EditorTestContext::new(cx).await;
12499    let lsp_store =
12500        cx.update_editor(|editor, _, cx| editor.project.as_ref().unwrap().read(cx).lsp_store());
12501
12502    cx.set_state(indoc! {"
12503        ˇfn func(abc def: i32) -> u32 {
12504        }
12505    "});
12506
12507    cx.update(|_, cx| {
12508        lsp_store.update(cx, |lsp_store, cx| {
12509            lsp_store
12510                .update_diagnostics(
12511                    LanguageServerId(0),
12512                    lsp::PublishDiagnosticsParams {
12513                        uri: lsp::Url::from_file_path(path!("/root/file")).unwrap(),
12514                        version: None,
12515                        diagnostics: vec![
12516                            lsp::Diagnostic {
12517                                range: lsp::Range::new(
12518                                    lsp::Position::new(0, 11),
12519                                    lsp::Position::new(0, 12),
12520                                ),
12521                                severity: Some(lsp::DiagnosticSeverity::ERROR),
12522                                ..Default::default()
12523                            },
12524                            lsp::Diagnostic {
12525                                range: lsp::Range::new(
12526                                    lsp::Position::new(0, 12),
12527                                    lsp::Position::new(0, 15),
12528                                ),
12529                                severity: Some(lsp::DiagnosticSeverity::ERROR),
12530                                ..Default::default()
12531                            },
12532                            lsp::Diagnostic {
12533                                range: lsp::Range::new(
12534                                    lsp::Position::new(0, 25),
12535                                    lsp::Position::new(0, 28),
12536                                ),
12537                                severity: Some(lsp::DiagnosticSeverity::ERROR),
12538                                ..Default::default()
12539                            },
12540                        ],
12541                    },
12542                    &[],
12543                    cx,
12544                )
12545                .unwrap()
12546        });
12547    });
12548
12549    executor.run_until_parked();
12550
12551    cx.update_editor(|editor, window, cx| {
12552        editor.go_to_prev_diagnostic(&GoToPreviousDiagnostic, window, cx);
12553    });
12554
12555    cx.assert_editor_state(indoc! {"
12556        fn func(abc def: i32) -> ˇu32 {
12557        }
12558    "});
12559
12560    cx.update_editor(|editor, window, cx| {
12561        editor.go_to_prev_diagnostic(&GoToPreviousDiagnostic, window, cx);
12562    });
12563
12564    cx.assert_editor_state(indoc! {"
12565        fn func(abc ˇdef: i32) -> u32 {
12566        }
12567    "});
12568
12569    cx.update_editor(|editor, window, cx| {
12570        editor.go_to_prev_diagnostic(&GoToPreviousDiagnostic, window, cx);
12571    });
12572
12573    cx.assert_editor_state(indoc! {"
12574        fn func(abcˇ def: i32) -> u32 {
12575        }
12576    "});
12577
12578    cx.update_editor(|editor, window, cx| {
12579        editor.go_to_prev_diagnostic(&GoToPreviousDiagnostic, window, cx);
12580    });
12581
12582    cx.assert_editor_state(indoc! {"
12583        fn func(abc def: i32) -> ˇu32 {
12584        }
12585    "});
12586}
12587
12588#[gpui::test]
12589async fn test_diagnostics_with_links(cx: &mut TestAppContext) {
12590    init_test(cx, |_| {});
12591
12592    let mut cx = EditorTestContext::new(cx).await;
12593
12594    cx.set_state(indoc! {"
12595        fn func(abˇc def: i32) -> u32 {
12596        }
12597    "});
12598    let lsp_store =
12599        cx.update_editor(|editor, _, cx| editor.project.as_ref().unwrap().read(cx).lsp_store());
12600
12601    cx.update(|_, cx| {
12602        lsp_store.update(cx, |lsp_store, cx| {
12603            lsp_store.update_diagnostics(
12604                LanguageServerId(0),
12605                lsp::PublishDiagnosticsParams {
12606                    uri: lsp::Url::from_file_path(path!("/root/file")).unwrap(),
12607                    version: None,
12608                    diagnostics: vec![lsp::Diagnostic {
12609                        range: lsp::Range::new(lsp::Position::new(0, 8), lsp::Position::new(0, 12)),
12610                        severity: Some(lsp::DiagnosticSeverity::ERROR),
12611                        message: "we've had problems with <https://link.one>, and <https://link.two> is broken".to_string(),
12612                        ..Default::default()
12613                    }],
12614                },
12615                &[],
12616                cx,
12617            )
12618        })
12619    }).unwrap();
12620    cx.run_until_parked();
12621    cx.update_editor(|editor, window, cx| {
12622        hover_popover::hover(editor, &Default::default(), window, cx)
12623    });
12624    cx.run_until_parked();
12625    cx.update_editor(|editor, _, _| assert!(editor.hover_state.diagnostic_popover.is_some()))
12626}
12627
12628#[gpui::test]
12629async fn test_go_to_hunk(executor: BackgroundExecutor, cx: &mut TestAppContext) {
12630    init_test(cx, |_| {});
12631
12632    let mut cx = EditorTestContext::new(cx).await;
12633
12634    let diff_base = r#"
12635        use some::mod;
12636
12637        const A: u32 = 42;
12638
12639        fn main() {
12640            println!("hello");
12641
12642            println!("world");
12643        }
12644        "#
12645    .unindent();
12646
12647    // Edits are modified, removed, modified, added
12648    cx.set_state(
12649        &r#"
12650        use some::modified;
12651
12652        ˇ
12653        fn main() {
12654            println!("hello there");
12655
12656            println!("around the");
12657            println!("world");
12658        }
12659        "#
12660        .unindent(),
12661    );
12662
12663    cx.set_head_text(&diff_base);
12664    executor.run_until_parked();
12665
12666    cx.update_editor(|editor, window, cx| {
12667        //Wrap around the bottom of the buffer
12668        for _ in 0..3 {
12669            editor.go_to_next_hunk(&GoToHunk, window, cx);
12670        }
12671    });
12672
12673    cx.assert_editor_state(
12674        &r#"
12675        ˇuse some::modified;
12676
12677
12678        fn main() {
12679            println!("hello there");
12680
12681            println!("around the");
12682            println!("world");
12683        }
12684        "#
12685        .unindent(),
12686    );
12687
12688    cx.update_editor(|editor, window, cx| {
12689        //Wrap around the top of the buffer
12690        for _ in 0..2 {
12691            editor.go_to_prev_hunk(&GoToPreviousHunk, window, cx);
12692        }
12693    });
12694
12695    cx.assert_editor_state(
12696        &r#"
12697        use some::modified;
12698
12699
12700        fn main() {
12701        ˇ    println!("hello there");
12702
12703            println!("around the");
12704            println!("world");
12705        }
12706        "#
12707        .unindent(),
12708    );
12709
12710    cx.update_editor(|editor, window, cx| {
12711        editor.go_to_prev_hunk(&GoToPreviousHunk, window, cx);
12712    });
12713
12714    cx.assert_editor_state(
12715        &r#"
12716        use some::modified;
12717
12718        ˇ
12719        fn main() {
12720            println!("hello there");
12721
12722            println!("around the");
12723            println!("world");
12724        }
12725        "#
12726        .unindent(),
12727    );
12728
12729    cx.update_editor(|editor, window, cx| {
12730        editor.go_to_prev_hunk(&GoToPreviousHunk, window, cx);
12731    });
12732
12733    cx.assert_editor_state(
12734        &r#"
12735        ˇuse some::modified;
12736
12737
12738        fn main() {
12739            println!("hello there");
12740
12741            println!("around the");
12742            println!("world");
12743        }
12744        "#
12745        .unindent(),
12746    );
12747
12748    cx.update_editor(|editor, window, cx| {
12749        for _ in 0..2 {
12750            editor.go_to_prev_hunk(&GoToPreviousHunk, window, cx);
12751        }
12752    });
12753
12754    cx.assert_editor_state(
12755        &r#"
12756        use some::modified;
12757
12758
12759        fn main() {
12760        ˇ    println!("hello there");
12761
12762            println!("around the");
12763            println!("world");
12764        }
12765        "#
12766        .unindent(),
12767    );
12768
12769    cx.update_editor(|editor, window, cx| {
12770        editor.fold(&Fold, window, cx);
12771    });
12772
12773    cx.update_editor(|editor, window, cx| {
12774        editor.go_to_next_hunk(&GoToHunk, window, cx);
12775    });
12776
12777    cx.assert_editor_state(
12778        &r#"
12779        ˇuse some::modified;
12780
12781
12782        fn main() {
12783            println!("hello there");
12784
12785            println!("around the");
12786            println!("world");
12787        }
12788        "#
12789        .unindent(),
12790    );
12791}
12792
12793#[test]
12794fn test_split_words() {
12795    fn split(text: &str) -> Vec<&str> {
12796        split_words(text).collect()
12797    }
12798
12799    assert_eq!(split("HelloWorld"), &["Hello", "World"]);
12800    assert_eq!(split("hello_world"), &["hello_", "world"]);
12801    assert_eq!(split("_hello_world_"), &["_", "hello_", "world_"]);
12802    assert_eq!(split("Hello_World"), &["Hello_", "World"]);
12803    assert_eq!(split("helloWOrld"), &["hello", "WOrld"]);
12804    assert_eq!(split("helloworld"), &["helloworld"]);
12805
12806    assert_eq!(split(":do_the_thing"), &[":", "do_", "the_", "thing"]);
12807}
12808
12809#[gpui::test]
12810async fn test_move_to_enclosing_bracket(cx: &mut TestAppContext) {
12811    init_test(cx, |_| {});
12812
12813    let mut cx = EditorLspTestContext::new_typescript(Default::default(), cx).await;
12814    let mut assert = |before, after| {
12815        let _state_context = cx.set_state(before);
12816        cx.run_until_parked();
12817        cx.update_editor(|editor, window, cx| {
12818            editor.move_to_enclosing_bracket(&MoveToEnclosingBracket, window, cx)
12819        });
12820        cx.run_until_parked();
12821        cx.assert_editor_state(after);
12822    };
12823
12824    // Outside bracket jumps to outside of matching bracket
12825    assert("console.logˇ(var);", "console.log(var)ˇ;");
12826    assert("console.log(var)ˇ;", "console.logˇ(var);");
12827
12828    // Inside bracket jumps to inside of matching bracket
12829    assert("console.log(ˇvar);", "console.log(varˇ);");
12830    assert("console.log(varˇ);", "console.log(ˇvar);");
12831
12832    // When outside a bracket and inside, favor jumping to the inside bracket
12833    assert(
12834        "console.log('foo', [1, 2, 3]ˇ);",
12835        "console.log(ˇ'foo', [1, 2, 3]);",
12836    );
12837    assert(
12838        "console.log(ˇ'foo', [1, 2, 3]);",
12839        "console.log('foo', [1, 2, 3]ˇ);",
12840    );
12841
12842    // Bias forward if two options are equally likely
12843    assert(
12844        "let result = curried_fun()ˇ();",
12845        "let result = curried_fun()()ˇ;",
12846    );
12847
12848    // If directly adjacent to a smaller pair but inside a larger (not adjacent), pick the smaller
12849    assert(
12850        indoc! {"
12851            function test() {
12852                console.log('test')ˇ
12853            }"},
12854        indoc! {"
12855            function test() {
12856                console.logˇ('test')
12857            }"},
12858    );
12859}
12860
12861#[gpui::test]
12862async fn test_on_type_formatting_not_triggered(cx: &mut TestAppContext) {
12863    init_test(cx, |_| {});
12864
12865    let fs = FakeFs::new(cx.executor());
12866    fs.insert_tree(
12867        path!("/a"),
12868        json!({
12869            "main.rs": "fn main() { let a = 5; }",
12870            "other.rs": "// Test file",
12871        }),
12872    )
12873    .await;
12874    let project = Project::test(fs, [path!("/a").as_ref()], cx).await;
12875
12876    let language_registry = project.read_with(cx, |project, _| project.languages().clone());
12877    language_registry.add(Arc::new(Language::new(
12878        LanguageConfig {
12879            name: "Rust".into(),
12880            matcher: LanguageMatcher {
12881                path_suffixes: vec!["rs".to_string()],
12882                ..Default::default()
12883            },
12884            brackets: BracketPairConfig {
12885                pairs: vec![BracketPair {
12886                    start: "{".to_string(),
12887                    end: "}".to_string(),
12888                    close: true,
12889                    surround: true,
12890                    newline: true,
12891                }],
12892                disabled_scopes_by_bracket_ix: Vec::new(),
12893            },
12894            ..Default::default()
12895        },
12896        Some(tree_sitter_rust::LANGUAGE.into()),
12897    )));
12898    let mut fake_servers = language_registry.register_fake_lsp(
12899        "Rust",
12900        FakeLspAdapter {
12901            capabilities: lsp::ServerCapabilities {
12902                document_on_type_formatting_provider: Some(lsp::DocumentOnTypeFormattingOptions {
12903                    first_trigger_character: "{".to_string(),
12904                    more_trigger_character: None,
12905                }),
12906                ..Default::default()
12907            },
12908            ..Default::default()
12909        },
12910    );
12911
12912    let workspace = cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
12913
12914    let cx = &mut VisualTestContext::from_window(*workspace, cx);
12915
12916    let worktree_id = workspace
12917        .update(cx, |workspace, _, cx| {
12918            workspace.project().update(cx, |project, cx| {
12919                project.worktrees(cx).next().unwrap().read(cx).id()
12920            })
12921        })
12922        .unwrap();
12923
12924    let buffer = project
12925        .update(cx, |project, cx| {
12926            project.open_local_buffer(path!("/a/main.rs"), cx)
12927        })
12928        .await
12929        .unwrap();
12930    let editor_handle = workspace
12931        .update(cx, |workspace, window, cx| {
12932            workspace.open_path((worktree_id, "main.rs"), None, true, window, cx)
12933        })
12934        .unwrap()
12935        .await
12936        .unwrap()
12937        .downcast::<Editor>()
12938        .unwrap();
12939
12940    cx.executor().start_waiting();
12941    let fake_server = fake_servers.next().await.unwrap();
12942
12943    fake_server.set_request_handler::<lsp::request::OnTypeFormatting, _, _>(
12944        |params, _| async move {
12945            assert_eq!(
12946                params.text_document_position.text_document.uri,
12947                lsp::Url::from_file_path(path!("/a/main.rs")).unwrap(),
12948            );
12949            assert_eq!(
12950                params.text_document_position.position,
12951                lsp::Position::new(0, 21),
12952            );
12953
12954            Ok(Some(vec![lsp::TextEdit {
12955                new_text: "]".to_string(),
12956                range: lsp::Range::new(lsp::Position::new(0, 22), lsp::Position::new(0, 22)),
12957            }]))
12958        },
12959    );
12960
12961    editor_handle.update_in(cx, |editor, window, cx| {
12962        window.focus(&editor.focus_handle(cx));
12963        editor.change_selections(None, window, cx, |s| {
12964            s.select_ranges([Point::new(0, 21)..Point::new(0, 20)])
12965        });
12966        editor.handle_input("{", window, cx);
12967    });
12968
12969    cx.executor().run_until_parked();
12970
12971    buffer.update(cx, |buffer, _| {
12972        assert_eq!(
12973            buffer.text(),
12974            "fn main() { let a = {5}; }",
12975            "No extra braces from on type formatting should appear in the buffer"
12976        )
12977    });
12978}
12979
12980#[gpui::test]
12981async fn test_language_server_restart_due_to_settings_change(cx: &mut TestAppContext) {
12982    init_test(cx, |_| {});
12983
12984    let fs = FakeFs::new(cx.executor());
12985    fs.insert_tree(
12986        path!("/a"),
12987        json!({
12988            "main.rs": "fn main() { let a = 5; }",
12989            "other.rs": "// Test file",
12990        }),
12991    )
12992    .await;
12993
12994    let project = Project::test(fs, [path!("/a").as_ref()], cx).await;
12995
12996    let server_restarts = Arc::new(AtomicUsize::new(0));
12997    let closure_restarts = Arc::clone(&server_restarts);
12998    let language_server_name = "test language server";
12999    let language_name: LanguageName = "Rust".into();
13000
13001    let language_registry = project.read_with(cx, |project, _| project.languages().clone());
13002    language_registry.add(Arc::new(Language::new(
13003        LanguageConfig {
13004            name: language_name.clone(),
13005            matcher: LanguageMatcher {
13006                path_suffixes: vec!["rs".to_string()],
13007                ..Default::default()
13008            },
13009            ..Default::default()
13010        },
13011        Some(tree_sitter_rust::LANGUAGE.into()),
13012    )));
13013    let mut fake_servers = language_registry.register_fake_lsp(
13014        "Rust",
13015        FakeLspAdapter {
13016            name: language_server_name,
13017            initialization_options: Some(json!({
13018                "testOptionValue": true
13019            })),
13020            initializer: Some(Box::new(move |fake_server| {
13021                let task_restarts = Arc::clone(&closure_restarts);
13022                fake_server.set_request_handler::<lsp::request::Shutdown, _, _>(move |_, _| {
13023                    task_restarts.fetch_add(1, atomic::Ordering::Release);
13024                    futures::future::ready(Ok(()))
13025                });
13026            })),
13027            ..Default::default()
13028        },
13029    );
13030
13031    let _window = cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
13032    let _buffer = project
13033        .update(cx, |project, cx| {
13034            project.open_local_buffer_with_lsp(path!("/a/main.rs"), cx)
13035        })
13036        .await
13037        .unwrap();
13038    let _fake_server = fake_servers.next().await.unwrap();
13039    update_test_language_settings(cx, |language_settings| {
13040        language_settings.languages.insert(
13041            language_name.clone(),
13042            LanguageSettingsContent {
13043                tab_size: NonZeroU32::new(8),
13044                ..Default::default()
13045            },
13046        );
13047    });
13048    cx.executor().run_until_parked();
13049    assert_eq!(
13050        server_restarts.load(atomic::Ordering::Acquire),
13051        0,
13052        "Should not restart LSP server on an unrelated change"
13053    );
13054
13055    update_test_project_settings(cx, |project_settings| {
13056        project_settings.lsp.insert(
13057            "Some other server name".into(),
13058            LspSettings {
13059                binary: None,
13060                settings: None,
13061                initialization_options: Some(json!({
13062                    "some other init value": false
13063                })),
13064                enable_lsp_tasks: false,
13065            },
13066        );
13067    });
13068    cx.executor().run_until_parked();
13069    assert_eq!(
13070        server_restarts.load(atomic::Ordering::Acquire),
13071        0,
13072        "Should not restart LSP server on an unrelated LSP settings change"
13073    );
13074
13075    update_test_project_settings(cx, |project_settings| {
13076        project_settings.lsp.insert(
13077            language_server_name.into(),
13078            LspSettings {
13079                binary: None,
13080                settings: None,
13081                initialization_options: Some(json!({
13082                    "anotherInitValue": false
13083                })),
13084                enable_lsp_tasks: false,
13085            },
13086        );
13087    });
13088    cx.executor().run_until_parked();
13089    assert_eq!(
13090        server_restarts.load(atomic::Ordering::Acquire),
13091        1,
13092        "Should restart LSP server on a related LSP settings change"
13093    );
13094
13095    update_test_project_settings(cx, |project_settings| {
13096        project_settings.lsp.insert(
13097            language_server_name.into(),
13098            LspSettings {
13099                binary: None,
13100                settings: None,
13101                initialization_options: Some(json!({
13102                    "anotherInitValue": false
13103                })),
13104                enable_lsp_tasks: false,
13105            },
13106        );
13107    });
13108    cx.executor().run_until_parked();
13109    assert_eq!(
13110        server_restarts.load(atomic::Ordering::Acquire),
13111        1,
13112        "Should not restart LSP server on a related LSP settings change that is the same"
13113    );
13114
13115    update_test_project_settings(cx, |project_settings| {
13116        project_settings.lsp.insert(
13117            language_server_name.into(),
13118            LspSettings {
13119                binary: None,
13120                settings: None,
13121                initialization_options: None,
13122                enable_lsp_tasks: false,
13123            },
13124        );
13125    });
13126    cx.executor().run_until_parked();
13127    assert_eq!(
13128        server_restarts.load(atomic::Ordering::Acquire),
13129        2,
13130        "Should restart LSP server on another related LSP settings change"
13131    );
13132}
13133
13134#[gpui::test]
13135async fn test_completions_with_additional_edits(cx: &mut TestAppContext) {
13136    init_test(cx, |_| {});
13137
13138    let mut cx = EditorLspTestContext::new_rust(
13139        lsp::ServerCapabilities {
13140            completion_provider: Some(lsp::CompletionOptions {
13141                trigger_characters: Some(vec![".".to_string()]),
13142                resolve_provider: Some(true),
13143                ..Default::default()
13144            }),
13145            ..Default::default()
13146        },
13147        cx,
13148    )
13149    .await;
13150
13151    cx.set_state("fn main() { let a = 2ˇ; }");
13152    cx.simulate_keystroke(".");
13153    let completion_item = lsp::CompletionItem {
13154        label: "some".into(),
13155        kind: Some(lsp::CompletionItemKind::SNIPPET),
13156        detail: Some("Wrap the expression in an `Option::Some`".to_string()),
13157        documentation: Some(lsp::Documentation::MarkupContent(lsp::MarkupContent {
13158            kind: lsp::MarkupKind::Markdown,
13159            value: "```rust\nSome(2)\n```".to_string(),
13160        })),
13161        deprecated: Some(false),
13162        sort_text: Some("fffffff2".to_string()),
13163        filter_text: Some("some".to_string()),
13164        insert_text_format: Some(lsp::InsertTextFormat::SNIPPET),
13165        text_edit: Some(lsp::CompletionTextEdit::Edit(lsp::TextEdit {
13166            range: lsp::Range {
13167                start: lsp::Position {
13168                    line: 0,
13169                    character: 22,
13170                },
13171                end: lsp::Position {
13172                    line: 0,
13173                    character: 22,
13174                },
13175            },
13176            new_text: "Some(2)".to_string(),
13177        })),
13178        additional_text_edits: Some(vec![lsp::TextEdit {
13179            range: lsp::Range {
13180                start: lsp::Position {
13181                    line: 0,
13182                    character: 20,
13183                },
13184                end: lsp::Position {
13185                    line: 0,
13186                    character: 22,
13187                },
13188            },
13189            new_text: "".to_string(),
13190        }]),
13191        ..Default::default()
13192    };
13193
13194    let closure_completion_item = completion_item.clone();
13195    let mut request = cx.set_request_handler::<lsp::request::Completion, _, _>(move |_, _, _| {
13196        let task_completion_item = closure_completion_item.clone();
13197        async move {
13198            Ok(Some(lsp::CompletionResponse::Array(vec![
13199                task_completion_item,
13200            ])))
13201        }
13202    });
13203
13204    request.next().await;
13205
13206    cx.condition(|editor, _| editor.context_menu_visible())
13207        .await;
13208    let apply_additional_edits = cx.update_editor(|editor, window, cx| {
13209        editor
13210            .confirm_completion(&ConfirmCompletion::default(), window, cx)
13211            .unwrap()
13212    });
13213    cx.assert_editor_state("fn main() { let a = 2.Some(2)ˇ; }");
13214
13215    cx.set_request_handler::<lsp::request::ResolveCompletionItem, _, _>(move |_, _, _| {
13216        let task_completion_item = completion_item.clone();
13217        async move { Ok(task_completion_item) }
13218    })
13219    .next()
13220    .await
13221    .unwrap();
13222    apply_additional_edits.await.unwrap();
13223    cx.assert_editor_state("fn main() { let a = Some(2)ˇ; }");
13224}
13225
13226#[gpui::test]
13227async fn test_completions_resolve_updates_labels_if_filter_text_matches(cx: &mut TestAppContext) {
13228    init_test(cx, |_| {});
13229
13230    let mut cx = EditorLspTestContext::new_rust(
13231        lsp::ServerCapabilities {
13232            completion_provider: Some(lsp::CompletionOptions {
13233                trigger_characters: Some(vec![".".to_string()]),
13234                resolve_provider: Some(true),
13235                ..Default::default()
13236            }),
13237            ..Default::default()
13238        },
13239        cx,
13240    )
13241    .await;
13242
13243    cx.set_state("fn main() { let a = 2ˇ; }");
13244    cx.simulate_keystroke(".");
13245
13246    let item1 = lsp::CompletionItem {
13247        label: "method id()".to_string(),
13248        filter_text: Some("id".to_string()),
13249        detail: None,
13250        documentation: None,
13251        text_edit: Some(lsp::CompletionTextEdit::Edit(lsp::TextEdit {
13252            range: lsp::Range::new(lsp::Position::new(0, 22), lsp::Position::new(0, 22)),
13253            new_text: ".id".to_string(),
13254        })),
13255        ..lsp::CompletionItem::default()
13256    };
13257
13258    let item2 = lsp::CompletionItem {
13259        label: "other".to_string(),
13260        filter_text: Some("other".to_string()),
13261        detail: None,
13262        documentation: None,
13263        text_edit: Some(lsp::CompletionTextEdit::Edit(lsp::TextEdit {
13264            range: lsp::Range::new(lsp::Position::new(0, 22), lsp::Position::new(0, 22)),
13265            new_text: ".other".to_string(),
13266        })),
13267        ..lsp::CompletionItem::default()
13268    };
13269
13270    let item1 = item1.clone();
13271    cx.set_request_handler::<lsp::request::Completion, _, _>({
13272        let item1 = item1.clone();
13273        move |_, _, _| {
13274            let item1 = item1.clone();
13275            let item2 = item2.clone();
13276            async move { Ok(Some(lsp::CompletionResponse::Array(vec![item1, item2]))) }
13277        }
13278    })
13279    .next()
13280    .await;
13281
13282    cx.condition(|editor, _| editor.context_menu_visible())
13283        .await;
13284    cx.update_editor(|editor, _, _| {
13285        let context_menu = editor.context_menu.borrow_mut();
13286        let context_menu = context_menu
13287            .as_ref()
13288            .expect("Should have the context menu deployed");
13289        match context_menu {
13290            CodeContextMenu::Completions(completions_menu) => {
13291                let completions = completions_menu.completions.borrow_mut();
13292                assert_eq!(
13293                    completions
13294                        .iter()
13295                        .map(|completion| &completion.label.text)
13296                        .collect::<Vec<_>>(),
13297                    vec!["method id()", "other"]
13298                )
13299            }
13300            CodeContextMenu::CodeActions(_) => panic!("Should show the completions menu"),
13301        }
13302    });
13303
13304    cx.set_request_handler::<lsp::request::ResolveCompletionItem, _, _>({
13305        let item1 = item1.clone();
13306        move |_, item_to_resolve, _| {
13307            let item1 = item1.clone();
13308            async move {
13309                if item1 == item_to_resolve {
13310                    Ok(lsp::CompletionItem {
13311                        label: "method id()".to_string(),
13312                        filter_text: Some("id".to_string()),
13313                        detail: Some("Now resolved!".to_string()),
13314                        documentation: Some(lsp::Documentation::String("Docs".to_string())),
13315                        text_edit: Some(lsp::CompletionTextEdit::Edit(lsp::TextEdit {
13316                            range: lsp::Range::new(
13317                                lsp::Position::new(0, 22),
13318                                lsp::Position::new(0, 22),
13319                            ),
13320                            new_text: ".id".to_string(),
13321                        })),
13322                        ..lsp::CompletionItem::default()
13323                    })
13324                } else {
13325                    Ok(item_to_resolve)
13326                }
13327            }
13328        }
13329    })
13330    .next()
13331    .await
13332    .unwrap();
13333    cx.run_until_parked();
13334
13335    cx.update_editor(|editor, window, cx| {
13336        editor.context_menu_next(&Default::default(), window, cx);
13337    });
13338
13339    cx.update_editor(|editor, _, _| {
13340        let context_menu = editor.context_menu.borrow_mut();
13341        let context_menu = context_menu
13342            .as_ref()
13343            .expect("Should have the context menu deployed");
13344        match context_menu {
13345            CodeContextMenu::Completions(completions_menu) => {
13346                let completions = completions_menu.completions.borrow_mut();
13347                assert_eq!(
13348                    completions
13349                        .iter()
13350                        .map(|completion| &completion.label.text)
13351                        .collect::<Vec<_>>(),
13352                    vec!["method id() Now resolved!", "other"],
13353                    "Should update first completion label, but not second as the filter text did not match."
13354                );
13355            }
13356            CodeContextMenu::CodeActions(_) => panic!("Should show the completions menu"),
13357        }
13358    });
13359}
13360
13361#[gpui::test]
13362async fn test_completions_resolve_happens_once(cx: &mut TestAppContext) {
13363    init_test(cx, |_| {});
13364
13365    let mut cx = EditorLspTestContext::new_rust(
13366        lsp::ServerCapabilities {
13367            completion_provider: Some(lsp::CompletionOptions {
13368                trigger_characters: Some(vec![".".to_string()]),
13369                resolve_provider: Some(true),
13370                ..Default::default()
13371            }),
13372            ..Default::default()
13373        },
13374        cx,
13375    )
13376    .await;
13377
13378    cx.set_state("fn main() { let a = 2ˇ; }");
13379    cx.simulate_keystroke(".");
13380
13381    let unresolved_item_1 = lsp::CompletionItem {
13382        label: "id".to_string(),
13383        filter_text: Some("id".to_string()),
13384        detail: None,
13385        documentation: None,
13386        text_edit: Some(lsp::CompletionTextEdit::Edit(lsp::TextEdit {
13387            range: lsp::Range::new(lsp::Position::new(0, 22), lsp::Position::new(0, 22)),
13388            new_text: ".id".to_string(),
13389        })),
13390        ..lsp::CompletionItem::default()
13391    };
13392    let resolved_item_1 = lsp::CompletionItem {
13393        additional_text_edits: Some(vec![lsp::TextEdit {
13394            range: lsp::Range::new(lsp::Position::new(0, 20), lsp::Position::new(0, 22)),
13395            new_text: "!!".to_string(),
13396        }]),
13397        ..unresolved_item_1.clone()
13398    };
13399    let unresolved_item_2 = lsp::CompletionItem {
13400        label: "other".to_string(),
13401        filter_text: Some("other".to_string()),
13402        detail: None,
13403        documentation: None,
13404        text_edit: Some(lsp::CompletionTextEdit::Edit(lsp::TextEdit {
13405            range: lsp::Range::new(lsp::Position::new(0, 22), lsp::Position::new(0, 22)),
13406            new_text: ".other".to_string(),
13407        })),
13408        ..lsp::CompletionItem::default()
13409    };
13410    let resolved_item_2 = lsp::CompletionItem {
13411        additional_text_edits: Some(vec![lsp::TextEdit {
13412            range: lsp::Range::new(lsp::Position::new(0, 20), lsp::Position::new(0, 22)),
13413            new_text: "??".to_string(),
13414        }]),
13415        ..unresolved_item_2.clone()
13416    };
13417
13418    let resolve_requests_1 = Arc::new(AtomicUsize::new(0));
13419    let resolve_requests_2 = Arc::new(AtomicUsize::new(0));
13420    cx.lsp
13421        .server
13422        .on_request::<lsp::request::ResolveCompletionItem, _, _>({
13423            let unresolved_item_1 = unresolved_item_1.clone();
13424            let resolved_item_1 = resolved_item_1.clone();
13425            let unresolved_item_2 = unresolved_item_2.clone();
13426            let resolved_item_2 = resolved_item_2.clone();
13427            let resolve_requests_1 = resolve_requests_1.clone();
13428            let resolve_requests_2 = resolve_requests_2.clone();
13429            move |unresolved_request, _| {
13430                let unresolved_item_1 = unresolved_item_1.clone();
13431                let resolved_item_1 = resolved_item_1.clone();
13432                let unresolved_item_2 = unresolved_item_2.clone();
13433                let resolved_item_2 = resolved_item_2.clone();
13434                let resolve_requests_1 = resolve_requests_1.clone();
13435                let resolve_requests_2 = resolve_requests_2.clone();
13436                async move {
13437                    if unresolved_request == unresolved_item_1 {
13438                        resolve_requests_1.fetch_add(1, atomic::Ordering::Release);
13439                        Ok(resolved_item_1.clone())
13440                    } else if unresolved_request == unresolved_item_2 {
13441                        resolve_requests_2.fetch_add(1, atomic::Ordering::Release);
13442                        Ok(resolved_item_2.clone())
13443                    } else {
13444                        panic!("Unexpected completion item {unresolved_request:?}")
13445                    }
13446                }
13447            }
13448        })
13449        .detach();
13450
13451    cx.set_request_handler::<lsp::request::Completion, _, _>(move |_, _, _| {
13452        let unresolved_item_1 = unresolved_item_1.clone();
13453        let unresolved_item_2 = unresolved_item_2.clone();
13454        async move {
13455            Ok(Some(lsp::CompletionResponse::Array(vec![
13456                unresolved_item_1,
13457                unresolved_item_2,
13458            ])))
13459        }
13460    })
13461    .next()
13462    .await;
13463
13464    cx.condition(|editor, _| editor.context_menu_visible())
13465        .await;
13466    cx.update_editor(|editor, _, _| {
13467        let context_menu = editor.context_menu.borrow_mut();
13468        let context_menu = context_menu
13469            .as_ref()
13470            .expect("Should have the context menu deployed");
13471        match context_menu {
13472            CodeContextMenu::Completions(completions_menu) => {
13473                let completions = completions_menu.completions.borrow_mut();
13474                assert_eq!(
13475                    completions
13476                        .iter()
13477                        .map(|completion| &completion.label.text)
13478                        .collect::<Vec<_>>(),
13479                    vec!["id", "other"]
13480                )
13481            }
13482            CodeContextMenu::CodeActions(_) => panic!("Should show the completions menu"),
13483        }
13484    });
13485    cx.run_until_parked();
13486
13487    cx.update_editor(|editor, window, cx| {
13488        editor.context_menu_next(&ContextMenuNext, window, cx);
13489    });
13490    cx.run_until_parked();
13491    cx.update_editor(|editor, window, cx| {
13492        editor.context_menu_prev(&ContextMenuPrevious, window, cx);
13493    });
13494    cx.run_until_parked();
13495    cx.update_editor(|editor, window, cx| {
13496        editor.context_menu_next(&ContextMenuNext, window, cx);
13497    });
13498    cx.run_until_parked();
13499    cx.update_editor(|editor, window, cx| {
13500        editor
13501            .compose_completion(&ComposeCompletion::default(), window, cx)
13502            .expect("No task returned")
13503    })
13504    .await
13505    .expect("Completion failed");
13506    cx.run_until_parked();
13507
13508    cx.update_editor(|editor, _, cx| {
13509        assert_eq!(
13510            resolve_requests_1.load(atomic::Ordering::Acquire),
13511            1,
13512            "Should always resolve once despite multiple selections"
13513        );
13514        assert_eq!(
13515            resolve_requests_2.load(atomic::Ordering::Acquire),
13516            1,
13517            "Should always resolve once after multiple selections and applying the completion"
13518        );
13519        assert_eq!(
13520            editor.text(cx),
13521            "fn main() { let a = ??.other; }",
13522            "Should use resolved data when applying the completion"
13523        );
13524    });
13525}
13526
13527#[gpui::test]
13528async fn test_completions_default_resolve_data_handling(cx: &mut TestAppContext) {
13529    init_test(cx, |_| {});
13530
13531    let item_0 = lsp::CompletionItem {
13532        label: "abs".into(),
13533        insert_text: Some("abs".into()),
13534        data: Some(json!({ "very": "special"})),
13535        insert_text_mode: Some(lsp::InsertTextMode::ADJUST_INDENTATION),
13536        text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13537            lsp::InsertReplaceEdit {
13538                new_text: "abs".to_string(),
13539                insert: lsp::Range::default(),
13540                replace: lsp::Range::default(),
13541            },
13542        )),
13543        ..lsp::CompletionItem::default()
13544    };
13545    let items = iter::once(item_0.clone())
13546        .chain((11..51).map(|i| lsp::CompletionItem {
13547            label: format!("item_{}", i),
13548            insert_text: Some(format!("item_{}", i)),
13549            insert_text_format: Some(lsp::InsertTextFormat::PLAIN_TEXT),
13550            ..lsp::CompletionItem::default()
13551        }))
13552        .collect::<Vec<_>>();
13553
13554    let default_commit_characters = vec!["?".to_string()];
13555    let default_data = json!({ "default": "data"});
13556    let default_insert_text_format = lsp::InsertTextFormat::SNIPPET;
13557    let default_insert_text_mode = lsp::InsertTextMode::AS_IS;
13558    let default_edit_range = lsp::Range {
13559        start: lsp::Position {
13560            line: 0,
13561            character: 5,
13562        },
13563        end: lsp::Position {
13564            line: 0,
13565            character: 5,
13566        },
13567    };
13568
13569    let mut cx = EditorLspTestContext::new_rust(
13570        lsp::ServerCapabilities {
13571            completion_provider: Some(lsp::CompletionOptions {
13572                trigger_characters: Some(vec![".".to_string()]),
13573                resolve_provider: Some(true),
13574                ..Default::default()
13575            }),
13576            ..Default::default()
13577        },
13578        cx,
13579    )
13580    .await;
13581
13582    cx.set_state("fn main() { let a = 2ˇ; }");
13583    cx.simulate_keystroke(".");
13584
13585    let completion_data = default_data.clone();
13586    let completion_characters = default_commit_characters.clone();
13587    let completion_items = items.clone();
13588    cx.set_request_handler::<lsp::request::Completion, _, _>(move |_, _, _| {
13589        let default_data = completion_data.clone();
13590        let default_commit_characters = completion_characters.clone();
13591        let items = completion_items.clone();
13592        async move {
13593            Ok(Some(lsp::CompletionResponse::List(lsp::CompletionList {
13594                items,
13595                item_defaults: Some(lsp::CompletionListItemDefaults {
13596                    data: Some(default_data.clone()),
13597                    commit_characters: Some(default_commit_characters.clone()),
13598                    edit_range: Some(lsp::CompletionListItemDefaultsEditRange::Range(
13599                        default_edit_range,
13600                    )),
13601                    insert_text_format: Some(default_insert_text_format),
13602                    insert_text_mode: Some(default_insert_text_mode),
13603                }),
13604                ..lsp::CompletionList::default()
13605            })))
13606        }
13607    })
13608    .next()
13609    .await;
13610
13611    let resolved_items = Arc::new(Mutex::new(Vec::new()));
13612    cx.lsp
13613        .server
13614        .on_request::<lsp::request::ResolveCompletionItem, _, _>({
13615            let closure_resolved_items = resolved_items.clone();
13616            move |item_to_resolve, _| {
13617                let closure_resolved_items = closure_resolved_items.clone();
13618                async move {
13619                    closure_resolved_items.lock().push(item_to_resolve.clone());
13620                    Ok(item_to_resolve)
13621                }
13622            }
13623        })
13624        .detach();
13625
13626    cx.condition(|editor, _| editor.context_menu_visible())
13627        .await;
13628    cx.run_until_parked();
13629    cx.update_editor(|editor, _, _| {
13630        let menu = editor.context_menu.borrow_mut();
13631        match menu.as_ref().expect("should have the completions menu") {
13632            CodeContextMenu::Completions(completions_menu) => {
13633                assert_eq!(
13634                    completions_menu
13635                        .entries
13636                        .borrow()
13637                        .iter()
13638                        .map(|mat| mat.string.clone())
13639                        .collect::<Vec<String>>(),
13640                    items
13641                        .iter()
13642                        .map(|completion| completion.label.clone())
13643                        .collect::<Vec<String>>()
13644                );
13645            }
13646            CodeContextMenu::CodeActions(_) => panic!("Expected to have the completions menu"),
13647        }
13648    });
13649    // Approximate initial displayed interval is 0..12. With extra item padding of 4 this is 0..16
13650    // with 4 from the end.
13651    assert_eq!(
13652        *resolved_items.lock(),
13653        [&items[0..16], &items[items.len() - 4..items.len()]]
13654            .concat()
13655            .iter()
13656            .cloned()
13657            .map(|mut item| {
13658                if item.data.is_none() {
13659                    item.data = Some(default_data.clone());
13660                }
13661                item
13662            })
13663            .collect::<Vec<lsp::CompletionItem>>(),
13664        "Items sent for resolve should be unchanged modulo resolve `data` filled with default if missing"
13665    );
13666    resolved_items.lock().clear();
13667
13668    cx.update_editor(|editor, window, cx| {
13669        editor.context_menu_prev(&ContextMenuPrevious, window, cx);
13670    });
13671    cx.run_until_parked();
13672    // Completions that have already been resolved are skipped.
13673    assert_eq!(
13674        *resolved_items.lock(),
13675        items[items.len() - 16..items.len() - 4]
13676            .iter()
13677            .cloned()
13678            .map(|mut item| {
13679                if item.data.is_none() {
13680                    item.data = Some(default_data.clone());
13681                }
13682                item
13683            })
13684            .collect::<Vec<lsp::CompletionItem>>()
13685    );
13686    resolved_items.lock().clear();
13687}
13688
13689#[gpui::test]
13690async fn test_completions_in_languages_with_extra_word_characters(cx: &mut TestAppContext) {
13691    init_test(cx, |_| {});
13692
13693    let mut cx = EditorLspTestContext::new(
13694        Language::new(
13695            LanguageConfig {
13696                matcher: LanguageMatcher {
13697                    path_suffixes: vec!["jsx".into()],
13698                    ..Default::default()
13699                },
13700                overrides: [(
13701                    "element".into(),
13702                    LanguageConfigOverride {
13703                        completion_query_characters: Override::Set(['-'].into_iter().collect()),
13704                        ..Default::default()
13705                    },
13706                )]
13707                .into_iter()
13708                .collect(),
13709                ..Default::default()
13710            },
13711            Some(tree_sitter_typescript::LANGUAGE_TSX.into()),
13712        )
13713        .with_override_query("(jsx_self_closing_element) @element")
13714        .unwrap(),
13715        lsp::ServerCapabilities {
13716            completion_provider: Some(lsp::CompletionOptions {
13717                trigger_characters: Some(vec![":".to_string()]),
13718                ..Default::default()
13719            }),
13720            ..Default::default()
13721        },
13722        cx,
13723    )
13724    .await;
13725
13726    cx.lsp
13727        .set_request_handler::<lsp::request::Completion, _, _>(move |_, _| async move {
13728            Ok(Some(lsp::CompletionResponse::Array(vec![
13729                lsp::CompletionItem {
13730                    label: "bg-blue".into(),
13731                    ..Default::default()
13732                },
13733                lsp::CompletionItem {
13734                    label: "bg-red".into(),
13735                    ..Default::default()
13736                },
13737                lsp::CompletionItem {
13738                    label: "bg-yellow".into(),
13739                    ..Default::default()
13740                },
13741            ])))
13742        });
13743
13744    cx.set_state(r#"<p class="bgˇ" />"#);
13745
13746    // Trigger completion when typing a dash, because the dash is an extra
13747    // word character in the 'element' scope, which contains the cursor.
13748    cx.simulate_keystroke("-");
13749    cx.executor().run_until_parked();
13750    cx.update_editor(|editor, _, _| {
13751        if let Some(CodeContextMenu::Completions(menu)) = editor.context_menu.borrow_mut().as_ref()
13752        {
13753            assert_eq!(
13754                completion_menu_entries(&menu),
13755                &["bg-red", "bg-blue", "bg-yellow"]
13756            );
13757        } else {
13758            panic!("expected completion menu to be open");
13759        }
13760    });
13761
13762    cx.simulate_keystroke("l");
13763    cx.executor().run_until_parked();
13764    cx.update_editor(|editor, _, _| {
13765        if let Some(CodeContextMenu::Completions(menu)) = editor.context_menu.borrow_mut().as_ref()
13766        {
13767            assert_eq!(completion_menu_entries(&menu), &["bg-blue", "bg-yellow"]);
13768        } else {
13769            panic!("expected completion menu to be open");
13770        }
13771    });
13772
13773    // When filtering completions, consider the character after the '-' to
13774    // be the start of a subword.
13775    cx.set_state(r#"<p class="yelˇ" />"#);
13776    cx.simulate_keystroke("l");
13777    cx.executor().run_until_parked();
13778    cx.update_editor(|editor, _, _| {
13779        if let Some(CodeContextMenu::Completions(menu)) = editor.context_menu.borrow_mut().as_ref()
13780        {
13781            assert_eq!(completion_menu_entries(&menu), &["bg-yellow"]);
13782        } else {
13783            panic!("expected completion menu to be open");
13784        }
13785    });
13786}
13787
13788fn completion_menu_entries(menu: &CompletionsMenu) -> Vec<String> {
13789    let entries = menu.entries.borrow();
13790    entries.iter().map(|mat| mat.string.clone()).collect()
13791}
13792
13793#[gpui::test]
13794async fn test_document_format_with_prettier(cx: &mut TestAppContext) {
13795    init_test(cx, |settings| {
13796        settings.defaults.formatter = Some(language_settings::SelectedFormatter::List(
13797            FormatterList(vec![Formatter::Prettier].into()),
13798        ))
13799    });
13800
13801    let fs = FakeFs::new(cx.executor());
13802    fs.insert_file(path!("/file.ts"), Default::default()).await;
13803
13804    let project = Project::test(fs, [path!("/file.ts").as_ref()], cx).await;
13805    let language_registry = project.read_with(cx, |project, _| project.languages().clone());
13806
13807    language_registry.add(Arc::new(Language::new(
13808        LanguageConfig {
13809            name: "TypeScript".into(),
13810            matcher: LanguageMatcher {
13811                path_suffixes: vec!["ts".to_string()],
13812                ..Default::default()
13813            },
13814            ..Default::default()
13815        },
13816        Some(tree_sitter_typescript::LANGUAGE_TYPESCRIPT.into()),
13817    )));
13818    update_test_language_settings(cx, |settings| {
13819        settings.defaults.prettier = Some(PrettierSettings {
13820            allowed: true,
13821            ..PrettierSettings::default()
13822        });
13823    });
13824
13825    let test_plugin = "test_plugin";
13826    let _ = language_registry.register_fake_lsp(
13827        "TypeScript",
13828        FakeLspAdapter {
13829            prettier_plugins: vec![test_plugin],
13830            ..Default::default()
13831        },
13832    );
13833
13834    let prettier_format_suffix = project::TEST_PRETTIER_FORMAT_SUFFIX;
13835    let buffer = project
13836        .update(cx, |project, cx| {
13837            project.open_local_buffer(path!("/file.ts"), cx)
13838        })
13839        .await
13840        .unwrap();
13841
13842    let buffer_text = "one\ntwo\nthree\n";
13843    let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
13844    let (editor, cx) = cx.add_window_view(|window, cx| build_editor(buffer, window, cx));
13845    editor.update_in(cx, |editor, window, cx| {
13846        editor.set_text(buffer_text, window, cx)
13847    });
13848
13849    editor
13850        .update_in(cx, |editor, window, cx| {
13851            editor.perform_format(
13852                project.clone(),
13853                FormatTrigger::Manual,
13854                FormatTarget::Buffers,
13855                window,
13856                cx,
13857            )
13858        })
13859        .unwrap()
13860        .await;
13861    assert_eq!(
13862        editor.update(cx, |editor, cx| editor.text(cx)),
13863        buffer_text.to_string() + prettier_format_suffix,
13864        "Test prettier formatting was not applied to the original buffer text",
13865    );
13866
13867    update_test_language_settings(cx, |settings| {
13868        settings.defaults.formatter = Some(language_settings::SelectedFormatter::Auto)
13869    });
13870    let format = editor.update_in(cx, |editor, window, cx| {
13871        editor.perform_format(
13872            project.clone(),
13873            FormatTrigger::Manual,
13874            FormatTarget::Buffers,
13875            window,
13876            cx,
13877        )
13878    });
13879    format.await.unwrap();
13880    assert_eq!(
13881        editor.update(cx, |editor, cx| editor.text(cx)),
13882        buffer_text.to_string() + prettier_format_suffix + "\n" + prettier_format_suffix,
13883        "Autoformatting (via test prettier) was not applied to the original buffer text",
13884    );
13885}
13886
13887#[gpui::test]
13888async fn test_addition_reverts(cx: &mut TestAppContext) {
13889    init_test(cx, |_| {});
13890    let mut cx = EditorLspTestContext::new_rust(lsp::ServerCapabilities::default(), cx).await;
13891    let base_text = indoc! {r#"
13892        struct Row;
13893        struct Row1;
13894        struct Row2;
13895
13896        struct Row4;
13897        struct Row5;
13898        struct Row6;
13899
13900        struct Row8;
13901        struct Row9;
13902        struct Row10;"#};
13903
13904    // When addition hunks are not adjacent to carets, no hunk revert is performed
13905    assert_hunk_revert(
13906        indoc! {r#"struct Row;
13907                   struct Row1;
13908                   struct Row1.1;
13909                   struct Row1.2;
13910                   struct Row2;ˇ
13911
13912                   struct Row4;
13913                   struct Row5;
13914                   struct Row6;
13915
13916                   struct Row8;
13917                   ˇstruct Row9;
13918                   struct Row9.1;
13919                   struct Row9.2;
13920                   struct Row9.3;
13921                   struct Row10;"#},
13922        vec![DiffHunkStatusKind::Added, DiffHunkStatusKind::Added],
13923        indoc! {r#"struct Row;
13924                   struct Row1;
13925                   struct Row1.1;
13926                   struct Row1.2;
13927                   struct Row2;ˇ
13928
13929                   struct Row4;
13930                   struct Row5;
13931                   struct Row6;
13932
13933                   struct Row8;
13934                   ˇstruct Row9;
13935                   struct Row9.1;
13936                   struct Row9.2;
13937                   struct Row9.3;
13938                   struct Row10;"#},
13939        base_text,
13940        &mut cx,
13941    );
13942    // Same for selections
13943    assert_hunk_revert(
13944        indoc! {r#"struct Row;
13945                   struct Row1;
13946                   struct Row2;
13947                   struct Row2.1;
13948                   struct Row2.2;
13949                   «ˇ
13950                   struct Row4;
13951                   struct» Row5;
13952                   «struct Row6;
13953                   ˇ»
13954                   struct Row9.1;
13955                   struct Row9.2;
13956                   struct Row9.3;
13957                   struct Row8;
13958                   struct Row9;
13959                   struct Row10;"#},
13960        vec![DiffHunkStatusKind::Added, DiffHunkStatusKind::Added],
13961        indoc! {r#"struct Row;
13962                   struct Row1;
13963                   struct Row2;
13964                   struct Row2.1;
13965                   struct Row2.2;
13966                   «ˇ
13967                   struct Row4;
13968                   struct» Row5;
13969                   «struct Row6;
13970                   ˇ»
13971                   struct Row9.1;
13972                   struct Row9.2;
13973                   struct Row9.3;
13974                   struct Row8;
13975                   struct Row9;
13976                   struct Row10;"#},
13977        base_text,
13978        &mut cx,
13979    );
13980
13981    // When carets and selections intersect the addition hunks, those are reverted.
13982    // Adjacent carets got merged.
13983    assert_hunk_revert(
13984        indoc! {r#"struct Row;
13985                   ˇ// something on the top
13986                   struct Row1;
13987                   struct Row2;
13988                   struct Roˇw3.1;
13989                   struct Row2.2;
13990                   struct Row2.3;ˇ
13991
13992                   struct Row4;
13993                   struct ˇRow5.1;
13994                   struct Row5.2;
13995                   struct «Rowˇ»5.3;
13996                   struct Row5;
13997                   struct Row6;
13998                   ˇ
13999                   struct Row9.1;
14000                   struct «Rowˇ»9.2;
14001                   struct «ˇRow»9.3;
14002                   struct Row8;
14003                   struct Row9;
14004                   «ˇ// something on bottom»
14005                   struct Row10;"#},
14006        vec![
14007            DiffHunkStatusKind::Added,
14008            DiffHunkStatusKind::Added,
14009            DiffHunkStatusKind::Added,
14010            DiffHunkStatusKind::Added,
14011            DiffHunkStatusKind::Added,
14012        ],
14013        indoc! {r#"struct Row;
14014                   ˇstruct Row1;
14015                   struct Row2;
14016                   ˇ
14017                   struct Row4;
14018                   ˇstruct Row5;
14019                   struct Row6;
14020                   ˇ
14021                   ˇstruct Row8;
14022                   struct Row9;
14023                   ˇstruct Row10;"#},
14024        base_text,
14025        &mut cx,
14026    );
14027}
14028
14029#[gpui::test]
14030async fn test_modification_reverts(cx: &mut TestAppContext) {
14031    init_test(cx, |_| {});
14032    let mut cx = EditorLspTestContext::new_rust(lsp::ServerCapabilities::default(), cx).await;
14033    let base_text = indoc! {r#"
14034        struct Row;
14035        struct Row1;
14036        struct Row2;
14037
14038        struct Row4;
14039        struct Row5;
14040        struct Row6;
14041
14042        struct Row8;
14043        struct Row9;
14044        struct Row10;"#};
14045
14046    // Modification hunks behave the same as the addition ones.
14047    assert_hunk_revert(
14048        indoc! {r#"struct Row;
14049                   struct Row1;
14050                   struct Row33;
14051                   ˇ
14052                   struct Row4;
14053                   struct Row5;
14054                   struct Row6;
14055                   ˇ
14056                   struct Row99;
14057                   struct Row9;
14058                   struct Row10;"#},
14059        vec![DiffHunkStatusKind::Modified, DiffHunkStatusKind::Modified],
14060        indoc! {r#"struct Row;
14061                   struct Row1;
14062                   struct Row33;
14063                   ˇ
14064                   struct Row4;
14065                   struct Row5;
14066                   struct Row6;
14067                   ˇ
14068                   struct Row99;
14069                   struct Row9;
14070                   struct Row10;"#},
14071        base_text,
14072        &mut cx,
14073    );
14074    assert_hunk_revert(
14075        indoc! {r#"struct Row;
14076                   struct Row1;
14077                   struct Row33;
14078                   «ˇ
14079                   struct Row4;
14080                   struct» Row5;
14081                   «struct Row6;
14082                   ˇ»
14083                   struct Row99;
14084                   struct Row9;
14085                   struct Row10;"#},
14086        vec![DiffHunkStatusKind::Modified, DiffHunkStatusKind::Modified],
14087        indoc! {r#"struct Row;
14088                   struct Row1;
14089                   struct Row33;
14090                   «ˇ
14091                   struct Row4;
14092                   struct» Row5;
14093                   «struct Row6;
14094                   ˇ»
14095                   struct Row99;
14096                   struct Row9;
14097                   struct Row10;"#},
14098        base_text,
14099        &mut cx,
14100    );
14101
14102    assert_hunk_revert(
14103        indoc! {r#"ˇstruct Row1.1;
14104                   struct Row1;
14105                   «ˇstr»uct Row22;
14106
14107                   struct ˇRow44;
14108                   struct Row5;
14109                   struct «Rˇ»ow66;ˇ
14110
14111                   «struˇ»ct Row88;
14112                   struct Row9;
14113                   struct Row1011;ˇ"#},
14114        vec![
14115            DiffHunkStatusKind::Modified,
14116            DiffHunkStatusKind::Modified,
14117            DiffHunkStatusKind::Modified,
14118            DiffHunkStatusKind::Modified,
14119            DiffHunkStatusKind::Modified,
14120            DiffHunkStatusKind::Modified,
14121        ],
14122        indoc! {r#"struct Row;
14123                   ˇstruct Row1;
14124                   struct Row2;
14125                   ˇ
14126                   struct Row4;
14127                   ˇstruct Row5;
14128                   struct Row6;
14129                   ˇ
14130                   struct Row8;
14131                   ˇstruct Row9;
14132                   struct Row10;ˇ"#},
14133        base_text,
14134        &mut cx,
14135    );
14136}
14137
14138#[gpui::test]
14139async fn test_deleting_over_diff_hunk(cx: &mut TestAppContext) {
14140    init_test(cx, |_| {});
14141    let mut cx = EditorLspTestContext::new_rust(lsp::ServerCapabilities::default(), cx).await;
14142    let base_text = indoc! {r#"
14143        one
14144
14145        two
14146        three
14147        "#};
14148
14149    cx.set_head_text(base_text);
14150    cx.set_state("\nˇ\n");
14151    cx.executor().run_until_parked();
14152    cx.update_editor(|editor, _window, cx| {
14153        editor.expand_selected_diff_hunks(cx);
14154    });
14155    cx.executor().run_until_parked();
14156    cx.update_editor(|editor, window, cx| {
14157        editor.backspace(&Default::default(), window, cx);
14158    });
14159    cx.run_until_parked();
14160    cx.assert_state_with_diff(
14161        indoc! {r#"
14162
14163        - two
14164        - threeˇ
14165        +
14166        "#}
14167        .to_string(),
14168    );
14169}
14170
14171#[gpui::test]
14172async fn test_deletion_reverts(cx: &mut TestAppContext) {
14173    init_test(cx, |_| {});
14174    let mut cx = EditorLspTestContext::new_rust(lsp::ServerCapabilities::default(), cx).await;
14175    let base_text = indoc! {r#"struct Row;
14176struct Row1;
14177struct Row2;
14178
14179struct Row4;
14180struct Row5;
14181struct Row6;
14182
14183struct Row8;
14184struct Row9;
14185struct Row10;"#};
14186
14187    // Deletion hunks trigger with carets on adjacent rows, so carets and selections have to stay farther to avoid the revert
14188    assert_hunk_revert(
14189        indoc! {r#"struct Row;
14190                   struct Row2;
14191
14192                   ˇstruct Row4;
14193                   struct Row5;
14194                   struct Row6;
14195                   ˇ
14196                   struct Row8;
14197                   struct Row10;"#},
14198        vec![DiffHunkStatusKind::Deleted, DiffHunkStatusKind::Deleted],
14199        indoc! {r#"struct Row;
14200                   struct Row2;
14201
14202                   ˇstruct Row4;
14203                   struct Row5;
14204                   struct Row6;
14205                   ˇ
14206                   struct Row8;
14207                   struct Row10;"#},
14208        base_text,
14209        &mut cx,
14210    );
14211    assert_hunk_revert(
14212        indoc! {r#"struct Row;
14213                   struct Row2;
14214
14215                   «ˇstruct Row4;
14216                   struct» Row5;
14217                   «struct Row6;
14218                   ˇ»
14219                   struct Row8;
14220                   struct Row10;"#},
14221        vec![DiffHunkStatusKind::Deleted, DiffHunkStatusKind::Deleted],
14222        indoc! {r#"struct Row;
14223                   struct Row2;
14224
14225                   «ˇstruct Row4;
14226                   struct» Row5;
14227                   «struct Row6;
14228                   ˇ»
14229                   struct Row8;
14230                   struct Row10;"#},
14231        base_text,
14232        &mut cx,
14233    );
14234
14235    // Deletion hunks are ephemeral, so it's impossible to place the caret into them — Zed triggers reverts for lines, adjacent to carets and selections.
14236    assert_hunk_revert(
14237        indoc! {r#"struct Row;
14238                   ˇstruct Row2;
14239
14240                   struct Row4;
14241                   struct Row5;
14242                   struct Row6;
14243
14244                   struct Row8;ˇ
14245                   struct Row10;"#},
14246        vec![DiffHunkStatusKind::Deleted, DiffHunkStatusKind::Deleted],
14247        indoc! {r#"struct Row;
14248                   struct Row1;
14249                   ˇstruct Row2;
14250
14251                   struct Row4;
14252                   struct Row5;
14253                   struct Row6;
14254
14255                   struct Row8;ˇ
14256                   struct Row9;
14257                   struct Row10;"#},
14258        base_text,
14259        &mut cx,
14260    );
14261    assert_hunk_revert(
14262        indoc! {r#"struct Row;
14263                   struct Row2«ˇ;
14264                   struct Row4;
14265                   struct» Row5;
14266                   «struct Row6;
14267
14268                   struct Row8;ˇ»
14269                   struct Row10;"#},
14270        vec![
14271            DiffHunkStatusKind::Deleted,
14272            DiffHunkStatusKind::Deleted,
14273            DiffHunkStatusKind::Deleted,
14274        ],
14275        indoc! {r#"struct Row;
14276                   struct Row1;
14277                   struct Row2«ˇ;
14278
14279                   struct Row4;
14280                   struct» Row5;
14281                   «struct Row6;
14282
14283                   struct Row8;ˇ»
14284                   struct Row9;
14285                   struct Row10;"#},
14286        base_text,
14287        &mut cx,
14288    );
14289}
14290
14291#[gpui::test]
14292async fn test_multibuffer_reverts(cx: &mut TestAppContext) {
14293    init_test(cx, |_| {});
14294
14295    let base_text_1 = "aaaa\nbbbb\ncccc\ndddd\neeee\nffff\ngggg\nhhhh\niiii\njjjj";
14296    let base_text_2 = "llll\nmmmm\nnnnn\noooo\npppp\nqqqq\nrrrr\nssss\ntttt\nuuuu";
14297    let base_text_3 =
14298        "vvvv\nwwww\nxxxx\nyyyy\nzzzz\n{{{{\n||||\n}}}}\n~~~~\n\u{7f}\u{7f}\u{7f}\u{7f}";
14299
14300    let text_1 = edit_first_char_of_every_line(base_text_1);
14301    let text_2 = edit_first_char_of_every_line(base_text_2);
14302    let text_3 = edit_first_char_of_every_line(base_text_3);
14303
14304    let buffer_1 = cx.new(|cx| Buffer::local(text_1.clone(), cx));
14305    let buffer_2 = cx.new(|cx| Buffer::local(text_2.clone(), cx));
14306    let buffer_3 = cx.new(|cx| Buffer::local(text_3.clone(), cx));
14307
14308    let multibuffer = cx.new(|cx| {
14309        let mut multibuffer = MultiBuffer::new(ReadWrite);
14310        multibuffer.push_excerpts(
14311            buffer_1.clone(),
14312            [
14313                ExcerptRange::new(Point::new(0, 0)..Point::new(3, 0)),
14314                ExcerptRange::new(Point::new(5, 0)..Point::new(7, 0)),
14315                ExcerptRange::new(Point::new(9, 0)..Point::new(10, 4)),
14316            ],
14317            cx,
14318        );
14319        multibuffer.push_excerpts(
14320            buffer_2.clone(),
14321            [
14322                ExcerptRange::new(Point::new(0, 0)..Point::new(3, 0)),
14323                ExcerptRange::new(Point::new(5, 0)..Point::new(7, 0)),
14324                ExcerptRange::new(Point::new(9, 0)..Point::new(10, 4)),
14325            ],
14326            cx,
14327        );
14328        multibuffer.push_excerpts(
14329            buffer_3.clone(),
14330            [
14331                ExcerptRange::new(Point::new(0, 0)..Point::new(3, 0)),
14332                ExcerptRange::new(Point::new(5, 0)..Point::new(7, 0)),
14333                ExcerptRange::new(Point::new(9, 0)..Point::new(10, 4)),
14334            ],
14335            cx,
14336        );
14337        multibuffer
14338    });
14339
14340    let fs = FakeFs::new(cx.executor());
14341    let project = Project::test(fs, [path!("/").as_ref()], cx).await;
14342    let (editor, cx) = cx
14343        .add_window_view(|window, cx| build_editor_with_project(project, multibuffer, window, cx));
14344    editor.update_in(cx, |editor, _window, cx| {
14345        for (buffer, diff_base) in [
14346            (buffer_1.clone(), base_text_1),
14347            (buffer_2.clone(), base_text_2),
14348            (buffer_3.clone(), base_text_3),
14349        ] {
14350            let diff = cx.new(|cx| BufferDiff::new_with_base_text(&diff_base, &buffer, cx));
14351            editor
14352                .buffer
14353                .update(cx, |buffer, cx| buffer.add_diff(diff, cx));
14354        }
14355    });
14356    cx.executor().run_until_parked();
14357
14358    editor.update_in(cx, |editor, window, cx| {
14359        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}");
14360        editor.select_all(&SelectAll, window, cx);
14361        editor.git_restore(&Default::default(), window, cx);
14362    });
14363    cx.executor().run_until_parked();
14364
14365    // When all ranges are selected, all buffer hunks are reverted.
14366    editor.update(cx, |editor, cx| {
14367        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");
14368    });
14369    buffer_1.update(cx, |buffer, _| {
14370        assert_eq!(buffer.text(), base_text_1);
14371    });
14372    buffer_2.update(cx, |buffer, _| {
14373        assert_eq!(buffer.text(), base_text_2);
14374    });
14375    buffer_3.update(cx, |buffer, _| {
14376        assert_eq!(buffer.text(), base_text_3);
14377    });
14378
14379    editor.update_in(cx, |editor, window, cx| {
14380        editor.undo(&Default::default(), window, cx);
14381    });
14382
14383    editor.update_in(cx, |editor, window, cx| {
14384        editor.change_selections(None, window, cx, |s| {
14385            s.select_ranges(Some(Point::new(0, 0)..Point::new(6, 0)));
14386        });
14387        editor.git_restore(&Default::default(), window, cx);
14388    });
14389
14390    // Now, when all ranges selected belong to buffer_1, the revert should succeed,
14391    // but not affect buffer_2 and its related excerpts.
14392    editor.update(cx, |editor, cx| {
14393        assert_eq!(
14394            editor.text(cx),
14395            "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}"
14396        );
14397    });
14398    buffer_1.update(cx, |buffer, _| {
14399        assert_eq!(buffer.text(), base_text_1);
14400    });
14401    buffer_2.update(cx, |buffer, _| {
14402        assert_eq!(
14403            buffer.text(),
14404            "Xlll\nXmmm\nXnnn\nXooo\nXppp\nXqqq\nXrrr\nXsss\nXttt\nXuuu"
14405        );
14406    });
14407    buffer_3.update(cx, |buffer, _| {
14408        assert_eq!(
14409            buffer.text(),
14410            "Xvvv\nXwww\nXxxx\nXyyy\nXzzz\nX{{{\nX|||\nX}}}\nX~~~\nX\u{7f}\u{7f}\u{7f}"
14411        );
14412    });
14413
14414    fn edit_first_char_of_every_line(text: &str) -> String {
14415        text.split('\n')
14416            .map(|line| format!("X{}", &line[1..]))
14417            .collect::<Vec<_>>()
14418            .join("\n")
14419    }
14420}
14421
14422#[gpui::test]
14423async fn test_mutlibuffer_in_navigation_history(cx: &mut TestAppContext) {
14424    init_test(cx, |_| {});
14425
14426    let cols = 4;
14427    let rows = 10;
14428    let sample_text_1 = sample_text(rows, cols, 'a');
14429    assert_eq!(
14430        sample_text_1,
14431        "aaaa\nbbbb\ncccc\ndddd\neeee\nffff\ngggg\nhhhh\niiii\njjjj"
14432    );
14433    let sample_text_2 = sample_text(rows, cols, 'l');
14434    assert_eq!(
14435        sample_text_2,
14436        "llll\nmmmm\nnnnn\noooo\npppp\nqqqq\nrrrr\nssss\ntttt\nuuuu"
14437    );
14438    let sample_text_3 = sample_text(rows, cols, 'v');
14439    assert_eq!(
14440        sample_text_3,
14441        "vvvv\nwwww\nxxxx\nyyyy\nzzzz\n{{{{\n||||\n}}}}\n~~~~\n\u{7f}\u{7f}\u{7f}\u{7f}"
14442    );
14443
14444    let buffer_1 = cx.new(|cx| Buffer::local(sample_text_1.clone(), cx));
14445    let buffer_2 = cx.new(|cx| Buffer::local(sample_text_2.clone(), cx));
14446    let buffer_3 = cx.new(|cx| Buffer::local(sample_text_3.clone(), cx));
14447
14448    let multi_buffer = cx.new(|cx| {
14449        let mut multibuffer = MultiBuffer::new(ReadWrite);
14450        multibuffer.push_excerpts(
14451            buffer_1.clone(),
14452            [
14453                ExcerptRange::new(Point::new(0, 0)..Point::new(3, 0)),
14454                ExcerptRange::new(Point::new(5, 0)..Point::new(7, 0)),
14455                ExcerptRange::new(Point::new(9, 0)..Point::new(10, 4)),
14456            ],
14457            cx,
14458        );
14459        multibuffer.push_excerpts(
14460            buffer_2.clone(),
14461            [
14462                ExcerptRange::new(Point::new(0, 0)..Point::new(3, 0)),
14463                ExcerptRange::new(Point::new(5, 0)..Point::new(7, 0)),
14464                ExcerptRange::new(Point::new(9, 0)..Point::new(10, 4)),
14465            ],
14466            cx,
14467        );
14468        multibuffer.push_excerpts(
14469            buffer_3.clone(),
14470            [
14471                ExcerptRange::new(Point::new(0, 0)..Point::new(3, 0)),
14472                ExcerptRange::new(Point::new(5, 0)..Point::new(7, 0)),
14473                ExcerptRange::new(Point::new(9, 0)..Point::new(10, 4)),
14474            ],
14475            cx,
14476        );
14477        multibuffer
14478    });
14479
14480    let fs = FakeFs::new(cx.executor());
14481    fs.insert_tree(
14482        "/a",
14483        json!({
14484            "main.rs": sample_text_1,
14485            "other.rs": sample_text_2,
14486            "lib.rs": sample_text_3,
14487        }),
14488    )
14489    .await;
14490    let project = Project::test(fs, ["/a".as_ref()], cx).await;
14491    let workspace = cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
14492    let cx = &mut VisualTestContext::from_window(*workspace.deref(), cx);
14493    let multi_buffer_editor = cx.new_window_entity(|window, cx| {
14494        Editor::new(
14495            EditorMode::full(),
14496            multi_buffer,
14497            Some(project.clone()),
14498            window,
14499            cx,
14500        )
14501    });
14502    let multibuffer_item_id = workspace
14503        .update(cx, |workspace, window, cx| {
14504            assert!(
14505                workspace.active_item(cx).is_none(),
14506                "active item should be None before the first item is added"
14507            );
14508            workspace.add_item_to_active_pane(
14509                Box::new(multi_buffer_editor.clone()),
14510                None,
14511                true,
14512                window,
14513                cx,
14514            );
14515            let active_item = workspace
14516                .active_item(cx)
14517                .expect("should have an active item after adding the multi buffer");
14518            assert!(
14519                !active_item.is_singleton(cx),
14520                "A multi buffer was expected to active after adding"
14521            );
14522            active_item.item_id()
14523        })
14524        .unwrap();
14525    cx.executor().run_until_parked();
14526
14527    multi_buffer_editor.update_in(cx, |editor, window, cx| {
14528        editor.change_selections(Some(Autoscroll::Next), window, cx, |s| {
14529            s.select_ranges(Some(1..2))
14530        });
14531        editor.open_excerpts(&OpenExcerpts, window, cx);
14532    });
14533    cx.executor().run_until_parked();
14534    let first_item_id = workspace
14535        .update(cx, |workspace, window, cx| {
14536            let active_item = workspace
14537                .active_item(cx)
14538                .expect("should have an active item after navigating into the 1st buffer");
14539            let first_item_id = active_item.item_id();
14540            assert_ne!(
14541                first_item_id, multibuffer_item_id,
14542                "Should navigate into the 1st buffer and activate it"
14543            );
14544            assert!(
14545                active_item.is_singleton(cx),
14546                "New active item should be a singleton buffer"
14547            );
14548            assert_eq!(
14549                active_item
14550                    .act_as::<Editor>(cx)
14551                    .expect("should have navigated into an editor for the 1st buffer")
14552                    .read(cx)
14553                    .text(cx),
14554                sample_text_1
14555            );
14556
14557            workspace
14558                .go_back(workspace.active_pane().downgrade(), window, cx)
14559                .detach_and_log_err(cx);
14560
14561            first_item_id
14562        })
14563        .unwrap();
14564    cx.executor().run_until_parked();
14565    workspace
14566        .update(cx, |workspace, _, cx| {
14567            let active_item = workspace
14568                .active_item(cx)
14569                .expect("should have an active item after navigating back");
14570            assert_eq!(
14571                active_item.item_id(),
14572                multibuffer_item_id,
14573                "Should navigate back to the multi buffer"
14574            );
14575            assert!(!active_item.is_singleton(cx));
14576        })
14577        .unwrap();
14578
14579    multi_buffer_editor.update_in(cx, |editor, window, cx| {
14580        editor.change_selections(Some(Autoscroll::Next), window, cx, |s| {
14581            s.select_ranges(Some(39..40))
14582        });
14583        editor.open_excerpts(&OpenExcerpts, window, cx);
14584    });
14585    cx.executor().run_until_parked();
14586    let second_item_id = workspace
14587        .update(cx, |workspace, window, cx| {
14588            let active_item = workspace
14589                .active_item(cx)
14590                .expect("should have an active item after navigating into the 2nd buffer");
14591            let second_item_id = active_item.item_id();
14592            assert_ne!(
14593                second_item_id, multibuffer_item_id,
14594                "Should navigate away from the multibuffer"
14595            );
14596            assert_ne!(
14597                second_item_id, first_item_id,
14598                "Should navigate into the 2nd buffer and activate it"
14599            );
14600            assert!(
14601                active_item.is_singleton(cx),
14602                "New active item should be a singleton buffer"
14603            );
14604            assert_eq!(
14605                active_item
14606                    .act_as::<Editor>(cx)
14607                    .expect("should have navigated into an editor")
14608                    .read(cx)
14609                    .text(cx),
14610                sample_text_2
14611            );
14612
14613            workspace
14614                .go_back(workspace.active_pane().downgrade(), window, cx)
14615                .detach_and_log_err(cx);
14616
14617            second_item_id
14618        })
14619        .unwrap();
14620    cx.executor().run_until_parked();
14621    workspace
14622        .update(cx, |workspace, _, cx| {
14623            let active_item = workspace
14624                .active_item(cx)
14625                .expect("should have an active item after navigating back from the 2nd buffer");
14626            assert_eq!(
14627                active_item.item_id(),
14628                multibuffer_item_id,
14629                "Should navigate back from the 2nd buffer to the multi buffer"
14630            );
14631            assert!(!active_item.is_singleton(cx));
14632        })
14633        .unwrap();
14634
14635    multi_buffer_editor.update_in(cx, |editor, window, cx| {
14636        editor.change_selections(Some(Autoscroll::Next), window, cx, |s| {
14637            s.select_ranges(Some(70..70))
14638        });
14639        editor.open_excerpts(&OpenExcerpts, window, cx);
14640    });
14641    cx.executor().run_until_parked();
14642    workspace
14643        .update(cx, |workspace, window, cx| {
14644            let active_item = workspace
14645                .active_item(cx)
14646                .expect("should have an active item after navigating into the 3rd buffer");
14647            let third_item_id = active_item.item_id();
14648            assert_ne!(
14649                third_item_id, multibuffer_item_id,
14650                "Should navigate into the 3rd buffer and activate it"
14651            );
14652            assert_ne!(third_item_id, first_item_id);
14653            assert_ne!(third_item_id, second_item_id);
14654            assert!(
14655                active_item.is_singleton(cx),
14656                "New active item should be a singleton buffer"
14657            );
14658            assert_eq!(
14659                active_item
14660                    .act_as::<Editor>(cx)
14661                    .expect("should have navigated into an editor")
14662                    .read(cx)
14663                    .text(cx),
14664                sample_text_3
14665            );
14666
14667            workspace
14668                .go_back(workspace.active_pane().downgrade(), window, cx)
14669                .detach_and_log_err(cx);
14670        })
14671        .unwrap();
14672    cx.executor().run_until_parked();
14673    workspace
14674        .update(cx, |workspace, _, cx| {
14675            let active_item = workspace
14676                .active_item(cx)
14677                .expect("should have an active item after navigating back from the 3rd buffer");
14678            assert_eq!(
14679                active_item.item_id(),
14680                multibuffer_item_id,
14681                "Should navigate back from the 3rd buffer to the multi buffer"
14682            );
14683            assert!(!active_item.is_singleton(cx));
14684        })
14685        .unwrap();
14686}
14687
14688#[gpui::test]
14689async fn test_toggle_selected_diff_hunks(executor: BackgroundExecutor, cx: &mut TestAppContext) {
14690    init_test(cx, |_| {});
14691
14692    let mut cx = EditorTestContext::new(cx).await;
14693
14694    let diff_base = r#"
14695        use some::mod;
14696
14697        const A: u32 = 42;
14698
14699        fn main() {
14700            println!("hello");
14701
14702            println!("world");
14703        }
14704        "#
14705    .unindent();
14706
14707    cx.set_state(
14708        &r#"
14709        use some::modified;
14710
14711        ˇ
14712        fn main() {
14713            println!("hello there");
14714
14715            println!("around the");
14716            println!("world");
14717        }
14718        "#
14719        .unindent(),
14720    );
14721
14722    cx.set_head_text(&diff_base);
14723    executor.run_until_parked();
14724
14725    cx.update_editor(|editor, window, cx| {
14726        editor.go_to_next_hunk(&GoToHunk, window, cx);
14727        editor.toggle_selected_diff_hunks(&ToggleSelectedDiffHunks, window, cx);
14728    });
14729    executor.run_until_parked();
14730    cx.assert_state_with_diff(
14731        r#"
14732          use some::modified;
14733
14734
14735          fn main() {
14736        -     println!("hello");
14737        + ˇ    println!("hello there");
14738
14739              println!("around the");
14740              println!("world");
14741          }
14742        "#
14743        .unindent(),
14744    );
14745
14746    cx.update_editor(|editor, window, cx| {
14747        for _ in 0..2 {
14748            editor.go_to_next_hunk(&GoToHunk, window, cx);
14749            editor.toggle_selected_diff_hunks(&ToggleSelectedDiffHunks, window, cx);
14750        }
14751    });
14752    executor.run_until_parked();
14753    cx.assert_state_with_diff(
14754        r#"
14755        - use some::mod;
14756        + ˇuse some::modified;
14757
14758
14759          fn main() {
14760        -     println!("hello");
14761        +     println!("hello there");
14762
14763        +     println!("around the");
14764              println!("world");
14765          }
14766        "#
14767        .unindent(),
14768    );
14769
14770    cx.update_editor(|editor, window, cx| {
14771        editor.go_to_next_hunk(&GoToHunk, window, cx);
14772        editor.toggle_selected_diff_hunks(&ToggleSelectedDiffHunks, window, cx);
14773    });
14774    executor.run_until_parked();
14775    cx.assert_state_with_diff(
14776        r#"
14777        - use some::mod;
14778        + use some::modified;
14779
14780        - const A: u32 = 42;
14781          ˇ
14782          fn main() {
14783        -     println!("hello");
14784        +     println!("hello there");
14785
14786        +     println!("around the");
14787              println!("world");
14788          }
14789        "#
14790        .unindent(),
14791    );
14792
14793    cx.update_editor(|editor, window, cx| {
14794        editor.cancel(&Cancel, window, cx);
14795    });
14796
14797    cx.assert_state_with_diff(
14798        r#"
14799          use some::modified;
14800
14801          ˇ
14802          fn main() {
14803              println!("hello there");
14804
14805              println!("around the");
14806              println!("world");
14807          }
14808        "#
14809        .unindent(),
14810    );
14811}
14812
14813#[gpui::test]
14814async fn test_diff_base_change_with_expanded_diff_hunks(
14815    executor: BackgroundExecutor,
14816    cx: &mut TestAppContext,
14817) {
14818    init_test(cx, |_| {});
14819
14820    let mut cx = EditorTestContext::new(cx).await;
14821
14822    let diff_base = r#"
14823        use some::mod1;
14824        use some::mod2;
14825
14826        const A: u32 = 42;
14827        const B: u32 = 42;
14828        const C: u32 = 42;
14829
14830        fn main() {
14831            println!("hello");
14832
14833            println!("world");
14834        }
14835        "#
14836    .unindent();
14837
14838    cx.set_state(
14839        &r#"
14840        use some::mod2;
14841
14842        const A: u32 = 42;
14843        const C: u32 = 42;
14844
14845        fn main(ˇ) {
14846            //println!("hello");
14847
14848            println!("world");
14849            //
14850            //
14851        }
14852        "#
14853        .unindent(),
14854    );
14855
14856    cx.set_head_text(&diff_base);
14857    executor.run_until_parked();
14858
14859    cx.update_editor(|editor, window, cx| {
14860        editor.expand_all_diff_hunks(&ExpandAllDiffHunks, window, cx);
14861    });
14862    executor.run_until_parked();
14863    cx.assert_state_with_diff(
14864        r#"
14865        - use some::mod1;
14866          use some::mod2;
14867
14868          const A: u32 = 42;
14869        - const B: u32 = 42;
14870          const C: u32 = 42;
14871
14872          fn main(ˇ) {
14873        -     println!("hello");
14874        +     //println!("hello");
14875
14876              println!("world");
14877        +     //
14878        +     //
14879          }
14880        "#
14881        .unindent(),
14882    );
14883
14884    cx.set_head_text("new diff base!");
14885    executor.run_until_parked();
14886    cx.assert_state_with_diff(
14887        r#"
14888        - new diff base!
14889        + use some::mod2;
14890        +
14891        + const A: u32 = 42;
14892        + const C: u32 = 42;
14893        +
14894        + fn main(ˇ) {
14895        +     //println!("hello");
14896        +
14897        +     println!("world");
14898        +     //
14899        +     //
14900        + }
14901        "#
14902        .unindent(),
14903    );
14904}
14905
14906#[gpui::test]
14907async fn test_toggle_diff_expand_in_multi_buffer(cx: &mut TestAppContext) {
14908    init_test(cx, |_| {});
14909
14910    let file_1_old = "aaa\nbbb\nccc\nddd\neee\nfff\nggg\nhhh\niii\njjj";
14911    let file_1_new = "aaa\nccc\nddd\neee\nfff\nggg\nhhh\niii\njjj";
14912    let file_2_old = "lll\nmmm\nnnn\nooo\nppp\nqqq\nrrr\nsss\nttt\nuuu";
14913    let file_2_new = "lll\nmmm\nNNN\nooo\nppp\nqqq\nrrr\nsss\nttt\nuuu";
14914    let file_3_old = "111\n222\n333\n444\n555\n777\n888\n999\n000\n!!!";
14915    let file_3_new = "111\n222\n333\n444\n555\n666\n777\n888\n999\n000\n!!!";
14916
14917    let buffer_1 = cx.new(|cx| Buffer::local(file_1_new.to_string(), cx));
14918    let buffer_2 = cx.new(|cx| Buffer::local(file_2_new.to_string(), cx));
14919    let buffer_3 = cx.new(|cx| Buffer::local(file_3_new.to_string(), cx));
14920
14921    let multi_buffer = cx.new(|cx| {
14922        let mut multibuffer = MultiBuffer::new(ReadWrite);
14923        multibuffer.push_excerpts(
14924            buffer_1.clone(),
14925            [
14926                ExcerptRange::new(Point::new(0, 0)..Point::new(3, 0)),
14927                ExcerptRange::new(Point::new(5, 0)..Point::new(7, 0)),
14928                ExcerptRange::new(Point::new(9, 0)..Point::new(10, 3)),
14929            ],
14930            cx,
14931        );
14932        multibuffer.push_excerpts(
14933            buffer_2.clone(),
14934            [
14935                ExcerptRange::new(Point::new(0, 0)..Point::new(3, 0)),
14936                ExcerptRange::new(Point::new(5, 0)..Point::new(7, 0)),
14937                ExcerptRange::new(Point::new(9, 0)..Point::new(10, 3)),
14938            ],
14939            cx,
14940        );
14941        multibuffer.push_excerpts(
14942            buffer_3.clone(),
14943            [
14944                ExcerptRange::new(Point::new(0, 0)..Point::new(3, 0)),
14945                ExcerptRange::new(Point::new(5, 0)..Point::new(7, 0)),
14946                ExcerptRange::new(Point::new(9, 0)..Point::new(10, 3)),
14947            ],
14948            cx,
14949        );
14950        multibuffer
14951    });
14952
14953    let editor =
14954        cx.add_window(|window, cx| Editor::new(EditorMode::full(), multi_buffer, None, window, cx));
14955    editor
14956        .update(cx, |editor, _window, cx| {
14957            for (buffer, diff_base) in [
14958                (buffer_1.clone(), file_1_old),
14959                (buffer_2.clone(), file_2_old),
14960                (buffer_3.clone(), file_3_old),
14961            ] {
14962                let diff = cx.new(|cx| BufferDiff::new_with_base_text(&diff_base, &buffer, cx));
14963                editor
14964                    .buffer
14965                    .update(cx, |buffer, cx| buffer.add_diff(diff, cx));
14966            }
14967        })
14968        .unwrap();
14969
14970    let mut cx = EditorTestContext::for_editor(editor, cx).await;
14971    cx.run_until_parked();
14972
14973    cx.assert_editor_state(
14974        &"
14975            ˇaaa
14976            ccc
14977            ddd
14978
14979            ggg
14980            hhh
14981
14982
14983            lll
14984            mmm
14985            NNN
14986
14987            qqq
14988            rrr
14989
14990            uuu
14991            111
14992            222
14993            333
14994
14995            666
14996            777
14997
14998            000
14999            !!!"
15000        .unindent(),
15001    );
15002
15003    cx.update_editor(|editor, window, cx| {
15004        editor.select_all(&SelectAll, window, cx);
15005        editor.toggle_selected_diff_hunks(&ToggleSelectedDiffHunks, window, cx);
15006    });
15007    cx.executor().run_until_parked();
15008
15009    cx.assert_state_with_diff(
15010        "
15011            «aaa
15012          - bbb
15013            ccc
15014            ddd
15015
15016            ggg
15017            hhh
15018
15019
15020            lll
15021            mmm
15022          - nnn
15023          + NNN
15024
15025            qqq
15026            rrr
15027
15028            uuu
15029            111
15030            222
15031            333
15032
15033          + 666
15034            777
15035
15036            000
15037            !!!ˇ»"
15038            .unindent(),
15039    );
15040}
15041
15042#[gpui::test]
15043async fn test_expand_diff_hunk_at_excerpt_boundary(cx: &mut TestAppContext) {
15044    init_test(cx, |_| {});
15045
15046    let base = "aaa\nbbb\nccc\nddd\neee\nfff\nggg\n";
15047    let text = "aaa\nBBB\nBB2\nccc\nDDD\nEEE\nfff\nggg\nhhh\niii\n";
15048
15049    let buffer = cx.new(|cx| Buffer::local(text.to_string(), cx));
15050    let multi_buffer = cx.new(|cx| {
15051        let mut multibuffer = MultiBuffer::new(ReadWrite);
15052        multibuffer.push_excerpts(
15053            buffer.clone(),
15054            [
15055                ExcerptRange::new(Point::new(0, 0)..Point::new(2, 0)),
15056                ExcerptRange::new(Point::new(4, 0)..Point::new(7, 0)),
15057                ExcerptRange::new(Point::new(9, 0)..Point::new(10, 0)),
15058            ],
15059            cx,
15060        );
15061        multibuffer
15062    });
15063
15064    let editor =
15065        cx.add_window(|window, cx| Editor::new(EditorMode::full(), multi_buffer, None, window, cx));
15066    editor
15067        .update(cx, |editor, _window, cx| {
15068            let diff = cx.new(|cx| BufferDiff::new_with_base_text(base, &buffer, cx));
15069            editor
15070                .buffer
15071                .update(cx, |buffer, cx| buffer.add_diff(diff, cx))
15072        })
15073        .unwrap();
15074
15075    let mut cx = EditorTestContext::for_editor(editor, cx).await;
15076    cx.run_until_parked();
15077
15078    cx.update_editor(|editor, window, cx| {
15079        editor.expand_all_diff_hunks(&Default::default(), window, cx)
15080    });
15081    cx.executor().run_until_parked();
15082
15083    // When the start of a hunk coincides with the start of its excerpt,
15084    // the hunk is expanded. When the start of a a hunk is earlier than
15085    // the start of its excerpt, the hunk is not expanded.
15086    cx.assert_state_with_diff(
15087        "
15088            ˇaaa
15089          - bbb
15090          + BBB
15091
15092          - ddd
15093          - eee
15094          + DDD
15095          + EEE
15096            fff
15097
15098            iii
15099        "
15100        .unindent(),
15101    );
15102}
15103
15104#[gpui::test]
15105async fn test_edits_around_expanded_insertion_hunks(
15106    executor: BackgroundExecutor,
15107    cx: &mut TestAppContext,
15108) {
15109    init_test(cx, |_| {});
15110
15111    let mut cx = EditorTestContext::new(cx).await;
15112
15113    let diff_base = r#"
15114        use some::mod1;
15115        use some::mod2;
15116
15117        const A: u32 = 42;
15118
15119        fn main() {
15120            println!("hello");
15121
15122            println!("world");
15123        }
15124        "#
15125    .unindent();
15126    executor.run_until_parked();
15127    cx.set_state(
15128        &r#"
15129        use some::mod1;
15130        use some::mod2;
15131
15132        const A: u32 = 42;
15133        const B: u32 = 42;
15134        const C: u32 = 42;
15135        ˇ
15136
15137        fn main() {
15138            println!("hello");
15139
15140            println!("world");
15141        }
15142        "#
15143        .unindent(),
15144    );
15145
15146    cx.set_head_text(&diff_base);
15147    executor.run_until_parked();
15148
15149    cx.update_editor(|editor, window, cx| {
15150        editor.expand_all_diff_hunks(&ExpandAllDiffHunks, window, cx);
15151    });
15152    executor.run_until_parked();
15153
15154    cx.assert_state_with_diff(
15155        r#"
15156        use some::mod1;
15157        use some::mod2;
15158
15159        const A: u32 = 42;
15160      + const B: u32 = 42;
15161      + const C: u32 = 42;
15162      + ˇ
15163
15164        fn main() {
15165            println!("hello");
15166
15167            println!("world");
15168        }
15169      "#
15170        .unindent(),
15171    );
15172
15173    cx.update_editor(|editor, window, cx| editor.handle_input("const D: u32 = 42;\n", window, cx));
15174    executor.run_until_parked();
15175
15176    cx.assert_state_with_diff(
15177        r#"
15178        use some::mod1;
15179        use some::mod2;
15180
15181        const A: u32 = 42;
15182      + const B: u32 = 42;
15183      + const C: u32 = 42;
15184      + const D: u32 = 42;
15185      + ˇ
15186
15187        fn main() {
15188            println!("hello");
15189
15190            println!("world");
15191        }
15192      "#
15193        .unindent(),
15194    );
15195
15196    cx.update_editor(|editor, window, cx| editor.handle_input("const E: u32 = 42;\n", window, cx));
15197    executor.run_until_parked();
15198
15199    cx.assert_state_with_diff(
15200        r#"
15201        use some::mod1;
15202        use some::mod2;
15203
15204        const A: u32 = 42;
15205      + const B: u32 = 42;
15206      + const C: u32 = 42;
15207      + const D: u32 = 42;
15208      + const E: u32 = 42;
15209      + ˇ
15210
15211        fn main() {
15212            println!("hello");
15213
15214            println!("world");
15215        }
15216      "#
15217        .unindent(),
15218    );
15219
15220    cx.update_editor(|editor, window, cx| {
15221        editor.delete_line(&DeleteLine, window, cx);
15222    });
15223    executor.run_until_parked();
15224
15225    cx.assert_state_with_diff(
15226        r#"
15227        use some::mod1;
15228        use some::mod2;
15229
15230        const A: u32 = 42;
15231      + const B: u32 = 42;
15232      + const C: u32 = 42;
15233      + const D: u32 = 42;
15234      + const E: u32 = 42;
15235        ˇ
15236        fn main() {
15237            println!("hello");
15238
15239            println!("world");
15240        }
15241      "#
15242        .unindent(),
15243    );
15244
15245    cx.update_editor(|editor, window, cx| {
15246        editor.move_up(&MoveUp, window, cx);
15247        editor.delete_line(&DeleteLine, window, cx);
15248        editor.move_up(&MoveUp, window, cx);
15249        editor.delete_line(&DeleteLine, window, cx);
15250        editor.move_up(&MoveUp, window, cx);
15251        editor.delete_line(&DeleteLine, window, cx);
15252    });
15253    executor.run_until_parked();
15254    cx.assert_state_with_diff(
15255        r#"
15256        use some::mod1;
15257        use some::mod2;
15258
15259        const A: u32 = 42;
15260      + const B: u32 = 42;
15261        ˇ
15262        fn main() {
15263            println!("hello");
15264
15265            println!("world");
15266        }
15267      "#
15268        .unindent(),
15269    );
15270
15271    cx.update_editor(|editor, window, cx| {
15272        editor.select_up_by_lines(&SelectUpByLines { lines: 5 }, window, cx);
15273        editor.delete_line(&DeleteLine, window, cx);
15274    });
15275    executor.run_until_parked();
15276    cx.assert_state_with_diff(
15277        r#"
15278        ˇ
15279        fn main() {
15280            println!("hello");
15281
15282            println!("world");
15283        }
15284      "#
15285        .unindent(),
15286    );
15287}
15288
15289#[gpui::test]
15290async fn test_toggling_adjacent_diff_hunks(cx: &mut TestAppContext) {
15291    init_test(cx, |_| {});
15292
15293    let mut cx = EditorTestContext::new(cx).await;
15294    cx.set_head_text(indoc! { "
15295        one
15296        two
15297        three
15298        four
15299        five
15300        "
15301    });
15302    cx.set_state(indoc! { "
15303        one
15304        ˇthree
15305        five
15306    "});
15307    cx.run_until_parked();
15308    cx.update_editor(|editor, window, cx| {
15309        editor.toggle_selected_diff_hunks(&Default::default(), window, cx);
15310    });
15311    cx.assert_state_with_diff(
15312        indoc! { "
15313        one
15314      - two
15315        ˇthree
15316      - four
15317        five
15318    "}
15319        .to_string(),
15320    );
15321    cx.update_editor(|editor, window, cx| {
15322        editor.toggle_selected_diff_hunks(&Default::default(), window, cx);
15323    });
15324
15325    cx.assert_state_with_diff(
15326        indoc! { "
15327        one
15328        ˇthree
15329        five
15330    "}
15331        .to_string(),
15332    );
15333
15334    cx.set_state(indoc! { "
15335        one
15336        ˇTWO
15337        three
15338        four
15339        five
15340    "});
15341    cx.run_until_parked();
15342    cx.update_editor(|editor, window, cx| {
15343        editor.toggle_selected_diff_hunks(&Default::default(), window, cx);
15344    });
15345
15346    cx.assert_state_with_diff(
15347        indoc! { "
15348            one
15349          - two
15350          + ˇTWO
15351            three
15352            four
15353            five
15354        "}
15355        .to_string(),
15356    );
15357    cx.update_editor(|editor, window, cx| {
15358        editor.move_up(&Default::default(), window, cx);
15359        editor.toggle_selected_diff_hunks(&Default::default(), window, cx);
15360    });
15361    cx.assert_state_with_diff(
15362        indoc! { "
15363            one
15364            ˇTWO
15365            three
15366            four
15367            five
15368        "}
15369        .to_string(),
15370    );
15371}
15372
15373#[gpui::test]
15374async fn test_edits_around_expanded_deletion_hunks(
15375    executor: BackgroundExecutor,
15376    cx: &mut TestAppContext,
15377) {
15378    init_test(cx, |_| {});
15379
15380    let mut cx = EditorTestContext::new(cx).await;
15381
15382    let diff_base = r#"
15383        use some::mod1;
15384        use some::mod2;
15385
15386        const A: u32 = 42;
15387        const B: u32 = 42;
15388        const C: u32 = 42;
15389
15390
15391        fn main() {
15392            println!("hello");
15393
15394            println!("world");
15395        }
15396    "#
15397    .unindent();
15398    executor.run_until_parked();
15399    cx.set_state(
15400        &r#"
15401        use some::mod1;
15402        use some::mod2;
15403
15404        ˇconst B: u32 = 42;
15405        const C: u32 = 42;
15406
15407
15408        fn main() {
15409            println!("hello");
15410
15411            println!("world");
15412        }
15413        "#
15414        .unindent(),
15415    );
15416
15417    cx.set_head_text(&diff_base);
15418    executor.run_until_parked();
15419
15420    cx.update_editor(|editor, window, cx| {
15421        editor.expand_all_diff_hunks(&ExpandAllDiffHunks, window, cx);
15422    });
15423    executor.run_until_parked();
15424
15425    cx.assert_state_with_diff(
15426        r#"
15427        use some::mod1;
15428        use some::mod2;
15429
15430      - const A: u32 = 42;
15431        ˇconst B: u32 = 42;
15432        const C: u32 = 42;
15433
15434
15435        fn main() {
15436            println!("hello");
15437
15438            println!("world");
15439        }
15440      "#
15441        .unindent(),
15442    );
15443
15444    cx.update_editor(|editor, window, cx| {
15445        editor.delete_line(&DeleteLine, window, cx);
15446    });
15447    executor.run_until_parked();
15448    cx.assert_state_with_diff(
15449        r#"
15450        use some::mod1;
15451        use some::mod2;
15452
15453      - const A: u32 = 42;
15454      - const B: u32 = 42;
15455        ˇconst C: u32 = 42;
15456
15457
15458        fn main() {
15459            println!("hello");
15460
15461            println!("world");
15462        }
15463      "#
15464        .unindent(),
15465    );
15466
15467    cx.update_editor(|editor, window, cx| {
15468        editor.delete_line(&DeleteLine, window, cx);
15469    });
15470    executor.run_until_parked();
15471    cx.assert_state_with_diff(
15472        r#"
15473        use some::mod1;
15474        use some::mod2;
15475
15476      - const A: u32 = 42;
15477      - const B: u32 = 42;
15478      - const C: u32 = 42;
15479        ˇ
15480
15481        fn main() {
15482            println!("hello");
15483
15484            println!("world");
15485        }
15486      "#
15487        .unindent(),
15488    );
15489
15490    cx.update_editor(|editor, window, cx| {
15491        editor.handle_input("replacement", window, cx);
15492    });
15493    executor.run_until_parked();
15494    cx.assert_state_with_diff(
15495        r#"
15496        use some::mod1;
15497        use some::mod2;
15498
15499      - const A: u32 = 42;
15500      - const B: u32 = 42;
15501      - const C: u32 = 42;
15502      -
15503      + replacementˇ
15504
15505        fn main() {
15506            println!("hello");
15507
15508            println!("world");
15509        }
15510      "#
15511        .unindent(),
15512    );
15513}
15514
15515#[gpui::test]
15516async fn test_backspace_after_deletion_hunk(executor: BackgroundExecutor, cx: &mut TestAppContext) {
15517    init_test(cx, |_| {});
15518
15519    let mut cx = EditorTestContext::new(cx).await;
15520
15521    let base_text = r#"
15522        one
15523        two
15524        three
15525        four
15526        five
15527    "#
15528    .unindent();
15529    executor.run_until_parked();
15530    cx.set_state(
15531        &r#"
15532        one
15533        two
15534        fˇour
15535        five
15536        "#
15537        .unindent(),
15538    );
15539
15540    cx.set_head_text(&base_text);
15541    executor.run_until_parked();
15542
15543    cx.update_editor(|editor, window, cx| {
15544        editor.expand_all_diff_hunks(&ExpandAllDiffHunks, window, cx);
15545    });
15546    executor.run_until_parked();
15547
15548    cx.assert_state_with_diff(
15549        r#"
15550          one
15551          two
15552        - three
15553          fˇour
15554          five
15555        "#
15556        .unindent(),
15557    );
15558
15559    cx.update_editor(|editor, window, cx| {
15560        editor.backspace(&Backspace, window, cx);
15561        editor.backspace(&Backspace, window, cx);
15562    });
15563    executor.run_until_parked();
15564    cx.assert_state_with_diff(
15565        r#"
15566          one
15567          two
15568        - threeˇ
15569        - four
15570        + our
15571          five
15572        "#
15573        .unindent(),
15574    );
15575}
15576
15577#[gpui::test]
15578async fn test_edit_after_expanded_modification_hunk(
15579    executor: BackgroundExecutor,
15580    cx: &mut TestAppContext,
15581) {
15582    init_test(cx, |_| {});
15583
15584    let mut cx = EditorTestContext::new(cx).await;
15585
15586    let diff_base = r#"
15587        use some::mod1;
15588        use some::mod2;
15589
15590        const A: u32 = 42;
15591        const B: u32 = 42;
15592        const C: u32 = 42;
15593        const D: u32 = 42;
15594
15595
15596        fn main() {
15597            println!("hello");
15598
15599            println!("world");
15600        }"#
15601    .unindent();
15602
15603    cx.set_state(
15604        &r#"
15605        use some::mod1;
15606        use some::mod2;
15607
15608        const A: u32 = 42;
15609        const B: u32 = 42;
15610        const C: u32 = 43ˇ
15611        const D: u32 = 42;
15612
15613
15614        fn main() {
15615            println!("hello");
15616
15617            println!("world");
15618        }"#
15619        .unindent(),
15620    );
15621
15622    cx.set_head_text(&diff_base);
15623    executor.run_until_parked();
15624    cx.update_editor(|editor, window, cx| {
15625        editor.expand_all_diff_hunks(&ExpandAllDiffHunks, window, cx);
15626    });
15627    executor.run_until_parked();
15628
15629    cx.assert_state_with_diff(
15630        r#"
15631        use some::mod1;
15632        use some::mod2;
15633
15634        const A: u32 = 42;
15635        const B: u32 = 42;
15636      - const C: u32 = 42;
15637      + const C: u32 = 43ˇ
15638        const D: u32 = 42;
15639
15640
15641        fn main() {
15642            println!("hello");
15643
15644            println!("world");
15645        }"#
15646        .unindent(),
15647    );
15648
15649    cx.update_editor(|editor, window, cx| {
15650        editor.handle_input("\nnew_line\n", window, cx);
15651    });
15652    executor.run_until_parked();
15653
15654    cx.assert_state_with_diff(
15655        r#"
15656        use some::mod1;
15657        use some::mod2;
15658
15659        const A: u32 = 42;
15660        const B: u32 = 42;
15661      - const C: u32 = 42;
15662      + const C: u32 = 43
15663      + new_line
15664      + ˇ
15665        const D: u32 = 42;
15666
15667
15668        fn main() {
15669            println!("hello");
15670
15671            println!("world");
15672        }"#
15673        .unindent(),
15674    );
15675}
15676
15677#[gpui::test]
15678async fn test_stage_and_unstage_added_file_hunk(
15679    executor: BackgroundExecutor,
15680    cx: &mut TestAppContext,
15681) {
15682    init_test(cx, |_| {});
15683
15684    let mut cx = EditorTestContext::new(cx).await;
15685    cx.update_editor(|editor, _, cx| {
15686        editor.set_expand_all_diff_hunks(cx);
15687    });
15688
15689    let working_copy = r#"
15690            ˇfn main() {
15691                println!("hello, world!");
15692            }
15693        "#
15694    .unindent();
15695
15696    cx.set_state(&working_copy);
15697    executor.run_until_parked();
15698
15699    cx.assert_state_with_diff(
15700        r#"
15701            + ˇfn main() {
15702            +     println!("hello, world!");
15703            + }
15704        "#
15705        .unindent(),
15706    );
15707    cx.assert_index_text(None);
15708
15709    cx.update_editor(|editor, window, cx| {
15710        editor.toggle_staged_selected_diff_hunks(&Default::default(), window, cx);
15711    });
15712    executor.run_until_parked();
15713    cx.assert_index_text(Some(&working_copy.replace("ˇ", "")));
15714    cx.assert_state_with_diff(
15715        r#"
15716            + ˇfn main() {
15717            +     println!("hello, world!");
15718            + }
15719        "#
15720        .unindent(),
15721    );
15722
15723    cx.update_editor(|editor, window, cx| {
15724        editor.toggle_staged_selected_diff_hunks(&Default::default(), window, cx);
15725    });
15726    executor.run_until_parked();
15727    cx.assert_index_text(None);
15728}
15729
15730async fn setup_indent_guides_editor(
15731    text: &str,
15732    cx: &mut TestAppContext,
15733) -> (BufferId, EditorTestContext) {
15734    init_test(cx, |_| {});
15735
15736    let mut cx = EditorTestContext::new(cx).await;
15737
15738    let buffer_id = cx.update_editor(|editor, window, cx| {
15739        editor.set_text(text, window, cx);
15740        let buffer_ids = editor.buffer().read(cx).excerpt_buffer_ids();
15741
15742        buffer_ids[0]
15743    });
15744
15745    (buffer_id, cx)
15746}
15747
15748fn assert_indent_guides(
15749    range: Range<u32>,
15750    expected: Vec<IndentGuide>,
15751    active_indices: Option<Vec<usize>>,
15752    cx: &mut EditorTestContext,
15753) {
15754    let indent_guides = cx.update_editor(|editor, window, cx| {
15755        let snapshot = editor.snapshot(window, cx).display_snapshot;
15756        let mut indent_guides: Vec<_> = crate::indent_guides::indent_guides_in_range(
15757            editor,
15758            MultiBufferRow(range.start)..MultiBufferRow(range.end),
15759            true,
15760            &snapshot,
15761            cx,
15762        );
15763
15764        indent_guides.sort_by(|a, b| {
15765            a.depth.cmp(&b.depth).then(
15766                a.start_row
15767                    .cmp(&b.start_row)
15768                    .then(a.end_row.cmp(&b.end_row)),
15769            )
15770        });
15771        indent_guides
15772    });
15773
15774    if let Some(expected) = active_indices {
15775        let active_indices = cx.update_editor(|editor, window, cx| {
15776            let snapshot = editor.snapshot(window, cx).display_snapshot;
15777            editor.find_active_indent_guide_indices(&indent_guides, &snapshot, window, cx)
15778        });
15779
15780        assert_eq!(
15781            active_indices.unwrap().into_iter().collect::<Vec<_>>(),
15782            expected,
15783            "Active indent guide indices do not match"
15784        );
15785    }
15786
15787    assert_eq!(indent_guides, expected, "Indent guides do not match");
15788}
15789
15790fn indent_guide(buffer_id: BufferId, start_row: u32, end_row: u32, depth: u32) -> IndentGuide {
15791    IndentGuide {
15792        buffer_id,
15793        start_row: MultiBufferRow(start_row),
15794        end_row: MultiBufferRow(end_row),
15795        depth,
15796        tab_size: 4,
15797        settings: IndentGuideSettings {
15798            enabled: true,
15799            line_width: 1,
15800            active_line_width: 1,
15801            ..Default::default()
15802        },
15803    }
15804}
15805
15806#[gpui::test]
15807async fn test_indent_guide_single_line(cx: &mut TestAppContext) {
15808    let (buffer_id, mut cx) = setup_indent_guides_editor(
15809        &"
15810    fn main() {
15811        let a = 1;
15812    }"
15813        .unindent(),
15814        cx,
15815    )
15816    .await;
15817
15818    assert_indent_guides(0..3, vec![indent_guide(buffer_id, 1, 1, 0)], None, &mut cx);
15819}
15820
15821#[gpui::test]
15822async fn test_indent_guide_simple_block(cx: &mut TestAppContext) {
15823    let (buffer_id, mut cx) = setup_indent_guides_editor(
15824        &"
15825    fn main() {
15826        let a = 1;
15827        let b = 2;
15828    }"
15829        .unindent(),
15830        cx,
15831    )
15832    .await;
15833
15834    assert_indent_guides(0..4, vec![indent_guide(buffer_id, 1, 2, 0)], None, &mut cx);
15835}
15836
15837#[gpui::test]
15838async fn test_indent_guide_nested(cx: &mut TestAppContext) {
15839    let (buffer_id, mut cx) = setup_indent_guides_editor(
15840        &"
15841    fn main() {
15842        let a = 1;
15843        if a == 3 {
15844            let b = 2;
15845        } else {
15846            let c = 3;
15847        }
15848    }"
15849        .unindent(),
15850        cx,
15851    )
15852    .await;
15853
15854    assert_indent_guides(
15855        0..8,
15856        vec![
15857            indent_guide(buffer_id, 1, 6, 0),
15858            indent_guide(buffer_id, 3, 3, 1),
15859            indent_guide(buffer_id, 5, 5, 1),
15860        ],
15861        None,
15862        &mut cx,
15863    );
15864}
15865
15866#[gpui::test]
15867async fn test_indent_guide_tab(cx: &mut TestAppContext) {
15868    let (buffer_id, mut cx) = setup_indent_guides_editor(
15869        &"
15870    fn main() {
15871        let a = 1;
15872            let b = 2;
15873        let c = 3;
15874    }"
15875        .unindent(),
15876        cx,
15877    )
15878    .await;
15879
15880    assert_indent_guides(
15881        0..5,
15882        vec![
15883            indent_guide(buffer_id, 1, 3, 0),
15884            indent_guide(buffer_id, 2, 2, 1),
15885        ],
15886        None,
15887        &mut cx,
15888    );
15889}
15890
15891#[gpui::test]
15892async fn test_indent_guide_continues_on_empty_line(cx: &mut TestAppContext) {
15893    let (buffer_id, mut cx) = setup_indent_guides_editor(
15894        &"
15895        fn main() {
15896            let a = 1;
15897
15898            let c = 3;
15899        }"
15900        .unindent(),
15901        cx,
15902    )
15903    .await;
15904
15905    assert_indent_guides(0..5, vec![indent_guide(buffer_id, 1, 3, 0)], None, &mut cx);
15906}
15907
15908#[gpui::test]
15909async fn test_indent_guide_complex(cx: &mut TestAppContext) {
15910    let (buffer_id, mut cx) = setup_indent_guides_editor(
15911        &"
15912        fn main() {
15913            let a = 1;
15914
15915            let c = 3;
15916
15917            if a == 3 {
15918                let b = 2;
15919            } else {
15920                let c = 3;
15921            }
15922        }"
15923        .unindent(),
15924        cx,
15925    )
15926    .await;
15927
15928    assert_indent_guides(
15929        0..11,
15930        vec![
15931            indent_guide(buffer_id, 1, 9, 0),
15932            indent_guide(buffer_id, 6, 6, 1),
15933            indent_guide(buffer_id, 8, 8, 1),
15934        ],
15935        None,
15936        &mut cx,
15937    );
15938}
15939
15940#[gpui::test]
15941async fn test_indent_guide_starts_off_screen(cx: &mut TestAppContext) {
15942    let (buffer_id, mut cx) = setup_indent_guides_editor(
15943        &"
15944        fn main() {
15945            let a = 1;
15946
15947            let c = 3;
15948
15949            if a == 3 {
15950                let b = 2;
15951            } else {
15952                let c = 3;
15953            }
15954        }"
15955        .unindent(),
15956        cx,
15957    )
15958    .await;
15959
15960    assert_indent_guides(
15961        1..11,
15962        vec![
15963            indent_guide(buffer_id, 1, 9, 0),
15964            indent_guide(buffer_id, 6, 6, 1),
15965            indent_guide(buffer_id, 8, 8, 1),
15966        ],
15967        None,
15968        &mut cx,
15969    );
15970}
15971
15972#[gpui::test]
15973async fn test_indent_guide_ends_off_screen(cx: &mut TestAppContext) {
15974    let (buffer_id, mut cx) = setup_indent_guides_editor(
15975        &"
15976        fn main() {
15977            let a = 1;
15978
15979            let c = 3;
15980
15981            if a == 3 {
15982                let b = 2;
15983            } else {
15984                let c = 3;
15985            }
15986        }"
15987        .unindent(),
15988        cx,
15989    )
15990    .await;
15991
15992    assert_indent_guides(
15993        1..10,
15994        vec![
15995            indent_guide(buffer_id, 1, 9, 0),
15996            indent_guide(buffer_id, 6, 6, 1),
15997            indent_guide(buffer_id, 8, 8, 1),
15998        ],
15999        None,
16000        &mut cx,
16001    );
16002}
16003
16004#[gpui::test]
16005async fn test_indent_guide_without_brackets(cx: &mut TestAppContext) {
16006    let (buffer_id, mut cx) = setup_indent_guides_editor(
16007        &"
16008        block1
16009            block2
16010                block3
16011                    block4
16012            block2
16013        block1
16014        block1"
16015            .unindent(),
16016        cx,
16017    )
16018    .await;
16019
16020    assert_indent_guides(
16021        1..10,
16022        vec![
16023            indent_guide(buffer_id, 1, 4, 0),
16024            indent_guide(buffer_id, 2, 3, 1),
16025            indent_guide(buffer_id, 3, 3, 2),
16026        ],
16027        None,
16028        &mut cx,
16029    );
16030}
16031
16032#[gpui::test]
16033async fn test_indent_guide_ends_before_empty_line(cx: &mut TestAppContext) {
16034    let (buffer_id, mut cx) = setup_indent_guides_editor(
16035        &"
16036        block1
16037            block2
16038                block3
16039
16040        block1
16041        block1"
16042            .unindent(),
16043        cx,
16044    )
16045    .await;
16046
16047    assert_indent_guides(
16048        0..6,
16049        vec![
16050            indent_guide(buffer_id, 1, 2, 0),
16051            indent_guide(buffer_id, 2, 2, 1),
16052        ],
16053        None,
16054        &mut cx,
16055    );
16056}
16057
16058#[gpui::test]
16059async fn test_indent_guide_continuing_off_screen(cx: &mut TestAppContext) {
16060    let (buffer_id, mut cx) = setup_indent_guides_editor(
16061        &"
16062        block1
16063
16064
16065
16066            block2
16067        "
16068        .unindent(),
16069        cx,
16070    )
16071    .await;
16072
16073    assert_indent_guides(0..1, vec![indent_guide(buffer_id, 1, 1, 0)], None, &mut cx);
16074}
16075
16076#[gpui::test]
16077async fn test_indent_guide_tabs(cx: &mut TestAppContext) {
16078    let (buffer_id, mut cx) = setup_indent_guides_editor(
16079        &"
16080        def a:
16081        \tb = 3
16082        \tif True:
16083        \t\tc = 4
16084        \t\td = 5
16085        \tprint(b)
16086        "
16087        .unindent(),
16088        cx,
16089    )
16090    .await;
16091
16092    assert_indent_guides(
16093        0..6,
16094        vec![
16095            indent_guide(buffer_id, 1, 6, 0),
16096            indent_guide(buffer_id, 3, 4, 1),
16097        ],
16098        None,
16099        &mut cx,
16100    );
16101}
16102
16103#[gpui::test]
16104async fn test_active_indent_guide_single_line(cx: &mut TestAppContext) {
16105    let (buffer_id, mut cx) = setup_indent_guides_editor(
16106        &"
16107    fn main() {
16108        let a = 1;
16109    }"
16110        .unindent(),
16111        cx,
16112    )
16113    .await;
16114
16115    cx.update_editor(|editor, window, cx| {
16116        editor.change_selections(None, window, cx, |s| {
16117            s.select_ranges([Point::new(1, 0)..Point::new(1, 0)])
16118        });
16119    });
16120
16121    assert_indent_guides(
16122        0..3,
16123        vec![indent_guide(buffer_id, 1, 1, 0)],
16124        Some(vec![0]),
16125        &mut cx,
16126    );
16127}
16128
16129#[gpui::test]
16130async fn test_active_indent_guide_respect_indented_range(cx: &mut TestAppContext) {
16131    let (buffer_id, mut cx) = setup_indent_guides_editor(
16132        &"
16133    fn main() {
16134        if 1 == 2 {
16135            let a = 1;
16136        }
16137    }"
16138        .unindent(),
16139        cx,
16140    )
16141    .await;
16142
16143    cx.update_editor(|editor, window, cx| {
16144        editor.change_selections(None, window, cx, |s| {
16145            s.select_ranges([Point::new(1, 0)..Point::new(1, 0)])
16146        });
16147    });
16148
16149    assert_indent_guides(
16150        0..4,
16151        vec![
16152            indent_guide(buffer_id, 1, 3, 0),
16153            indent_guide(buffer_id, 2, 2, 1),
16154        ],
16155        Some(vec![1]),
16156        &mut cx,
16157    );
16158
16159    cx.update_editor(|editor, window, cx| {
16160        editor.change_selections(None, window, cx, |s| {
16161            s.select_ranges([Point::new(2, 0)..Point::new(2, 0)])
16162        });
16163    });
16164
16165    assert_indent_guides(
16166        0..4,
16167        vec![
16168            indent_guide(buffer_id, 1, 3, 0),
16169            indent_guide(buffer_id, 2, 2, 1),
16170        ],
16171        Some(vec![1]),
16172        &mut cx,
16173    );
16174
16175    cx.update_editor(|editor, window, cx| {
16176        editor.change_selections(None, window, cx, |s| {
16177            s.select_ranges([Point::new(3, 0)..Point::new(3, 0)])
16178        });
16179    });
16180
16181    assert_indent_guides(
16182        0..4,
16183        vec![
16184            indent_guide(buffer_id, 1, 3, 0),
16185            indent_guide(buffer_id, 2, 2, 1),
16186        ],
16187        Some(vec![0]),
16188        &mut cx,
16189    );
16190}
16191
16192#[gpui::test]
16193async fn test_active_indent_guide_empty_line(cx: &mut TestAppContext) {
16194    let (buffer_id, mut cx) = setup_indent_guides_editor(
16195        &"
16196    fn main() {
16197        let a = 1;
16198
16199        let b = 2;
16200    }"
16201        .unindent(),
16202        cx,
16203    )
16204    .await;
16205
16206    cx.update_editor(|editor, window, cx| {
16207        editor.change_selections(None, window, cx, |s| {
16208            s.select_ranges([Point::new(2, 0)..Point::new(2, 0)])
16209        });
16210    });
16211
16212    assert_indent_guides(
16213        0..5,
16214        vec![indent_guide(buffer_id, 1, 3, 0)],
16215        Some(vec![0]),
16216        &mut cx,
16217    );
16218}
16219
16220#[gpui::test]
16221async fn test_active_indent_guide_non_matching_indent(cx: &mut TestAppContext) {
16222    let (buffer_id, mut cx) = setup_indent_guides_editor(
16223        &"
16224    def m:
16225        a = 1
16226        pass"
16227            .unindent(),
16228        cx,
16229    )
16230    .await;
16231
16232    cx.update_editor(|editor, window, cx| {
16233        editor.change_selections(None, window, cx, |s| {
16234            s.select_ranges([Point::new(1, 0)..Point::new(1, 0)])
16235        });
16236    });
16237
16238    assert_indent_guides(
16239        0..3,
16240        vec![indent_guide(buffer_id, 1, 2, 0)],
16241        Some(vec![0]),
16242        &mut cx,
16243    );
16244}
16245
16246#[gpui::test]
16247async fn test_indent_guide_with_expanded_diff_hunks(cx: &mut TestAppContext) {
16248    init_test(cx, |_| {});
16249    let mut cx = EditorTestContext::new(cx).await;
16250    let text = indoc! {
16251        "
16252        impl A {
16253            fn b() {
16254                0;
16255                3;
16256                5;
16257                6;
16258                7;
16259            }
16260        }
16261        "
16262    };
16263    let base_text = indoc! {
16264        "
16265        impl A {
16266            fn b() {
16267                0;
16268                1;
16269                2;
16270                3;
16271                4;
16272            }
16273            fn c() {
16274                5;
16275                6;
16276                7;
16277            }
16278        }
16279        "
16280    };
16281
16282    cx.update_editor(|editor, window, cx| {
16283        editor.set_text(text, window, cx);
16284
16285        editor.buffer().update(cx, |multibuffer, cx| {
16286            let buffer = multibuffer.as_singleton().unwrap();
16287            let diff = cx.new(|cx| BufferDiff::new_with_base_text(base_text, &buffer, cx));
16288
16289            multibuffer.set_all_diff_hunks_expanded(cx);
16290            multibuffer.add_diff(diff, cx);
16291
16292            buffer.read(cx).remote_id()
16293        })
16294    });
16295    cx.run_until_parked();
16296
16297    cx.assert_state_with_diff(
16298        indoc! { "
16299          impl A {
16300              fn b() {
16301                  0;
16302        -         1;
16303        -         2;
16304                  3;
16305        -         4;
16306        -     }
16307        -     fn c() {
16308                  5;
16309                  6;
16310                  7;
16311              }
16312          }
16313          ˇ"
16314        }
16315        .to_string(),
16316    );
16317
16318    let mut actual_guides = cx.update_editor(|editor, window, cx| {
16319        editor
16320            .snapshot(window, cx)
16321            .buffer_snapshot
16322            .indent_guides_in_range(Anchor::min()..Anchor::max(), false, cx)
16323            .map(|guide| (guide.start_row..=guide.end_row, guide.depth))
16324            .collect::<Vec<_>>()
16325    });
16326    actual_guides.sort_by_key(|item| (*item.0.start(), item.1));
16327    assert_eq!(
16328        actual_guides,
16329        vec![
16330            (MultiBufferRow(1)..=MultiBufferRow(12), 0),
16331            (MultiBufferRow(2)..=MultiBufferRow(6), 1),
16332            (MultiBufferRow(9)..=MultiBufferRow(11), 1),
16333        ]
16334    );
16335}
16336
16337#[gpui::test]
16338async fn test_adjacent_diff_hunks(executor: BackgroundExecutor, cx: &mut TestAppContext) {
16339    init_test(cx, |_| {});
16340    let mut cx = EditorTestContext::new(cx).await;
16341
16342    let diff_base = r#"
16343        a
16344        b
16345        c
16346        "#
16347    .unindent();
16348
16349    cx.set_state(
16350        &r#"
16351        ˇA
16352        b
16353        C
16354        "#
16355        .unindent(),
16356    );
16357    cx.set_head_text(&diff_base);
16358    cx.update_editor(|editor, window, cx| {
16359        editor.expand_all_diff_hunks(&ExpandAllDiffHunks, window, cx);
16360    });
16361    executor.run_until_parked();
16362
16363    let both_hunks_expanded = r#"
16364        - a
16365        + ˇA
16366          b
16367        - c
16368        + C
16369        "#
16370    .unindent();
16371
16372    cx.assert_state_with_diff(both_hunks_expanded.clone());
16373
16374    let hunk_ranges = cx.update_editor(|editor, window, cx| {
16375        let snapshot = editor.snapshot(window, cx);
16376        let hunks = editor
16377            .diff_hunks_in_ranges(&[Anchor::min()..Anchor::max()], &snapshot.buffer_snapshot)
16378            .collect::<Vec<_>>();
16379        let excerpt_id = editor.buffer.read(cx).excerpt_ids()[0];
16380        let buffer_id = hunks[0].buffer_id;
16381        hunks
16382            .into_iter()
16383            .map(|hunk| Anchor::range_in_buffer(excerpt_id, buffer_id, hunk.buffer_range.clone()))
16384            .collect::<Vec<_>>()
16385    });
16386    assert_eq!(hunk_ranges.len(), 2);
16387
16388    cx.update_editor(|editor, _, cx| {
16389        editor.toggle_single_diff_hunk(hunk_ranges[0].clone(), cx);
16390    });
16391    executor.run_until_parked();
16392
16393    let second_hunk_expanded = r#"
16394          ˇA
16395          b
16396        - c
16397        + C
16398        "#
16399    .unindent();
16400
16401    cx.assert_state_with_diff(second_hunk_expanded);
16402
16403    cx.update_editor(|editor, _, cx| {
16404        editor.toggle_single_diff_hunk(hunk_ranges[0].clone(), cx);
16405    });
16406    executor.run_until_parked();
16407
16408    cx.assert_state_with_diff(both_hunks_expanded.clone());
16409
16410    cx.update_editor(|editor, _, cx| {
16411        editor.toggle_single_diff_hunk(hunk_ranges[1].clone(), cx);
16412    });
16413    executor.run_until_parked();
16414
16415    let first_hunk_expanded = r#"
16416        - a
16417        + ˇA
16418          b
16419          C
16420        "#
16421    .unindent();
16422
16423    cx.assert_state_with_diff(first_hunk_expanded);
16424
16425    cx.update_editor(|editor, _, cx| {
16426        editor.toggle_single_diff_hunk(hunk_ranges[1].clone(), cx);
16427    });
16428    executor.run_until_parked();
16429
16430    cx.assert_state_with_diff(both_hunks_expanded);
16431
16432    cx.set_state(
16433        &r#"
16434        ˇA
16435        b
16436        "#
16437        .unindent(),
16438    );
16439    cx.run_until_parked();
16440
16441    // TODO this cursor position seems bad
16442    cx.assert_state_with_diff(
16443        r#"
16444        - ˇa
16445        + A
16446          b
16447        "#
16448        .unindent(),
16449    );
16450
16451    cx.update_editor(|editor, window, cx| {
16452        editor.expand_all_diff_hunks(&ExpandAllDiffHunks, window, cx);
16453    });
16454
16455    cx.assert_state_with_diff(
16456        r#"
16457            - ˇa
16458            + A
16459              b
16460            - c
16461            "#
16462        .unindent(),
16463    );
16464
16465    let hunk_ranges = cx.update_editor(|editor, window, cx| {
16466        let snapshot = editor.snapshot(window, cx);
16467        let hunks = editor
16468            .diff_hunks_in_ranges(&[Anchor::min()..Anchor::max()], &snapshot.buffer_snapshot)
16469            .collect::<Vec<_>>();
16470        let excerpt_id = editor.buffer.read(cx).excerpt_ids()[0];
16471        let buffer_id = hunks[0].buffer_id;
16472        hunks
16473            .into_iter()
16474            .map(|hunk| Anchor::range_in_buffer(excerpt_id, buffer_id, hunk.buffer_range.clone()))
16475            .collect::<Vec<_>>()
16476    });
16477    assert_eq!(hunk_ranges.len(), 2);
16478
16479    cx.update_editor(|editor, _, cx| {
16480        editor.toggle_single_diff_hunk(hunk_ranges[1].clone(), cx);
16481    });
16482    executor.run_until_parked();
16483
16484    cx.assert_state_with_diff(
16485        r#"
16486        - ˇa
16487        + A
16488          b
16489        "#
16490        .unindent(),
16491    );
16492}
16493
16494#[gpui::test]
16495async fn test_toggle_deletion_hunk_at_start_of_file(
16496    executor: BackgroundExecutor,
16497    cx: &mut TestAppContext,
16498) {
16499    init_test(cx, |_| {});
16500    let mut cx = EditorTestContext::new(cx).await;
16501
16502    let diff_base = r#"
16503        a
16504        b
16505        c
16506        "#
16507    .unindent();
16508
16509    cx.set_state(
16510        &r#"
16511        ˇb
16512        c
16513        "#
16514        .unindent(),
16515    );
16516    cx.set_head_text(&diff_base);
16517    cx.update_editor(|editor, window, cx| {
16518        editor.expand_all_diff_hunks(&ExpandAllDiffHunks, window, cx);
16519    });
16520    executor.run_until_parked();
16521
16522    let hunk_expanded = r#"
16523        - a
16524          ˇb
16525          c
16526        "#
16527    .unindent();
16528
16529    cx.assert_state_with_diff(hunk_expanded.clone());
16530
16531    let hunk_ranges = cx.update_editor(|editor, window, cx| {
16532        let snapshot = editor.snapshot(window, cx);
16533        let hunks = editor
16534            .diff_hunks_in_ranges(&[Anchor::min()..Anchor::max()], &snapshot.buffer_snapshot)
16535            .collect::<Vec<_>>();
16536        let excerpt_id = editor.buffer.read(cx).excerpt_ids()[0];
16537        let buffer_id = hunks[0].buffer_id;
16538        hunks
16539            .into_iter()
16540            .map(|hunk| Anchor::range_in_buffer(excerpt_id, buffer_id, hunk.buffer_range.clone()))
16541            .collect::<Vec<_>>()
16542    });
16543    assert_eq!(hunk_ranges.len(), 1);
16544
16545    cx.update_editor(|editor, _, cx| {
16546        editor.toggle_single_diff_hunk(hunk_ranges[0].clone(), cx);
16547    });
16548    executor.run_until_parked();
16549
16550    let hunk_collapsed = r#"
16551          ˇb
16552          c
16553        "#
16554    .unindent();
16555
16556    cx.assert_state_with_diff(hunk_collapsed);
16557
16558    cx.update_editor(|editor, _, cx| {
16559        editor.toggle_single_diff_hunk(hunk_ranges[0].clone(), cx);
16560    });
16561    executor.run_until_parked();
16562
16563    cx.assert_state_with_diff(hunk_expanded.clone());
16564}
16565
16566#[gpui::test]
16567async fn test_display_diff_hunks(cx: &mut TestAppContext) {
16568    init_test(cx, |_| {});
16569
16570    let fs = FakeFs::new(cx.executor());
16571    fs.insert_tree(
16572        path!("/test"),
16573        json!({
16574            ".git": {},
16575            "file-1": "ONE\n",
16576            "file-2": "TWO\n",
16577            "file-3": "THREE\n",
16578        }),
16579    )
16580    .await;
16581
16582    fs.set_head_for_repo(
16583        path!("/test/.git").as_ref(),
16584        &[
16585            ("file-1".into(), "one\n".into()),
16586            ("file-2".into(), "two\n".into()),
16587            ("file-3".into(), "three\n".into()),
16588        ],
16589    );
16590
16591    let project = Project::test(fs, [path!("/test").as_ref()], cx).await;
16592    let mut buffers = vec![];
16593    for i in 1..=3 {
16594        let buffer = project
16595            .update(cx, |project, cx| {
16596                let path = format!(path!("/test/file-{}"), i);
16597                project.open_local_buffer(path, cx)
16598            })
16599            .await
16600            .unwrap();
16601        buffers.push(buffer);
16602    }
16603
16604    let multibuffer = cx.new(|cx| {
16605        let mut multibuffer = MultiBuffer::new(Capability::ReadWrite);
16606        multibuffer.set_all_diff_hunks_expanded(cx);
16607        for buffer in &buffers {
16608            let snapshot = buffer.read(cx).snapshot();
16609            multibuffer.set_excerpts_for_path(
16610                PathKey::namespaced(0, buffer.read(cx).file().unwrap().path().clone()),
16611                buffer.clone(),
16612                vec![text::Anchor::MIN.to_point(&snapshot)..text::Anchor::MAX.to_point(&snapshot)],
16613                DEFAULT_MULTIBUFFER_CONTEXT,
16614                cx,
16615            );
16616        }
16617        multibuffer
16618    });
16619
16620    let editor = cx.add_window(|window, cx| {
16621        Editor::new(EditorMode::full(), multibuffer, Some(project), window, cx)
16622    });
16623    cx.run_until_parked();
16624
16625    let snapshot = editor
16626        .update(cx, |editor, window, cx| editor.snapshot(window, cx))
16627        .unwrap();
16628    let hunks = snapshot
16629        .display_diff_hunks_for_rows(DisplayRow(0)..DisplayRow(u32::MAX), &Default::default())
16630        .map(|hunk| match hunk {
16631            DisplayDiffHunk::Unfolded {
16632                display_row_range, ..
16633            } => display_row_range,
16634            DisplayDiffHunk::Folded { .. } => unreachable!(),
16635        })
16636        .collect::<Vec<_>>();
16637    assert_eq!(
16638        hunks,
16639        [
16640            DisplayRow(2)..DisplayRow(4),
16641            DisplayRow(7)..DisplayRow(9),
16642            DisplayRow(12)..DisplayRow(14),
16643        ]
16644    );
16645}
16646
16647#[gpui::test]
16648async fn test_partially_staged_hunk(cx: &mut TestAppContext) {
16649    init_test(cx, |_| {});
16650
16651    let mut cx = EditorTestContext::new(cx).await;
16652    cx.set_head_text(indoc! { "
16653        one
16654        two
16655        three
16656        four
16657        five
16658        "
16659    });
16660    cx.set_index_text(indoc! { "
16661        one
16662        two
16663        three
16664        four
16665        five
16666        "
16667    });
16668    cx.set_state(indoc! {"
16669        one
16670        TWO
16671        ˇTHREE
16672        FOUR
16673        five
16674    "});
16675    cx.run_until_parked();
16676    cx.update_editor(|editor, window, cx| {
16677        editor.toggle_staged_selected_diff_hunks(&Default::default(), window, cx);
16678    });
16679    cx.run_until_parked();
16680    cx.assert_index_text(Some(indoc! {"
16681        one
16682        TWO
16683        THREE
16684        FOUR
16685        five
16686    "}));
16687    cx.set_state(indoc! { "
16688        one
16689        TWO
16690        ˇTHREE-HUNDRED
16691        FOUR
16692        five
16693    "});
16694    cx.run_until_parked();
16695    cx.update_editor(|editor, window, cx| {
16696        let snapshot = editor.snapshot(window, cx);
16697        let hunks = editor
16698            .diff_hunks_in_ranges(&[Anchor::min()..Anchor::max()], &snapshot.buffer_snapshot)
16699            .collect::<Vec<_>>();
16700        assert_eq!(hunks.len(), 1);
16701        assert_eq!(
16702            hunks[0].status(),
16703            DiffHunkStatus {
16704                kind: DiffHunkStatusKind::Modified,
16705                secondary: DiffHunkSecondaryStatus::OverlapsWithSecondaryHunk
16706            }
16707        );
16708
16709        editor.toggle_staged_selected_diff_hunks(&Default::default(), window, cx);
16710    });
16711    cx.run_until_parked();
16712    cx.assert_index_text(Some(indoc! {"
16713        one
16714        TWO
16715        THREE-HUNDRED
16716        FOUR
16717        five
16718    "}));
16719}
16720
16721#[gpui::test]
16722fn test_crease_insertion_and_rendering(cx: &mut TestAppContext) {
16723    init_test(cx, |_| {});
16724
16725    let editor = cx.add_window(|window, cx| {
16726        let buffer = MultiBuffer::build_simple("aaaaaa\nbbbbbb\ncccccc\nddddddd\n", cx);
16727        build_editor(buffer, window, cx)
16728    });
16729
16730    let render_args = Arc::new(Mutex::new(None));
16731    let snapshot = editor
16732        .update(cx, |editor, window, cx| {
16733            let snapshot = editor.buffer().read(cx).snapshot(cx);
16734            let range =
16735                snapshot.anchor_before(Point::new(1, 0))..snapshot.anchor_after(Point::new(2, 6));
16736
16737            struct RenderArgs {
16738                row: MultiBufferRow,
16739                folded: bool,
16740                callback: Arc<dyn Fn(bool, &mut Window, &mut App) + Send + Sync>,
16741            }
16742
16743            let crease = Crease::inline(
16744                range,
16745                FoldPlaceholder::test(),
16746                {
16747                    let toggle_callback = render_args.clone();
16748                    move |row, folded, callback, _window, _cx| {
16749                        *toggle_callback.lock() = Some(RenderArgs {
16750                            row,
16751                            folded,
16752                            callback,
16753                        });
16754                        div()
16755                    }
16756                },
16757                |_row, _folded, _window, _cx| div(),
16758            );
16759
16760            editor.insert_creases(Some(crease), cx);
16761            let snapshot = editor.snapshot(window, cx);
16762            let _div = snapshot.render_crease_toggle(
16763                MultiBufferRow(1),
16764                false,
16765                cx.entity().clone(),
16766                window,
16767                cx,
16768            );
16769            snapshot
16770        })
16771        .unwrap();
16772
16773    let render_args = render_args.lock().take().unwrap();
16774    assert_eq!(render_args.row, MultiBufferRow(1));
16775    assert!(!render_args.folded);
16776    assert!(!snapshot.is_line_folded(MultiBufferRow(1)));
16777
16778    cx.update_window(*editor, |_, window, cx| {
16779        (render_args.callback)(true, window, cx)
16780    })
16781    .unwrap();
16782    let snapshot = editor
16783        .update(cx, |editor, window, cx| editor.snapshot(window, cx))
16784        .unwrap();
16785    assert!(snapshot.is_line_folded(MultiBufferRow(1)));
16786
16787    cx.update_window(*editor, |_, window, cx| {
16788        (render_args.callback)(false, window, cx)
16789    })
16790    .unwrap();
16791    let snapshot = editor
16792        .update(cx, |editor, window, cx| editor.snapshot(window, cx))
16793        .unwrap();
16794    assert!(!snapshot.is_line_folded(MultiBufferRow(1)));
16795}
16796
16797#[gpui::test]
16798async fn test_input_text(cx: &mut TestAppContext) {
16799    init_test(cx, |_| {});
16800    let mut cx = EditorTestContext::new(cx).await;
16801
16802    cx.set_state(
16803        &r#"ˇone
16804        two
16805
16806        three
16807        fourˇ
16808        five
16809
16810        siˇx"#
16811            .unindent(),
16812    );
16813
16814    cx.dispatch_action(HandleInput(String::new()));
16815    cx.assert_editor_state(
16816        &r#"ˇone
16817        two
16818
16819        three
16820        fourˇ
16821        five
16822
16823        siˇx"#
16824            .unindent(),
16825    );
16826
16827    cx.dispatch_action(HandleInput("AAAA".to_string()));
16828    cx.assert_editor_state(
16829        &r#"AAAAˇone
16830        two
16831
16832        three
16833        fourAAAAˇ
16834        five
16835
16836        siAAAAˇx"#
16837            .unindent(),
16838    );
16839}
16840
16841#[gpui::test]
16842async fn test_scroll_cursor_center_top_bottom(cx: &mut TestAppContext) {
16843    init_test(cx, |_| {});
16844
16845    let mut cx = EditorTestContext::new(cx).await;
16846    cx.set_state(
16847        r#"let foo = 1;
16848let foo = 2;
16849let foo = 3;
16850let fooˇ = 4;
16851let foo = 5;
16852let foo = 6;
16853let foo = 7;
16854let foo = 8;
16855let foo = 9;
16856let foo = 10;
16857let foo = 11;
16858let foo = 12;
16859let foo = 13;
16860let foo = 14;
16861let foo = 15;"#,
16862    );
16863
16864    cx.update_editor(|e, window, cx| {
16865        assert_eq!(
16866            e.next_scroll_position,
16867            NextScrollCursorCenterTopBottom::Center,
16868            "Default next scroll direction is center",
16869        );
16870
16871        e.scroll_cursor_center_top_bottom(&ScrollCursorCenterTopBottom, window, cx);
16872        assert_eq!(
16873            e.next_scroll_position,
16874            NextScrollCursorCenterTopBottom::Top,
16875            "After center, next scroll direction should be top",
16876        );
16877
16878        e.scroll_cursor_center_top_bottom(&ScrollCursorCenterTopBottom, window, cx);
16879        assert_eq!(
16880            e.next_scroll_position,
16881            NextScrollCursorCenterTopBottom::Bottom,
16882            "After top, next scroll direction should be bottom",
16883        );
16884
16885        e.scroll_cursor_center_top_bottom(&ScrollCursorCenterTopBottom, window, cx);
16886        assert_eq!(
16887            e.next_scroll_position,
16888            NextScrollCursorCenterTopBottom::Center,
16889            "After bottom, scrolling should start over",
16890        );
16891
16892        e.scroll_cursor_center_top_bottom(&ScrollCursorCenterTopBottom, window, cx);
16893        assert_eq!(
16894            e.next_scroll_position,
16895            NextScrollCursorCenterTopBottom::Top,
16896            "Scrolling continues if retriggered fast enough"
16897        );
16898    });
16899
16900    cx.executor()
16901        .advance_clock(SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT + Duration::from_millis(200));
16902    cx.executor().run_until_parked();
16903    cx.update_editor(|e, _, _| {
16904        assert_eq!(
16905            e.next_scroll_position,
16906            NextScrollCursorCenterTopBottom::Center,
16907            "If scrolling is not triggered fast enough, it should reset"
16908        );
16909    });
16910}
16911
16912#[gpui::test]
16913async fn test_goto_definition_with_find_all_references_fallback(cx: &mut TestAppContext) {
16914    init_test(cx, |_| {});
16915    let mut cx = EditorLspTestContext::new_rust(
16916        lsp::ServerCapabilities {
16917            definition_provider: Some(lsp::OneOf::Left(true)),
16918            references_provider: Some(lsp::OneOf::Left(true)),
16919            ..lsp::ServerCapabilities::default()
16920        },
16921        cx,
16922    )
16923    .await;
16924
16925    let set_up_lsp_handlers = |empty_go_to_definition: bool, cx: &mut EditorLspTestContext| {
16926        let go_to_definition = cx
16927            .lsp
16928            .set_request_handler::<lsp::request::GotoDefinition, _, _>(
16929                move |params, _| async move {
16930                    if empty_go_to_definition {
16931                        Ok(None)
16932                    } else {
16933                        Ok(Some(lsp::GotoDefinitionResponse::Scalar(lsp::Location {
16934                            uri: params.text_document_position_params.text_document.uri,
16935                            range: lsp::Range::new(
16936                                lsp::Position::new(4, 3),
16937                                lsp::Position::new(4, 6),
16938                            ),
16939                        })))
16940                    }
16941                },
16942            );
16943        let references = cx
16944            .lsp
16945            .set_request_handler::<lsp::request::References, _, _>(move |params, _| async move {
16946                Ok(Some(vec![lsp::Location {
16947                    uri: params.text_document_position.text_document.uri,
16948                    range: lsp::Range::new(lsp::Position::new(0, 8), lsp::Position::new(0, 11)),
16949                }]))
16950            });
16951        (go_to_definition, references)
16952    };
16953
16954    cx.set_state(
16955        &r#"fn one() {
16956            let mut a = ˇtwo();
16957        }
16958
16959        fn two() {}"#
16960            .unindent(),
16961    );
16962    set_up_lsp_handlers(false, &mut cx);
16963    let navigated = cx
16964        .update_editor(|editor, window, cx| editor.go_to_definition(&GoToDefinition, window, cx))
16965        .await
16966        .expect("Failed to navigate to definition");
16967    assert_eq!(
16968        navigated,
16969        Navigated::Yes,
16970        "Should have navigated to definition from the GetDefinition response"
16971    );
16972    cx.assert_editor_state(
16973        &r#"fn one() {
16974            let mut a = two();
16975        }
16976
16977        fn «twoˇ»() {}"#
16978            .unindent(),
16979    );
16980
16981    let editors = cx.update_workspace(|workspace, _, cx| {
16982        workspace.items_of_type::<Editor>(cx).collect::<Vec<_>>()
16983    });
16984    cx.update_editor(|_, _, test_editor_cx| {
16985        assert_eq!(
16986            editors.len(),
16987            1,
16988            "Initially, only one, test, editor should be open in the workspace"
16989        );
16990        assert_eq!(
16991            test_editor_cx.entity(),
16992            editors.last().expect("Asserted len is 1").clone()
16993        );
16994    });
16995
16996    set_up_lsp_handlers(true, &mut cx);
16997    let navigated = cx
16998        .update_editor(|editor, window, cx| editor.go_to_definition(&GoToDefinition, window, cx))
16999        .await
17000        .expect("Failed to navigate to lookup references");
17001    assert_eq!(
17002        navigated,
17003        Navigated::Yes,
17004        "Should have navigated to references as a fallback after empty GoToDefinition response"
17005    );
17006    // We should not change the selections in the existing file,
17007    // if opening another milti buffer with the references
17008    cx.assert_editor_state(
17009        &r#"fn one() {
17010            let mut a = two();
17011        }
17012
17013        fn «twoˇ»() {}"#
17014            .unindent(),
17015    );
17016    let editors = cx.update_workspace(|workspace, _, cx| {
17017        workspace.items_of_type::<Editor>(cx).collect::<Vec<_>>()
17018    });
17019    cx.update_editor(|_, _, test_editor_cx| {
17020        assert_eq!(
17021            editors.len(),
17022            2,
17023            "After falling back to references search, we open a new editor with the results"
17024        );
17025        let references_fallback_text = editors
17026            .into_iter()
17027            .find(|new_editor| *new_editor != test_editor_cx.entity())
17028            .expect("Should have one non-test editor now")
17029            .read(test_editor_cx)
17030            .text(test_editor_cx);
17031        assert_eq!(
17032            references_fallback_text, "fn one() {\n    let mut a = two();\n}",
17033            "Should use the range from the references response and not the GoToDefinition one"
17034        );
17035    });
17036}
17037
17038#[gpui::test]
17039async fn test_goto_definition_no_fallback(cx: &mut TestAppContext) {
17040    init_test(cx, |_| {});
17041    cx.update(|cx| {
17042        let mut editor_settings = EditorSettings::get_global(cx).clone();
17043        editor_settings.go_to_definition_fallback = GoToDefinitionFallback::None;
17044        EditorSettings::override_global(editor_settings, cx);
17045    });
17046    let mut cx = EditorLspTestContext::new_rust(
17047        lsp::ServerCapabilities {
17048            definition_provider: Some(lsp::OneOf::Left(true)),
17049            references_provider: Some(lsp::OneOf::Left(true)),
17050            ..lsp::ServerCapabilities::default()
17051        },
17052        cx,
17053    )
17054    .await;
17055    let original_state = r#"fn one() {
17056        let mut a = ˇtwo();
17057    }
17058
17059    fn two() {}"#
17060        .unindent();
17061    cx.set_state(&original_state);
17062
17063    let mut go_to_definition = cx
17064        .lsp
17065        .set_request_handler::<lsp::request::GotoDefinition, _, _>(
17066            move |_, _| async move { Ok(None) },
17067        );
17068    let _references = cx
17069        .lsp
17070        .set_request_handler::<lsp::request::References, _, _>(move |_, _| async move {
17071            panic!("Should not call for references with no go to definition fallback")
17072        });
17073
17074    let navigated = cx
17075        .update_editor(|editor, window, cx| editor.go_to_definition(&GoToDefinition, window, cx))
17076        .await
17077        .expect("Failed to navigate to lookup references");
17078    go_to_definition
17079        .next()
17080        .await
17081        .expect("Should have called the go_to_definition handler");
17082
17083    assert_eq!(
17084        navigated,
17085        Navigated::No,
17086        "Should have navigated to references as a fallback after empty GoToDefinition response"
17087    );
17088    cx.assert_editor_state(&original_state);
17089    let editors = cx.update_workspace(|workspace, _, cx| {
17090        workspace.items_of_type::<Editor>(cx).collect::<Vec<_>>()
17091    });
17092    cx.update_editor(|_, _, _| {
17093        assert_eq!(
17094            editors.len(),
17095            1,
17096            "After unsuccessful fallback, no other editor should have been opened"
17097        );
17098    });
17099}
17100
17101#[gpui::test]
17102async fn test_find_enclosing_node_with_task(cx: &mut TestAppContext) {
17103    init_test(cx, |_| {});
17104
17105    let language = Arc::new(Language::new(
17106        LanguageConfig::default(),
17107        Some(tree_sitter_rust::LANGUAGE.into()),
17108    ));
17109
17110    let text = r#"
17111        #[cfg(test)]
17112        mod tests() {
17113            #[test]
17114            fn runnable_1() {
17115                let a = 1;
17116            }
17117
17118            #[test]
17119            fn runnable_2() {
17120                let a = 1;
17121                let b = 2;
17122            }
17123        }
17124    "#
17125    .unindent();
17126
17127    let fs = FakeFs::new(cx.executor());
17128    fs.insert_file("/file.rs", Default::default()).await;
17129
17130    let project = Project::test(fs, ["/a".as_ref()], cx).await;
17131    let workspace = cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
17132    let cx = &mut VisualTestContext::from_window(*workspace.deref(), cx);
17133    let buffer = cx.new(|cx| Buffer::local(text, cx).with_language(language, cx));
17134    let multi_buffer = cx.new(|cx| MultiBuffer::singleton(buffer.clone(), cx));
17135
17136    let editor = cx.new_window_entity(|window, cx| {
17137        Editor::new(
17138            EditorMode::full(),
17139            multi_buffer,
17140            Some(project.clone()),
17141            window,
17142            cx,
17143        )
17144    });
17145
17146    editor.update_in(cx, |editor, window, cx| {
17147        let snapshot = editor.buffer().read(cx).snapshot(cx);
17148        editor.tasks.insert(
17149            (buffer.read(cx).remote_id(), 3),
17150            RunnableTasks {
17151                templates: vec![],
17152                offset: snapshot.anchor_before(43),
17153                column: 0,
17154                extra_variables: HashMap::default(),
17155                context_range: BufferOffset(43)..BufferOffset(85),
17156            },
17157        );
17158        editor.tasks.insert(
17159            (buffer.read(cx).remote_id(), 8),
17160            RunnableTasks {
17161                templates: vec![],
17162                offset: snapshot.anchor_before(86),
17163                column: 0,
17164                extra_variables: HashMap::default(),
17165                context_range: BufferOffset(86)..BufferOffset(191),
17166            },
17167        );
17168
17169        // Test finding task when cursor is inside function body
17170        editor.change_selections(None, window, cx, |s| {
17171            s.select_ranges([Point::new(4, 5)..Point::new(4, 5)])
17172        });
17173        let (_, row, _) = editor.find_enclosing_node_task(cx).unwrap();
17174        assert_eq!(row, 3, "Should find task for cursor inside runnable_1");
17175
17176        // Test finding task when cursor is on function name
17177        editor.change_selections(None, window, cx, |s| {
17178            s.select_ranges([Point::new(8, 4)..Point::new(8, 4)])
17179        });
17180        let (_, row, _) = editor.find_enclosing_node_task(cx).unwrap();
17181        assert_eq!(row, 8, "Should find task when cursor is on function name");
17182    });
17183}
17184
17185#[gpui::test]
17186async fn test_folding_buffers(cx: &mut TestAppContext) {
17187    init_test(cx, |_| {});
17188
17189    let sample_text_1 = "aaaa\nbbbb\ncccc\ndddd\neeee\nffff\ngggg\nhhhh\niiii\njjjj".to_string();
17190    let sample_text_2 = "llll\nmmmm\nnnnn\noooo\npppp\nqqqq\nrrrr\nssss\ntttt\nuuuu".to_string();
17191    let sample_text_3 = "vvvv\nwwww\nxxxx\nyyyy\nzzzz\n1111\n2222\n3333\n4444\n5555".to_string();
17192
17193    let fs = FakeFs::new(cx.executor());
17194    fs.insert_tree(
17195        path!("/a"),
17196        json!({
17197            "first.rs": sample_text_1,
17198            "second.rs": sample_text_2,
17199            "third.rs": sample_text_3,
17200        }),
17201    )
17202    .await;
17203    let project = Project::test(fs, [path!("/a").as_ref()], cx).await;
17204    let workspace = cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
17205    let cx = &mut VisualTestContext::from_window(*workspace.deref(), cx);
17206    let worktree = project.update(cx, |project, cx| {
17207        let mut worktrees = project.worktrees(cx).collect::<Vec<_>>();
17208        assert_eq!(worktrees.len(), 1);
17209        worktrees.pop().unwrap()
17210    });
17211    let worktree_id = worktree.update(cx, |worktree, _| worktree.id());
17212
17213    let buffer_1 = project
17214        .update(cx, |project, cx| {
17215            project.open_buffer((worktree_id, "first.rs"), cx)
17216        })
17217        .await
17218        .unwrap();
17219    let buffer_2 = project
17220        .update(cx, |project, cx| {
17221            project.open_buffer((worktree_id, "second.rs"), cx)
17222        })
17223        .await
17224        .unwrap();
17225    let buffer_3 = project
17226        .update(cx, |project, cx| {
17227            project.open_buffer((worktree_id, "third.rs"), cx)
17228        })
17229        .await
17230        .unwrap();
17231
17232    let multi_buffer = cx.new(|cx| {
17233        let mut multi_buffer = MultiBuffer::new(ReadWrite);
17234        multi_buffer.push_excerpts(
17235            buffer_1.clone(),
17236            [
17237                ExcerptRange::new(Point::new(0, 0)..Point::new(3, 0)),
17238                ExcerptRange::new(Point::new(5, 0)..Point::new(7, 0)),
17239                ExcerptRange::new(Point::new(9, 0)..Point::new(10, 4)),
17240            ],
17241            cx,
17242        );
17243        multi_buffer.push_excerpts(
17244            buffer_2.clone(),
17245            [
17246                ExcerptRange::new(Point::new(0, 0)..Point::new(3, 0)),
17247                ExcerptRange::new(Point::new(5, 0)..Point::new(7, 0)),
17248                ExcerptRange::new(Point::new(9, 0)..Point::new(10, 4)),
17249            ],
17250            cx,
17251        );
17252        multi_buffer.push_excerpts(
17253            buffer_3.clone(),
17254            [
17255                ExcerptRange::new(Point::new(0, 0)..Point::new(3, 0)),
17256                ExcerptRange::new(Point::new(5, 0)..Point::new(7, 0)),
17257                ExcerptRange::new(Point::new(9, 0)..Point::new(10, 4)),
17258            ],
17259            cx,
17260        );
17261        multi_buffer
17262    });
17263    let multi_buffer_editor = cx.new_window_entity(|window, cx| {
17264        Editor::new(
17265            EditorMode::full(),
17266            multi_buffer.clone(),
17267            Some(project.clone()),
17268            window,
17269            cx,
17270        )
17271    });
17272
17273    assert_eq!(
17274        multi_buffer_editor.update(cx, |editor, cx| editor.display_text(cx)),
17275        "\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",
17276    );
17277
17278    multi_buffer_editor.update(cx, |editor, cx| {
17279        editor.fold_buffer(buffer_1.read(cx).remote_id(), cx)
17280    });
17281    assert_eq!(
17282        multi_buffer_editor.update(cx, |editor, cx| editor.display_text(cx)),
17283        "\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",
17284        "After folding the first buffer, its text should not be displayed"
17285    );
17286
17287    multi_buffer_editor.update(cx, |editor, cx| {
17288        editor.fold_buffer(buffer_2.read(cx).remote_id(), cx)
17289    });
17290    assert_eq!(
17291        multi_buffer_editor.update(cx, |editor, cx| editor.display_text(cx)),
17292        "\n\n\n\n\n\nvvvv\nwwww\nxxxx\n\n\n1111\n2222\n\n\n5555",
17293        "After folding the second buffer, its text should not be displayed"
17294    );
17295
17296    multi_buffer_editor.update(cx, |editor, cx| {
17297        editor.fold_buffer(buffer_3.read(cx).remote_id(), cx)
17298    });
17299    assert_eq!(
17300        multi_buffer_editor.update(cx, |editor, cx| editor.display_text(cx)),
17301        "\n\n\n\n\n",
17302        "After folding the third buffer, its text should not be displayed"
17303    );
17304
17305    // Emulate selection inside the fold logic, that should work
17306    multi_buffer_editor.update_in(cx, |editor, window, cx| {
17307        editor
17308            .snapshot(window, cx)
17309            .next_line_boundary(Point::new(0, 4));
17310    });
17311
17312    multi_buffer_editor.update(cx, |editor, cx| {
17313        editor.unfold_buffer(buffer_2.read(cx).remote_id(), cx)
17314    });
17315    assert_eq!(
17316        multi_buffer_editor.update(cx, |editor, cx| editor.display_text(cx)),
17317        "\n\n\n\nllll\nmmmm\nnnnn\n\n\nqqqq\nrrrr\n\n\nuuuu\n\n",
17318        "After unfolding the second buffer, its text should be displayed"
17319    );
17320
17321    // Typing inside of buffer 1 causes that buffer to be unfolded.
17322    multi_buffer_editor.update_in(cx, |editor, window, cx| {
17323        assert_eq!(
17324            multi_buffer
17325                .read(cx)
17326                .snapshot(cx)
17327                .text_for_range(Point::new(1, 0)..Point::new(1, 4))
17328                .collect::<String>(),
17329            "bbbb"
17330        );
17331        editor.change_selections(None, window, cx, |selections| {
17332            selections.select_ranges(vec![Point::new(1, 0)..Point::new(1, 0)]);
17333        });
17334        editor.handle_input("B", window, cx);
17335    });
17336
17337    assert_eq!(
17338        multi_buffer_editor.update(cx, |editor, cx| editor.display_text(cx)),
17339        "\n\nB\n\n\n\n\n\n\nllll\nmmmm\nnnnn\n\n\nqqqq\nrrrr\n\n\nuuuu\n\n",
17340        "After unfolding the first buffer, its and 2nd buffer's text should be displayed"
17341    );
17342
17343    multi_buffer_editor.update(cx, |editor, cx| {
17344        editor.unfold_buffer(buffer_3.read(cx).remote_id(), cx)
17345    });
17346    assert_eq!(
17347        multi_buffer_editor.update(cx, |editor, cx| editor.display_text(cx)),
17348        "\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",
17349        "After unfolding the all buffers, all original text should be displayed"
17350    );
17351}
17352
17353#[gpui::test]
17354async fn test_folding_buffers_with_one_excerpt(cx: &mut TestAppContext) {
17355    init_test(cx, |_| {});
17356
17357    let sample_text_1 = "1111\n2222\n3333".to_string();
17358    let sample_text_2 = "4444\n5555\n6666".to_string();
17359    let sample_text_3 = "7777\n8888\n9999".to_string();
17360
17361    let fs = FakeFs::new(cx.executor());
17362    fs.insert_tree(
17363        path!("/a"),
17364        json!({
17365            "first.rs": sample_text_1,
17366            "second.rs": sample_text_2,
17367            "third.rs": sample_text_3,
17368        }),
17369    )
17370    .await;
17371    let project = Project::test(fs, [path!("/a").as_ref()], cx).await;
17372    let workspace = cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
17373    let cx = &mut VisualTestContext::from_window(*workspace.deref(), cx);
17374    let worktree = project.update(cx, |project, cx| {
17375        let mut worktrees = project.worktrees(cx).collect::<Vec<_>>();
17376        assert_eq!(worktrees.len(), 1);
17377        worktrees.pop().unwrap()
17378    });
17379    let worktree_id = worktree.update(cx, |worktree, _| worktree.id());
17380
17381    let buffer_1 = project
17382        .update(cx, |project, cx| {
17383            project.open_buffer((worktree_id, "first.rs"), cx)
17384        })
17385        .await
17386        .unwrap();
17387    let buffer_2 = project
17388        .update(cx, |project, cx| {
17389            project.open_buffer((worktree_id, "second.rs"), cx)
17390        })
17391        .await
17392        .unwrap();
17393    let buffer_3 = project
17394        .update(cx, |project, cx| {
17395            project.open_buffer((worktree_id, "third.rs"), cx)
17396        })
17397        .await
17398        .unwrap();
17399
17400    let multi_buffer = cx.new(|cx| {
17401        let mut multi_buffer = MultiBuffer::new(ReadWrite);
17402        multi_buffer.push_excerpts(
17403            buffer_1.clone(),
17404            [ExcerptRange::new(Point::new(0, 0)..Point::new(3, 0))],
17405            cx,
17406        );
17407        multi_buffer.push_excerpts(
17408            buffer_2.clone(),
17409            [ExcerptRange::new(Point::new(0, 0)..Point::new(3, 0))],
17410            cx,
17411        );
17412        multi_buffer.push_excerpts(
17413            buffer_3.clone(),
17414            [ExcerptRange::new(Point::new(0, 0)..Point::new(3, 0))],
17415            cx,
17416        );
17417        multi_buffer
17418    });
17419
17420    let multi_buffer_editor = cx.new_window_entity(|window, cx| {
17421        Editor::new(
17422            EditorMode::full(),
17423            multi_buffer,
17424            Some(project.clone()),
17425            window,
17426            cx,
17427        )
17428    });
17429
17430    let full_text = "\n\n1111\n2222\n3333\n\n\n4444\n5555\n6666\n\n\n7777\n8888\n9999";
17431    assert_eq!(
17432        multi_buffer_editor.update(cx, |editor, cx| editor.display_text(cx)),
17433        full_text,
17434    );
17435
17436    multi_buffer_editor.update(cx, |editor, cx| {
17437        editor.fold_buffer(buffer_1.read(cx).remote_id(), cx)
17438    });
17439    assert_eq!(
17440        multi_buffer_editor.update(cx, |editor, cx| editor.display_text(cx)),
17441        "\n\n\n\n4444\n5555\n6666\n\n\n7777\n8888\n9999",
17442        "After folding the first buffer, its text should not be displayed"
17443    );
17444
17445    multi_buffer_editor.update(cx, |editor, cx| {
17446        editor.fold_buffer(buffer_2.read(cx).remote_id(), cx)
17447    });
17448
17449    assert_eq!(
17450        multi_buffer_editor.update(cx, |editor, cx| editor.display_text(cx)),
17451        "\n\n\n\n\n\n7777\n8888\n9999",
17452        "After folding the second buffer, its text should not be displayed"
17453    );
17454
17455    multi_buffer_editor.update(cx, |editor, cx| {
17456        editor.fold_buffer(buffer_3.read(cx).remote_id(), cx)
17457    });
17458    assert_eq!(
17459        multi_buffer_editor.update(cx, |editor, cx| editor.display_text(cx)),
17460        "\n\n\n\n\n",
17461        "After folding the third buffer, its text should not be displayed"
17462    );
17463
17464    multi_buffer_editor.update(cx, |editor, cx| {
17465        editor.unfold_buffer(buffer_2.read(cx).remote_id(), cx)
17466    });
17467    assert_eq!(
17468        multi_buffer_editor.update(cx, |editor, cx| editor.display_text(cx)),
17469        "\n\n\n\n4444\n5555\n6666\n\n",
17470        "After unfolding the second buffer, its text should be displayed"
17471    );
17472
17473    multi_buffer_editor.update(cx, |editor, cx| {
17474        editor.unfold_buffer(buffer_1.read(cx).remote_id(), cx)
17475    });
17476    assert_eq!(
17477        multi_buffer_editor.update(cx, |editor, cx| editor.display_text(cx)),
17478        "\n\n1111\n2222\n3333\n\n\n4444\n5555\n6666\n\n",
17479        "After unfolding the first buffer, its text should be displayed"
17480    );
17481
17482    multi_buffer_editor.update(cx, |editor, cx| {
17483        editor.unfold_buffer(buffer_3.read(cx).remote_id(), cx)
17484    });
17485    assert_eq!(
17486        multi_buffer_editor.update(cx, |editor, cx| editor.display_text(cx)),
17487        full_text,
17488        "After unfolding all buffers, all original text should be displayed"
17489    );
17490}
17491
17492#[gpui::test]
17493async fn test_folding_buffer_when_multibuffer_has_only_one_excerpt(cx: &mut TestAppContext) {
17494    init_test(cx, |_| {});
17495
17496    let sample_text = "aaaa\nbbbb\ncccc\ndddd\neeee\nffff\ngggg\nhhhh\niiii\njjjj".to_string();
17497
17498    let fs = FakeFs::new(cx.executor());
17499    fs.insert_tree(
17500        path!("/a"),
17501        json!({
17502            "main.rs": sample_text,
17503        }),
17504    )
17505    .await;
17506    let project = Project::test(fs, [path!("/a").as_ref()], cx).await;
17507    let workspace = cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
17508    let cx = &mut VisualTestContext::from_window(*workspace.deref(), cx);
17509    let worktree = project.update(cx, |project, cx| {
17510        let mut worktrees = project.worktrees(cx).collect::<Vec<_>>();
17511        assert_eq!(worktrees.len(), 1);
17512        worktrees.pop().unwrap()
17513    });
17514    let worktree_id = worktree.update(cx, |worktree, _| worktree.id());
17515
17516    let buffer_1 = project
17517        .update(cx, |project, cx| {
17518            project.open_buffer((worktree_id, "main.rs"), cx)
17519        })
17520        .await
17521        .unwrap();
17522
17523    let multi_buffer = cx.new(|cx| {
17524        let mut multi_buffer = MultiBuffer::new(ReadWrite);
17525        multi_buffer.push_excerpts(
17526            buffer_1.clone(),
17527            [ExcerptRange::new(
17528                Point::new(0, 0)
17529                    ..Point::new(
17530                        sample_text.chars().filter(|&c| c == '\n').count() as u32 + 1,
17531                        0,
17532                    ),
17533            )],
17534            cx,
17535        );
17536        multi_buffer
17537    });
17538    let multi_buffer_editor = cx.new_window_entity(|window, cx| {
17539        Editor::new(
17540            EditorMode::full(),
17541            multi_buffer,
17542            Some(project.clone()),
17543            window,
17544            cx,
17545        )
17546    });
17547
17548    let selection_range = Point::new(1, 0)..Point::new(2, 0);
17549    multi_buffer_editor.update_in(cx, |editor, window, cx| {
17550        enum TestHighlight {}
17551        let multi_buffer_snapshot = editor.buffer().read(cx).snapshot(cx);
17552        let highlight_range = selection_range.clone().to_anchors(&multi_buffer_snapshot);
17553        editor.highlight_text::<TestHighlight>(
17554            vec![highlight_range.clone()],
17555            HighlightStyle::color(Hsla::green()),
17556            cx,
17557        );
17558        editor.change_selections(None, window, cx, |s| s.select_ranges(Some(highlight_range)));
17559    });
17560
17561    let full_text = format!("\n\n{sample_text}");
17562    assert_eq!(
17563        multi_buffer_editor.update(cx, |editor, cx| editor.display_text(cx)),
17564        full_text,
17565    );
17566}
17567
17568#[gpui::test]
17569async fn test_multi_buffer_navigation_with_folded_buffers(cx: &mut TestAppContext) {
17570    init_test(cx, |_| {});
17571    cx.update(|cx| {
17572        let default_key_bindings = settings::KeymapFile::load_asset_allow_partial_failure(
17573            "keymaps/default-linux.json",
17574            cx,
17575        )
17576        .unwrap();
17577        cx.bind_keys(default_key_bindings);
17578    });
17579
17580    let (editor, cx) = cx.add_window_view(|window, cx| {
17581        let multi_buffer = MultiBuffer::build_multi(
17582            [
17583                ("a0\nb0\nc0\nd0\ne0\n", vec![Point::row_range(0..2)]),
17584                ("a1\nb1\nc1\nd1\ne1\n", vec![Point::row_range(0..2)]),
17585                ("a2\nb2\nc2\nd2\ne2\n", vec![Point::row_range(0..2)]),
17586                ("a3\nb3\nc3\nd3\ne3\n", vec![Point::row_range(0..2)]),
17587            ],
17588            cx,
17589        );
17590        let mut editor = Editor::new(EditorMode::full(), multi_buffer.clone(), None, window, cx);
17591
17592        let buffer_ids = multi_buffer.read(cx).excerpt_buffer_ids();
17593        // fold all but the second buffer, so that we test navigating between two
17594        // adjacent folded buffers, as well as folded buffers at the start and
17595        // end the multibuffer
17596        editor.fold_buffer(buffer_ids[0], cx);
17597        editor.fold_buffer(buffer_ids[2], cx);
17598        editor.fold_buffer(buffer_ids[3], cx);
17599
17600        editor
17601    });
17602    cx.simulate_resize(size(px(1000.), px(1000.)));
17603
17604    let mut cx = EditorTestContext::for_editor_in(editor.clone(), cx).await;
17605    cx.assert_excerpts_with_selections(indoc! {"
17606        [EXCERPT]
17607        ˇ[FOLDED]
17608        [EXCERPT]
17609        a1
17610        b1
17611        [EXCERPT]
17612        [FOLDED]
17613        [EXCERPT]
17614        [FOLDED]
17615        "
17616    });
17617    cx.simulate_keystroke("down");
17618    cx.assert_excerpts_with_selections(indoc! {"
17619        [EXCERPT]
17620        [FOLDED]
17621        [EXCERPT]
17622        ˇa1
17623        b1
17624        [EXCERPT]
17625        [FOLDED]
17626        [EXCERPT]
17627        [FOLDED]
17628        "
17629    });
17630    cx.simulate_keystroke("down");
17631    cx.assert_excerpts_with_selections(indoc! {"
17632        [EXCERPT]
17633        [FOLDED]
17634        [EXCERPT]
17635        a1
17636        ˇb1
17637        [EXCERPT]
17638        [FOLDED]
17639        [EXCERPT]
17640        [FOLDED]
17641        "
17642    });
17643    cx.simulate_keystroke("down");
17644    cx.assert_excerpts_with_selections(indoc! {"
17645        [EXCERPT]
17646        [FOLDED]
17647        [EXCERPT]
17648        a1
17649        b1
17650        ˇ[EXCERPT]
17651        [FOLDED]
17652        [EXCERPT]
17653        [FOLDED]
17654        "
17655    });
17656    cx.simulate_keystroke("down");
17657    cx.assert_excerpts_with_selections(indoc! {"
17658        [EXCERPT]
17659        [FOLDED]
17660        [EXCERPT]
17661        a1
17662        b1
17663        [EXCERPT]
17664        ˇ[FOLDED]
17665        [EXCERPT]
17666        [FOLDED]
17667        "
17668    });
17669    for _ in 0..5 {
17670        cx.simulate_keystroke("down");
17671        cx.assert_excerpts_with_selections(indoc! {"
17672            [EXCERPT]
17673            [FOLDED]
17674            [EXCERPT]
17675            a1
17676            b1
17677            [EXCERPT]
17678            [FOLDED]
17679            [EXCERPT]
17680            ˇ[FOLDED]
17681            "
17682        });
17683    }
17684
17685    cx.simulate_keystroke("up");
17686    cx.assert_excerpts_with_selections(indoc! {"
17687        [EXCERPT]
17688        [FOLDED]
17689        [EXCERPT]
17690        a1
17691        b1
17692        [EXCERPT]
17693        ˇ[FOLDED]
17694        [EXCERPT]
17695        [FOLDED]
17696        "
17697    });
17698    cx.simulate_keystroke("up");
17699    cx.assert_excerpts_with_selections(indoc! {"
17700        [EXCERPT]
17701        [FOLDED]
17702        [EXCERPT]
17703        a1
17704        b1
17705        ˇ[EXCERPT]
17706        [FOLDED]
17707        [EXCERPT]
17708        [FOLDED]
17709        "
17710    });
17711    cx.simulate_keystroke("up");
17712    cx.assert_excerpts_with_selections(indoc! {"
17713        [EXCERPT]
17714        [FOLDED]
17715        [EXCERPT]
17716        a1
17717        ˇb1
17718        [EXCERPT]
17719        [FOLDED]
17720        [EXCERPT]
17721        [FOLDED]
17722        "
17723    });
17724    cx.simulate_keystroke("up");
17725    cx.assert_excerpts_with_selections(indoc! {"
17726        [EXCERPT]
17727        [FOLDED]
17728        [EXCERPT]
17729        ˇa1
17730        b1
17731        [EXCERPT]
17732        [FOLDED]
17733        [EXCERPT]
17734        [FOLDED]
17735        "
17736    });
17737    for _ in 0..5 {
17738        cx.simulate_keystroke("up");
17739        cx.assert_excerpts_with_selections(indoc! {"
17740            [EXCERPT]
17741            ˇ[FOLDED]
17742            [EXCERPT]
17743            a1
17744            b1
17745            [EXCERPT]
17746            [FOLDED]
17747            [EXCERPT]
17748            [FOLDED]
17749            "
17750        });
17751    }
17752}
17753
17754#[gpui::test]
17755async fn test_inline_completion_text(cx: &mut TestAppContext) {
17756    init_test(cx, |_| {});
17757
17758    // Simple insertion
17759    assert_highlighted_edits(
17760        "Hello, world!",
17761        vec![(Point::new(0, 6)..Point::new(0, 6), " beautiful".into())],
17762        true,
17763        cx,
17764        |highlighted_edits, cx| {
17765            assert_eq!(highlighted_edits.text, "Hello, beautiful world!");
17766            assert_eq!(highlighted_edits.highlights.len(), 1);
17767            assert_eq!(highlighted_edits.highlights[0].0, 6..16);
17768            assert_eq!(
17769                highlighted_edits.highlights[0].1.background_color,
17770                Some(cx.theme().status().created_background)
17771            );
17772        },
17773    )
17774    .await;
17775
17776    // Replacement
17777    assert_highlighted_edits(
17778        "This is a test.",
17779        vec![(Point::new(0, 0)..Point::new(0, 4), "That".into())],
17780        false,
17781        cx,
17782        |highlighted_edits, cx| {
17783            assert_eq!(highlighted_edits.text, "That is a test.");
17784            assert_eq!(highlighted_edits.highlights.len(), 1);
17785            assert_eq!(highlighted_edits.highlights[0].0, 0..4);
17786            assert_eq!(
17787                highlighted_edits.highlights[0].1.background_color,
17788                Some(cx.theme().status().created_background)
17789            );
17790        },
17791    )
17792    .await;
17793
17794    // Multiple edits
17795    assert_highlighted_edits(
17796        "Hello, world!",
17797        vec![
17798            (Point::new(0, 0)..Point::new(0, 5), "Greetings".into()),
17799            (Point::new(0, 12)..Point::new(0, 12), " and universe".into()),
17800        ],
17801        false,
17802        cx,
17803        |highlighted_edits, cx| {
17804            assert_eq!(highlighted_edits.text, "Greetings, world and universe!");
17805            assert_eq!(highlighted_edits.highlights.len(), 2);
17806            assert_eq!(highlighted_edits.highlights[0].0, 0..9);
17807            assert_eq!(highlighted_edits.highlights[1].0, 16..29);
17808            assert_eq!(
17809                highlighted_edits.highlights[0].1.background_color,
17810                Some(cx.theme().status().created_background)
17811            );
17812            assert_eq!(
17813                highlighted_edits.highlights[1].1.background_color,
17814                Some(cx.theme().status().created_background)
17815            );
17816        },
17817    )
17818    .await;
17819
17820    // Multiple lines with edits
17821    assert_highlighted_edits(
17822        "First line\nSecond line\nThird line\nFourth line",
17823        vec![
17824            (Point::new(1, 7)..Point::new(1, 11), "modified".to_string()),
17825            (
17826                Point::new(2, 0)..Point::new(2, 10),
17827                "New third line".to_string(),
17828            ),
17829            (Point::new(3, 6)..Point::new(3, 6), " updated".to_string()),
17830        ],
17831        false,
17832        cx,
17833        |highlighted_edits, cx| {
17834            assert_eq!(
17835                highlighted_edits.text,
17836                "Second modified\nNew third line\nFourth updated line"
17837            );
17838            assert_eq!(highlighted_edits.highlights.len(), 3);
17839            assert_eq!(highlighted_edits.highlights[0].0, 7..15); // "modified"
17840            assert_eq!(highlighted_edits.highlights[1].0, 16..30); // "New third line"
17841            assert_eq!(highlighted_edits.highlights[2].0, 37..45); // " updated"
17842            for highlight in &highlighted_edits.highlights {
17843                assert_eq!(
17844                    highlight.1.background_color,
17845                    Some(cx.theme().status().created_background)
17846                );
17847            }
17848        },
17849    )
17850    .await;
17851}
17852
17853#[gpui::test]
17854async fn test_inline_completion_text_with_deletions(cx: &mut TestAppContext) {
17855    init_test(cx, |_| {});
17856
17857    // Deletion
17858    assert_highlighted_edits(
17859        "Hello, world!",
17860        vec![(Point::new(0, 5)..Point::new(0, 11), "".to_string())],
17861        true,
17862        cx,
17863        |highlighted_edits, cx| {
17864            assert_eq!(highlighted_edits.text, "Hello, world!");
17865            assert_eq!(highlighted_edits.highlights.len(), 1);
17866            assert_eq!(highlighted_edits.highlights[0].0, 5..11);
17867            assert_eq!(
17868                highlighted_edits.highlights[0].1.background_color,
17869                Some(cx.theme().status().deleted_background)
17870            );
17871        },
17872    )
17873    .await;
17874
17875    // Insertion
17876    assert_highlighted_edits(
17877        "Hello, world!",
17878        vec![(Point::new(0, 6)..Point::new(0, 6), " digital".to_string())],
17879        true,
17880        cx,
17881        |highlighted_edits, cx| {
17882            assert_eq!(highlighted_edits.highlights.len(), 1);
17883            assert_eq!(highlighted_edits.highlights[0].0, 6..14);
17884            assert_eq!(
17885                highlighted_edits.highlights[0].1.background_color,
17886                Some(cx.theme().status().created_background)
17887            );
17888        },
17889    )
17890    .await;
17891}
17892
17893async fn assert_highlighted_edits(
17894    text: &str,
17895    edits: Vec<(Range<Point>, String)>,
17896    include_deletions: bool,
17897    cx: &mut TestAppContext,
17898    assertion_fn: impl Fn(HighlightedText, &App),
17899) {
17900    let window = cx.add_window(|window, cx| {
17901        let buffer = MultiBuffer::build_simple(text, cx);
17902        Editor::new(EditorMode::full(), buffer, None, window, cx)
17903    });
17904    let cx = &mut VisualTestContext::from_window(*window, cx);
17905
17906    let (buffer, snapshot) = window
17907        .update(cx, |editor, _window, cx| {
17908            (
17909                editor.buffer().clone(),
17910                editor.buffer().read(cx).snapshot(cx),
17911            )
17912        })
17913        .unwrap();
17914
17915    let edits = edits
17916        .into_iter()
17917        .map(|(range, edit)| {
17918            (
17919                snapshot.anchor_after(range.start)..snapshot.anchor_before(range.end),
17920                edit,
17921            )
17922        })
17923        .collect::<Vec<_>>();
17924
17925    let text_anchor_edits = edits
17926        .clone()
17927        .into_iter()
17928        .map(|(range, edit)| (range.start.text_anchor..range.end.text_anchor, edit))
17929        .collect::<Vec<_>>();
17930
17931    let edit_preview = window
17932        .update(cx, |_, _window, cx| {
17933            buffer
17934                .read(cx)
17935                .as_singleton()
17936                .unwrap()
17937                .read(cx)
17938                .preview_edits(text_anchor_edits.into(), cx)
17939        })
17940        .unwrap()
17941        .await;
17942
17943    cx.update(|_window, cx| {
17944        let highlighted_edits = inline_completion_edit_text(
17945            &snapshot.as_singleton().unwrap().2,
17946            &edits,
17947            &edit_preview,
17948            include_deletions,
17949            cx,
17950        );
17951        assertion_fn(highlighted_edits, cx)
17952    });
17953}
17954
17955#[track_caller]
17956fn assert_breakpoint(
17957    breakpoints: &BTreeMap<Arc<Path>, Vec<SourceBreakpoint>>,
17958    path: &Arc<Path>,
17959    expected: Vec<(u32, Breakpoint)>,
17960) {
17961    if expected.len() == 0usize {
17962        assert!(!breakpoints.contains_key(path), "{}", path.display());
17963    } else {
17964        let mut breakpoint = breakpoints
17965            .get(path)
17966            .unwrap()
17967            .into_iter()
17968            .map(|breakpoint| {
17969                (
17970                    breakpoint.row,
17971                    Breakpoint {
17972                        message: breakpoint.message.clone(),
17973                        state: breakpoint.state,
17974                        condition: breakpoint.condition.clone(),
17975                        hit_condition: breakpoint.hit_condition.clone(),
17976                    },
17977                )
17978            })
17979            .collect::<Vec<_>>();
17980
17981        breakpoint.sort_by_key(|(cached_position, _)| *cached_position);
17982
17983        assert_eq!(expected, breakpoint);
17984    }
17985}
17986
17987fn add_log_breakpoint_at_cursor(
17988    editor: &mut Editor,
17989    log_message: &str,
17990    window: &mut Window,
17991    cx: &mut Context<Editor>,
17992) {
17993    let (anchor, bp) = editor
17994        .breakpoints_at_cursors(window, cx)
17995        .first()
17996        .and_then(|(anchor, bp)| {
17997            if let Some(bp) = bp {
17998                Some((*anchor, bp.clone()))
17999            } else {
18000                None
18001            }
18002        })
18003        .unwrap_or_else(|| {
18004            let cursor_position: Point = editor.selections.newest(cx).head();
18005
18006            let breakpoint_position = editor
18007                .snapshot(window, cx)
18008                .display_snapshot
18009                .buffer_snapshot
18010                .anchor_before(Point::new(cursor_position.row, 0));
18011
18012            (breakpoint_position, Breakpoint::new_log(&log_message))
18013        });
18014
18015    editor.edit_breakpoint_at_anchor(
18016        anchor,
18017        bp,
18018        BreakpointEditAction::EditLogMessage(log_message.into()),
18019        cx,
18020    );
18021}
18022
18023#[gpui::test]
18024async fn test_breakpoint_toggling(cx: &mut TestAppContext) {
18025    init_test(cx, |_| {});
18026
18027    let sample_text = "First line\nSecond line\nThird line\nFourth line".to_string();
18028    let fs = FakeFs::new(cx.executor());
18029    fs.insert_tree(
18030        path!("/a"),
18031        json!({
18032            "main.rs": sample_text,
18033        }),
18034    )
18035    .await;
18036    let project = Project::test(fs, [path!("/a").as_ref()], cx).await;
18037    let workspace = cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
18038    let cx = &mut VisualTestContext::from_window(*workspace.deref(), cx);
18039
18040    let fs = FakeFs::new(cx.executor());
18041    fs.insert_tree(
18042        path!("/a"),
18043        json!({
18044            "main.rs": sample_text,
18045        }),
18046    )
18047    .await;
18048    let project = Project::test(fs, [path!("/a").as_ref()], cx).await;
18049    let workspace = cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
18050    let cx = &mut VisualTestContext::from_window(*workspace.deref(), cx);
18051    let worktree_id = workspace
18052        .update(cx, |workspace, _window, cx| {
18053            workspace.project().update(cx, |project, cx| {
18054                project.worktrees(cx).next().unwrap().read(cx).id()
18055            })
18056        })
18057        .unwrap();
18058
18059    let buffer = project
18060        .update(cx, |project, cx| {
18061            project.open_buffer((worktree_id, "main.rs"), cx)
18062        })
18063        .await
18064        .unwrap();
18065
18066    let (editor, cx) = cx.add_window_view(|window, cx| {
18067        Editor::new(
18068            EditorMode::full(),
18069            MultiBuffer::build_from_buffer(buffer, cx),
18070            Some(project.clone()),
18071            window,
18072            cx,
18073        )
18074    });
18075
18076    let project_path = editor.update(cx, |editor, cx| editor.project_path(cx).unwrap());
18077    let abs_path = project.read_with(cx, |project, cx| {
18078        project
18079            .absolute_path(&project_path, cx)
18080            .map(|path_buf| Arc::from(path_buf.to_owned()))
18081            .unwrap()
18082    });
18083
18084    // assert we can add breakpoint on the first line
18085    editor.update_in(cx, |editor, window, cx| {
18086        editor.toggle_breakpoint(&actions::ToggleBreakpoint, window, cx);
18087        editor.move_to_end(&MoveToEnd, window, cx);
18088        editor.toggle_breakpoint(&actions::ToggleBreakpoint, window, cx);
18089    });
18090
18091    let breakpoints = editor.update(cx, |editor, cx| {
18092        editor
18093            .breakpoint_store()
18094            .as_ref()
18095            .unwrap()
18096            .read(cx)
18097            .all_breakpoints(cx)
18098            .clone()
18099    });
18100
18101    assert_eq!(1, breakpoints.len());
18102    assert_breakpoint(
18103        &breakpoints,
18104        &abs_path,
18105        vec![
18106            (0, Breakpoint::new_standard()),
18107            (3, Breakpoint::new_standard()),
18108        ],
18109    );
18110
18111    editor.update_in(cx, |editor, window, cx| {
18112        editor.move_to_beginning(&MoveToBeginning, window, cx);
18113        editor.toggle_breakpoint(&actions::ToggleBreakpoint, window, cx);
18114    });
18115
18116    let breakpoints = editor.update(cx, |editor, cx| {
18117        editor
18118            .breakpoint_store()
18119            .as_ref()
18120            .unwrap()
18121            .read(cx)
18122            .all_breakpoints(cx)
18123            .clone()
18124    });
18125
18126    assert_eq!(1, breakpoints.len());
18127    assert_breakpoint(
18128        &breakpoints,
18129        &abs_path,
18130        vec![(3, Breakpoint::new_standard())],
18131    );
18132
18133    editor.update_in(cx, |editor, window, cx| {
18134        editor.move_to_end(&MoveToEnd, window, cx);
18135        editor.toggle_breakpoint(&actions::ToggleBreakpoint, window, cx);
18136    });
18137
18138    let breakpoints = editor.update(cx, |editor, cx| {
18139        editor
18140            .breakpoint_store()
18141            .as_ref()
18142            .unwrap()
18143            .read(cx)
18144            .all_breakpoints(cx)
18145            .clone()
18146    });
18147
18148    assert_eq!(0, breakpoints.len());
18149    assert_breakpoint(&breakpoints, &abs_path, vec![]);
18150}
18151
18152#[gpui::test]
18153async fn test_log_breakpoint_editing(cx: &mut TestAppContext) {
18154    init_test(cx, |_| {});
18155
18156    let sample_text = "First line\nSecond line\nThird line\nFourth line".to_string();
18157
18158    let fs = FakeFs::new(cx.executor());
18159    fs.insert_tree(
18160        path!("/a"),
18161        json!({
18162            "main.rs": sample_text,
18163        }),
18164    )
18165    .await;
18166    let project = Project::test(fs, [path!("/a").as_ref()], cx).await;
18167    let (workspace, cx) =
18168        cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
18169
18170    let worktree_id = workspace.update(cx, |workspace, cx| {
18171        workspace.project().update(cx, |project, cx| {
18172            project.worktrees(cx).next().unwrap().read(cx).id()
18173        })
18174    });
18175
18176    let buffer = project
18177        .update(cx, |project, cx| {
18178            project.open_buffer((worktree_id, "main.rs"), cx)
18179        })
18180        .await
18181        .unwrap();
18182
18183    let (editor, cx) = cx.add_window_view(|window, cx| {
18184        Editor::new(
18185            EditorMode::full(),
18186            MultiBuffer::build_from_buffer(buffer, cx),
18187            Some(project.clone()),
18188            window,
18189            cx,
18190        )
18191    });
18192
18193    let project_path = editor.update(cx, |editor, cx| editor.project_path(cx).unwrap());
18194    let abs_path = project.read_with(cx, |project, cx| {
18195        project
18196            .absolute_path(&project_path, cx)
18197            .map(|path_buf| Arc::from(path_buf.to_owned()))
18198            .unwrap()
18199    });
18200
18201    editor.update_in(cx, |editor, window, cx| {
18202        add_log_breakpoint_at_cursor(editor, "hello world", window, cx);
18203    });
18204
18205    let breakpoints = editor.update(cx, |editor, cx| {
18206        editor
18207            .breakpoint_store()
18208            .as_ref()
18209            .unwrap()
18210            .read(cx)
18211            .all_breakpoints(cx)
18212            .clone()
18213    });
18214
18215    assert_breakpoint(
18216        &breakpoints,
18217        &abs_path,
18218        vec![(0, Breakpoint::new_log("hello world"))],
18219    );
18220
18221    // Removing a log message from a log breakpoint should remove it
18222    editor.update_in(cx, |editor, window, cx| {
18223        add_log_breakpoint_at_cursor(editor, "", window, cx);
18224    });
18225
18226    let breakpoints = editor.update(cx, |editor, cx| {
18227        editor
18228            .breakpoint_store()
18229            .as_ref()
18230            .unwrap()
18231            .read(cx)
18232            .all_breakpoints(cx)
18233            .clone()
18234    });
18235
18236    assert_breakpoint(&breakpoints, &abs_path, vec![]);
18237
18238    editor.update_in(cx, |editor, window, cx| {
18239        editor.toggle_breakpoint(&actions::ToggleBreakpoint, window, cx);
18240        editor.move_to_end(&MoveToEnd, window, cx);
18241        editor.toggle_breakpoint(&actions::ToggleBreakpoint, window, cx);
18242        // Not adding a log message to a standard breakpoint shouldn't remove it
18243        add_log_breakpoint_at_cursor(editor, "", window, cx);
18244    });
18245
18246    let breakpoints = editor.update(cx, |editor, cx| {
18247        editor
18248            .breakpoint_store()
18249            .as_ref()
18250            .unwrap()
18251            .read(cx)
18252            .all_breakpoints(cx)
18253            .clone()
18254    });
18255
18256    assert_breakpoint(
18257        &breakpoints,
18258        &abs_path,
18259        vec![
18260            (0, Breakpoint::new_standard()),
18261            (3, Breakpoint::new_standard()),
18262        ],
18263    );
18264
18265    editor.update_in(cx, |editor, window, cx| {
18266        add_log_breakpoint_at_cursor(editor, "hello world", window, cx);
18267    });
18268
18269    let breakpoints = editor.update(cx, |editor, cx| {
18270        editor
18271            .breakpoint_store()
18272            .as_ref()
18273            .unwrap()
18274            .read(cx)
18275            .all_breakpoints(cx)
18276            .clone()
18277    });
18278
18279    assert_breakpoint(
18280        &breakpoints,
18281        &abs_path,
18282        vec![
18283            (0, Breakpoint::new_standard()),
18284            (3, Breakpoint::new_log("hello world")),
18285        ],
18286    );
18287
18288    editor.update_in(cx, |editor, window, cx| {
18289        add_log_breakpoint_at_cursor(editor, "hello Earth!!", window, cx);
18290    });
18291
18292    let breakpoints = editor.update(cx, |editor, cx| {
18293        editor
18294            .breakpoint_store()
18295            .as_ref()
18296            .unwrap()
18297            .read(cx)
18298            .all_breakpoints(cx)
18299            .clone()
18300    });
18301
18302    assert_breakpoint(
18303        &breakpoints,
18304        &abs_path,
18305        vec![
18306            (0, Breakpoint::new_standard()),
18307            (3, Breakpoint::new_log("hello Earth!!")),
18308        ],
18309    );
18310}
18311
18312/// This also tests that Editor::breakpoint_at_cursor_head is working properly
18313/// we had some issues where we wouldn't find a breakpoint at Point {row: 0, col: 0}
18314/// or when breakpoints were placed out of order. This tests for a regression too
18315#[gpui::test]
18316async fn test_breakpoint_enabling_and_disabling(cx: &mut TestAppContext) {
18317    init_test(cx, |_| {});
18318
18319    let sample_text = "First line\nSecond line\nThird line\nFourth line".to_string();
18320    let fs = FakeFs::new(cx.executor());
18321    fs.insert_tree(
18322        path!("/a"),
18323        json!({
18324            "main.rs": sample_text,
18325        }),
18326    )
18327    .await;
18328    let project = Project::test(fs, [path!("/a").as_ref()], cx).await;
18329    let workspace = cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
18330    let cx = &mut VisualTestContext::from_window(*workspace.deref(), cx);
18331
18332    let fs = FakeFs::new(cx.executor());
18333    fs.insert_tree(
18334        path!("/a"),
18335        json!({
18336            "main.rs": sample_text,
18337        }),
18338    )
18339    .await;
18340    let project = Project::test(fs, [path!("/a").as_ref()], cx).await;
18341    let workspace = cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
18342    let cx = &mut VisualTestContext::from_window(*workspace.deref(), cx);
18343    let worktree_id = workspace
18344        .update(cx, |workspace, _window, cx| {
18345            workspace.project().update(cx, |project, cx| {
18346                project.worktrees(cx).next().unwrap().read(cx).id()
18347            })
18348        })
18349        .unwrap();
18350
18351    let buffer = project
18352        .update(cx, |project, cx| {
18353            project.open_buffer((worktree_id, "main.rs"), cx)
18354        })
18355        .await
18356        .unwrap();
18357
18358    let (editor, cx) = cx.add_window_view(|window, cx| {
18359        Editor::new(
18360            EditorMode::full(),
18361            MultiBuffer::build_from_buffer(buffer, cx),
18362            Some(project.clone()),
18363            window,
18364            cx,
18365        )
18366    });
18367
18368    let project_path = editor.update(cx, |editor, cx| editor.project_path(cx).unwrap());
18369    let abs_path = project.read_with(cx, |project, cx| {
18370        project
18371            .absolute_path(&project_path, cx)
18372            .map(|path_buf| Arc::from(path_buf.to_owned()))
18373            .unwrap()
18374    });
18375
18376    // assert we can add breakpoint on the first line
18377    editor.update_in(cx, |editor, window, cx| {
18378        editor.toggle_breakpoint(&actions::ToggleBreakpoint, window, cx);
18379        editor.move_to_end(&MoveToEnd, window, cx);
18380        editor.toggle_breakpoint(&actions::ToggleBreakpoint, window, cx);
18381        editor.move_up(&MoveUp, window, cx);
18382        editor.toggle_breakpoint(&actions::ToggleBreakpoint, window, cx);
18383    });
18384
18385    let breakpoints = editor.update(cx, |editor, cx| {
18386        editor
18387            .breakpoint_store()
18388            .as_ref()
18389            .unwrap()
18390            .read(cx)
18391            .all_breakpoints(cx)
18392            .clone()
18393    });
18394
18395    assert_eq!(1, breakpoints.len());
18396    assert_breakpoint(
18397        &breakpoints,
18398        &abs_path,
18399        vec![
18400            (0, Breakpoint::new_standard()),
18401            (2, Breakpoint::new_standard()),
18402            (3, Breakpoint::new_standard()),
18403        ],
18404    );
18405
18406    editor.update_in(cx, |editor, window, cx| {
18407        editor.move_to_beginning(&MoveToBeginning, window, cx);
18408        editor.disable_breakpoint(&actions::DisableBreakpoint, window, cx);
18409        editor.move_to_end(&MoveToEnd, window, cx);
18410        editor.disable_breakpoint(&actions::DisableBreakpoint, window, cx);
18411        // Disabling a breakpoint that doesn't exist should do nothing
18412        editor.move_up(&MoveUp, window, cx);
18413        editor.move_up(&MoveUp, window, cx);
18414        editor.disable_breakpoint(&actions::DisableBreakpoint, window, cx);
18415    });
18416
18417    let breakpoints = editor.update(cx, |editor, cx| {
18418        editor
18419            .breakpoint_store()
18420            .as_ref()
18421            .unwrap()
18422            .read(cx)
18423            .all_breakpoints(cx)
18424            .clone()
18425    });
18426
18427    let disable_breakpoint = {
18428        let mut bp = Breakpoint::new_standard();
18429        bp.state = BreakpointState::Disabled;
18430        bp
18431    };
18432
18433    assert_eq!(1, breakpoints.len());
18434    assert_breakpoint(
18435        &breakpoints,
18436        &abs_path,
18437        vec![
18438            (0, disable_breakpoint.clone()),
18439            (2, Breakpoint::new_standard()),
18440            (3, disable_breakpoint.clone()),
18441        ],
18442    );
18443
18444    editor.update_in(cx, |editor, window, cx| {
18445        editor.move_to_beginning(&MoveToBeginning, window, cx);
18446        editor.enable_breakpoint(&actions::EnableBreakpoint, window, cx);
18447        editor.move_to_end(&MoveToEnd, window, cx);
18448        editor.enable_breakpoint(&actions::EnableBreakpoint, window, cx);
18449        editor.move_up(&MoveUp, window, cx);
18450        editor.disable_breakpoint(&actions::DisableBreakpoint, window, cx);
18451    });
18452
18453    let breakpoints = editor.update(cx, |editor, cx| {
18454        editor
18455            .breakpoint_store()
18456            .as_ref()
18457            .unwrap()
18458            .read(cx)
18459            .all_breakpoints(cx)
18460            .clone()
18461    });
18462
18463    assert_eq!(1, breakpoints.len());
18464    assert_breakpoint(
18465        &breakpoints,
18466        &abs_path,
18467        vec![
18468            (0, Breakpoint::new_standard()),
18469            (2, disable_breakpoint),
18470            (3, Breakpoint::new_standard()),
18471        ],
18472    );
18473}
18474
18475#[gpui::test]
18476async fn test_rename_with_duplicate_edits(cx: &mut TestAppContext) {
18477    init_test(cx, |_| {});
18478    let capabilities = lsp::ServerCapabilities {
18479        rename_provider: Some(lsp::OneOf::Right(lsp::RenameOptions {
18480            prepare_provider: Some(true),
18481            work_done_progress_options: Default::default(),
18482        })),
18483        ..Default::default()
18484    };
18485    let mut cx = EditorLspTestContext::new_rust(capabilities, cx).await;
18486
18487    cx.set_state(indoc! {"
18488        struct Fˇoo {}
18489    "});
18490
18491    cx.update_editor(|editor, _, cx| {
18492        let highlight_range = Point::new(0, 7)..Point::new(0, 10);
18493        let highlight_range = highlight_range.to_anchors(&editor.buffer().read(cx).snapshot(cx));
18494        editor.highlight_background::<DocumentHighlightRead>(
18495            &[highlight_range],
18496            |c| c.editor_document_highlight_read_background,
18497            cx,
18498        );
18499    });
18500
18501    let mut prepare_rename_handler = cx
18502        .set_request_handler::<lsp::request::PrepareRenameRequest, _, _>(
18503            move |_, _, _| async move {
18504                Ok(Some(lsp::PrepareRenameResponse::Range(lsp::Range {
18505                    start: lsp::Position {
18506                        line: 0,
18507                        character: 7,
18508                    },
18509                    end: lsp::Position {
18510                        line: 0,
18511                        character: 10,
18512                    },
18513                })))
18514            },
18515        );
18516    let prepare_rename_task = cx
18517        .update_editor(|e, window, cx| e.rename(&Rename, window, cx))
18518        .expect("Prepare rename was not started");
18519    prepare_rename_handler.next().await.unwrap();
18520    prepare_rename_task.await.expect("Prepare rename failed");
18521
18522    let mut rename_handler =
18523        cx.set_request_handler::<lsp::request::Rename, _, _>(move |url, _, _| async move {
18524            let edit = lsp::TextEdit {
18525                range: lsp::Range {
18526                    start: lsp::Position {
18527                        line: 0,
18528                        character: 7,
18529                    },
18530                    end: lsp::Position {
18531                        line: 0,
18532                        character: 10,
18533                    },
18534                },
18535                new_text: "FooRenamed".to_string(),
18536            };
18537            Ok(Some(lsp::WorkspaceEdit::new(
18538                // Specify the same edit twice
18539                std::collections::HashMap::from_iter(Some((url, vec![edit.clone(), edit]))),
18540            )))
18541        });
18542    let rename_task = cx
18543        .update_editor(|e, window, cx| e.confirm_rename(&ConfirmRename, window, cx))
18544        .expect("Confirm rename was not started");
18545    rename_handler.next().await.unwrap();
18546    rename_task.await.expect("Confirm rename failed");
18547    cx.run_until_parked();
18548
18549    // Despite two edits, only one is actually applied as those are identical
18550    cx.assert_editor_state(indoc! {"
18551        struct FooRenamedˇ {}
18552    "});
18553}
18554
18555#[gpui::test]
18556async fn test_rename_without_prepare(cx: &mut TestAppContext) {
18557    init_test(cx, |_| {});
18558    // These capabilities indicate that the server does not support prepare rename.
18559    let capabilities = lsp::ServerCapabilities {
18560        rename_provider: Some(lsp::OneOf::Left(true)),
18561        ..Default::default()
18562    };
18563    let mut cx = EditorLspTestContext::new_rust(capabilities, cx).await;
18564
18565    cx.set_state(indoc! {"
18566        struct Fˇoo {}
18567    "});
18568
18569    cx.update_editor(|editor, _window, cx| {
18570        let highlight_range = Point::new(0, 7)..Point::new(0, 10);
18571        let highlight_range = highlight_range.to_anchors(&editor.buffer().read(cx).snapshot(cx));
18572        editor.highlight_background::<DocumentHighlightRead>(
18573            &[highlight_range],
18574            |c| c.editor_document_highlight_read_background,
18575            cx,
18576        );
18577    });
18578
18579    cx.update_editor(|e, window, cx| e.rename(&Rename, window, cx))
18580        .expect("Prepare rename was not started")
18581        .await
18582        .expect("Prepare rename failed");
18583
18584    let mut rename_handler =
18585        cx.set_request_handler::<lsp::request::Rename, _, _>(move |url, _, _| async move {
18586            let edit = lsp::TextEdit {
18587                range: lsp::Range {
18588                    start: lsp::Position {
18589                        line: 0,
18590                        character: 7,
18591                    },
18592                    end: lsp::Position {
18593                        line: 0,
18594                        character: 10,
18595                    },
18596                },
18597                new_text: "FooRenamed".to_string(),
18598            };
18599            Ok(Some(lsp::WorkspaceEdit::new(
18600                std::collections::HashMap::from_iter(Some((url, vec![edit]))),
18601            )))
18602        });
18603    let rename_task = cx
18604        .update_editor(|e, window, cx| e.confirm_rename(&ConfirmRename, window, cx))
18605        .expect("Confirm rename was not started");
18606    rename_handler.next().await.unwrap();
18607    rename_task.await.expect("Confirm rename failed");
18608    cx.run_until_parked();
18609
18610    // Correct range is renamed, as `surrounding_word` is used to find it.
18611    cx.assert_editor_state(indoc! {"
18612        struct FooRenamedˇ {}
18613    "});
18614}
18615
18616#[gpui::test]
18617async fn test_tree_sitter_brackets_newline_insertion(cx: &mut TestAppContext) {
18618    init_test(cx, |_| {});
18619    let mut cx = EditorTestContext::new(cx).await;
18620
18621    let language = Arc::new(
18622        Language::new(
18623            LanguageConfig::default(),
18624            Some(tree_sitter_html::LANGUAGE.into()),
18625        )
18626        .with_brackets_query(
18627            r#"
18628            ("<" @open "/>" @close)
18629            ("</" @open ">" @close)
18630            ("<" @open ">" @close)
18631            ("\"" @open "\"" @close)
18632            ((element (start_tag) @open (end_tag) @close) (#set! newline.only))
18633        "#,
18634        )
18635        .unwrap(),
18636    );
18637    cx.update_buffer(|buffer, cx| buffer.set_language(Some(language), cx));
18638
18639    cx.set_state(indoc! {"
18640        <span>ˇ</span>
18641    "});
18642    cx.update_editor(|e, window, cx| e.newline(&Newline, window, cx));
18643    cx.assert_editor_state(indoc! {"
18644        <span>
18645        ˇ
18646        </span>
18647    "});
18648
18649    cx.set_state(indoc! {"
18650        <span><span></span>ˇ</span>
18651    "});
18652    cx.update_editor(|e, window, cx| e.newline(&Newline, window, cx));
18653    cx.assert_editor_state(indoc! {"
18654        <span><span></span>
18655        ˇ</span>
18656    "});
18657
18658    cx.set_state(indoc! {"
18659        <span>ˇ
18660        </span>
18661    "});
18662    cx.update_editor(|e, window, cx| e.newline(&Newline, window, cx));
18663    cx.assert_editor_state(indoc! {"
18664        <span>
18665        ˇ
18666        </span>
18667    "});
18668}
18669
18670#[gpui::test(iterations = 10)]
18671async fn test_apply_code_lens_actions_with_commands(cx: &mut gpui::TestAppContext) {
18672    init_test(cx, |_| {});
18673
18674    let fs = FakeFs::new(cx.executor());
18675    fs.insert_tree(
18676        path!("/dir"),
18677        json!({
18678            "a.ts": "a",
18679        }),
18680    )
18681    .await;
18682
18683    let project = Project::test(fs, [path!("/dir").as_ref()], cx).await;
18684    let workspace = cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
18685    let cx = &mut VisualTestContext::from_window(*workspace.deref(), cx);
18686
18687    let language_registry = project.read_with(cx, |project, _| project.languages().clone());
18688    language_registry.add(Arc::new(Language::new(
18689        LanguageConfig {
18690            name: "TypeScript".into(),
18691            matcher: LanguageMatcher {
18692                path_suffixes: vec!["ts".to_string()],
18693                ..Default::default()
18694            },
18695            ..Default::default()
18696        },
18697        Some(tree_sitter_typescript::LANGUAGE_TYPESCRIPT.into()),
18698    )));
18699    let mut fake_language_servers = language_registry.register_fake_lsp(
18700        "TypeScript",
18701        FakeLspAdapter {
18702            capabilities: lsp::ServerCapabilities {
18703                code_lens_provider: Some(lsp::CodeLensOptions {
18704                    resolve_provider: Some(true),
18705                }),
18706                execute_command_provider: Some(lsp::ExecuteCommandOptions {
18707                    commands: vec!["_the/command".to_string()],
18708                    ..lsp::ExecuteCommandOptions::default()
18709                }),
18710                ..lsp::ServerCapabilities::default()
18711            },
18712            ..FakeLspAdapter::default()
18713        },
18714    );
18715
18716    let (buffer, _handle) = project
18717        .update(cx, |p, cx| {
18718            p.open_local_buffer_with_lsp(path!("/dir/a.ts"), cx)
18719        })
18720        .await
18721        .unwrap();
18722    cx.executor().run_until_parked();
18723
18724    let fake_server = fake_language_servers.next().await.unwrap();
18725
18726    let buffer_snapshot = buffer.update(cx, |buffer, _| buffer.snapshot());
18727    let anchor = buffer_snapshot.anchor_at(0, text::Bias::Left);
18728    drop(buffer_snapshot);
18729    let actions = cx
18730        .update_window(*workspace, |_, window, cx| {
18731            project.code_actions(&buffer, anchor..anchor, window, cx)
18732        })
18733        .unwrap();
18734
18735    fake_server
18736        .set_request_handler::<lsp::request::CodeLensRequest, _, _>(|_, _| async move {
18737            Ok(Some(vec![
18738                lsp::CodeLens {
18739                    range: lsp::Range::default(),
18740                    command: Some(lsp::Command {
18741                        title: "Code lens command".to_owned(),
18742                        command: "_the/command".to_owned(),
18743                        arguments: None,
18744                    }),
18745                    data: None,
18746                },
18747                lsp::CodeLens {
18748                    range: lsp::Range::default(),
18749                    command: Some(lsp::Command {
18750                        title: "Command not in capabilities".to_owned(),
18751                        command: "not in capabilities".to_owned(),
18752                        arguments: None,
18753                    }),
18754                    data: None,
18755                },
18756                lsp::CodeLens {
18757                    range: lsp::Range {
18758                        start: lsp::Position {
18759                            line: 1,
18760                            character: 1,
18761                        },
18762                        end: lsp::Position {
18763                            line: 1,
18764                            character: 1,
18765                        },
18766                    },
18767                    command: Some(lsp::Command {
18768                        title: "Command not in range".to_owned(),
18769                        command: "_the/command".to_owned(),
18770                        arguments: None,
18771                    }),
18772                    data: None,
18773                },
18774            ]))
18775        })
18776        .next()
18777        .await;
18778
18779    let actions = actions.await.unwrap();
18780    assert_eq!(
18781        actions.len(),
18782        1,
18783        "Should have only one valid action for the 0..0 range"
18784    );
18785    let action = actions[0].clone();
18786    let apply = project.update(cx, |project, cx| {
18787        project.apply_code_action(buffer.clone(), action, true, cx)
18788    });
18789
18790    // Resolving the code action does not populate its edits. In absence of
18791    // edits, we must execute the given command.
18792    fake_server.set_request_handler::<lsp::request::CodeLensResolve, _, _>(
18793        |mut lens, _| async move {
18794            let lens_command = lens.command.as_mut().expect("should have a command");
18795            assert_eq!(lens_command.title, "Code lens command");
18796            lens_command.arguments = Some(vec![json!("the-argument")]);
18797            Ok(lens)
18798        },
18799    );
18800
18801    // While executing the command, the language server sends the editor
18802    // a `workspaceEdit` request.
18803    fake_server
18804        .set_request_handler::<lsp::request::ExecuteCommand, _, _>({
18805            let fake = fake_server.clone();
18806            move |params, _| {
18807                assert_eq!(params.command, "_the/command");
18808                let fake = fake.clone();
18809                async move {
18810                    fake.server
18811                        .request::<lsp::request::ApplyWorkspaceEdit>(
18812                            lsp::ApplyWorkspaceEditParams {
18813                                label: None,
18814                                edit: lsp::WorkspaceEdit {
18815                                    changes: Some(
18816                                        [(
18817                                            lsp::Url::from_file_path(path!("/dir/a.ts")).unwrap(),
18818                                            vec![lsp::TextEdit {
18819                                                range: lsp::Range::new(
18820                                                    lsp::Position::new(0, 0),
18821                                                    lsp::Position::new(0, 0),
18822                                                ),
18823                                                new_text: "X".into(),
18824                                            }],
18825                                        )]
18826                                        .into_iter()
18827                                        .collect(),
18828                                    ),
18829                                    ..Default::default()
18830                                },
18831                            },
18832                        )
18833                        .await
18834                        .unwrap();
18835                    Ok(Some(json!(null)))
18836                }
18837            }
18838        })
18839        .next()
18840        .await;
18841
18842    // Applying the code lens command returns a project transaction containing the edits
18843    // sent by the language server in its `workspaceEdit` request.
18844    let transaction = apply.await.unwrap();
18845    assert!(transaction.0.contains_key(&buffer));
18846    buffer.update(cx, |buffer, cx| {
18847        assert_eq!(buffer.text(), "Xa");
18848        buffer.undo(cx);
18849        assert_eq!(buffer.text(), "a");
18850    });
18851}
18852
18853#[gpui::test]
18854async fn test_editor_restore_data_different_in_panes(cx: &mut TestAppContext) {
18855    init_test(cx, |_| {});
18856
18857    let fs = FakeFs::new(cx.executor());
18858    let main_text = r#"fn main() {
18859println!("1");
18860println!("2");
18861println!("3");
18862println!("4");
18863println!("5");
18864}"#;
18865    let lib_text = "mod foo {}";
18866    fs.insert_tree(
18867        path!("/a"),
18868        json!({
18869            "lib.rs": lib_text,
18870            "main.rs": main_text,
18871        }),
18872    )
18873    .await;
18874
18875    let project = Project::test(fs, [path!("/a").as_ref()], cx).await;
18876    let (workspace, cx) =
18877        cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
18878    let worktree_id = workspace.update(cx, |workspace, cx| {
18879        workspace.project().update(cx, |project, cx| {
18880            project.worktrees(cx).next().unwrap().read(cx).id()
18881        })
18882    });
18883
18884    let expected_ranges = vec![
18885        Point::new(0, 0)..Point::new(0, 0),
18886        Point::new(1, 0)..Point::new(1, 1),
18887        Point::new(2, 0)..Point::new(2, 2),
18888        Point::new(3, 0)..Point::new(3, 3),
18889    ];
18890
18891    let pane_1 = workspace.update(cx, |workspace, _| workspace.active_pane().clone());
18892    let editor_1 = workspace
18893        .update_in(cx, |workspace, window, cx| {
18894            workspace.open_path(
18895                (worktree_id, "main.rs"),
18896                Some(pane_1.downgrade()),
18897                true,
18898                window,
18899                cx,
18900            )
18901        })
18902        .unwrap()
18903        .await
18904        .downcast::<Editor>()
18905        .unwrap();
18906    pane_1.update(cx, |pane, cx| {
18907        let open_editor = pane.active_item().unwrap().downcast::<Editor>().unwrap();
18908        open_editor.update(cx, |editor, cx| {
18909            assert_eq!(
18910                editor.display_text(cx),
18911                main_text,
18912                "Original main.rs text on initial open",
18913            );
18914            assert_eq!(
18915                editor
18916                    .selections
18917                    .all::<Point>(cx)
18918                    .into_iter()
18919                    .map(|s| s.range())
18920                    .collect::<Vec<_>>(),
18921                vec![Point::zero()..Point::zero()],
18922                "Default selections on initial open",
18923            );
18924        })
18925    });
18926    editor_1.update_in(cx, |editor, window, cx| {
18927        editor.change_selections(None, window, cx, |s| {
18928            s.select_ranges(expected_ranges.clone());
18929        });
18930    });
18931
18932    let pane_2 = workspace.update_in(cx, |workspace, window, cx| {
18933        workspace.split_pane(pane_1.clone(), SplitDirection::Right, window, cx)
18934    });
18935    let editor_2 = workspace
18936        .update_in(cx, |workspace, window, cx| {
18937            workspace.open_path(
18938                (worktree_id, "main.rs"),
18939                Some(pane_2.downgrade()),
18940                true,
18941                window,
18942                cx,
18943            )
18944        })
18945        .unwrap()
18946        .await
18947        .downcast::<Editor>()
18948        .unwrap();
18949    pane_2.update(cx, |pane, cx| {
18950        let open_editor = pane.active_item().unwrap().downcast::<Editor>().unwrap();
18951        open_editor.update(cx, |editor, cx| {
18952            assert_eq!(
18953                editor.display_text(cx),
18954                main_text,
18955                "Original main.rs text on initial open in another panel",
18956            );
18957            assert_eq!(
18958                editor
18959                    .selections
18960                    .all::<Point>(cx)
18961                    .into_iter()
18962                    .map(|s| s.range())
18963                    .collect::<Vec<_>>(),
18964                vec![Point::zero()..Point::zero()],
18965                "Default selections on initial open in another panel",
18966            );
18967        })
18968    });
18969
18970    editor_2.update_in(cx, |editor, window, cx| {
18971        editor.fold_ranges(expected_ranges.clone(), false, window, cx);
18972    });
18973
18974    let _other_editor_1 = workspace
18975        .update_in(cx, |workspace, window, cx| {
18976            workspace.open_path(
18977                (worktree_id, "lib.rs"),
18978                Some(pane_1.downgrade()),
18979                true,
18980                window,
18981                cx,
18982            )
18983        })
18984        .unwrap()
18985        .await
18986        .downcast::<Editor>()
18987        .unwrap();
18988    pane_1
18989        .update_in(cx, |pane, window, cx| {
18990            pane.close_inactive_items(&CloseInactiveItems::default(), window, cx)
18991                .unwrap()
18992        })
18993        .await
18994        .unwrap();
18995    drop(editor_1);
18996    pane_1.update(cx, |pane, cx| {
18997        pane.active_item()
18998            .unwrap()
18999            .downcast::<Editor>()
19000            .unwrap()
19001            .update(cx, |editor, cx| {
19002                assert_eq!(
19003                    editor.display_text(cx),
19004                    lib_text,
19005                    "Other file should be open and active",
19006                );
19007            });
19008        assert_eq!(pane.items().count(), 1, "No other editors should be open");
19009    });
19010
19011    let _other_editor_2 = workspace
19012        .update_in(cx, |workspace, window, cx| {
19013            workspace.open_path(
19014                (worktree_id, "lib.rs"),
19015                Some(pane_2.downgrade()),
19016                true,
19017                window,
19018                cx,
19019            )
19020        })
19021        .unwrap()
19022        .await
19023        .downcast::<Editor>()
19024        .unwrap();
19025    pane_2
19026        .update_in(cx, |pane, window, cx| {
19027            pane.close_inactive_items(&CloseInactiveItems::default(), window, cx)
19028                .unwrap()
19029        })
19030        .await
19031        .unwrap();
19032    drop(editor_2);
19033    pane_2.update(cx, |pane, cx| {
19034        let open_editor = pane.active_item().unwrap().downcast::<Editor>().unwrap();
19035        open_editor.update(cx, |editor, cx| {
19036            assert_eq!(
19037                editor.display_text(cx),
19038                lib_text,
19039                "Other file should be open and active in another panel too",
19040            );
19041        });
19042        assert_eq!(
19043            pane.items().count(),
19044            1,
19045            "No other editors should be open in another pane",
19046        );
19047    });
19048
19049    let _editor_1_reopened = workspace
19050        .update_in(cx, |workspace, window, cx| {
19051            workspace.open_path(
19052                (worktree_id, "main.rs"),
19053                Some(pane_1.downgrade()),
19054                true,
19055                window,
19056                cx,
19057            )
19058        })
19059        .unwrap()
19060        .await
19061        .downcast::<Editor>()
19062        .unwrap();
19063    let _editor_2_reopened = workspace
19064        .update_in(cx, |workspace, window, cx| {
19065            workspace.open_path(
19066                (worktree_id, "main.rs"),
19067                Some(pane_2.downgrade()),
19068                true,
19069                window,
19070                cx,
19071            )
19072        })
19073        .unwrap()
19074        .await
19075        .downcast::<Editor>()
19076        .unwrap();
19077    pane_1.update(cx, |pane, cx| {
19078        let open_editor = pane.active_item().unwrap().downcast::<Editor>().unwrap();
19079        open_editor.update(cx, |editor, cx| {
19080            assert_eq!(
19081                editor.display_text(cx),
19082                main_text,
19083                "Previous editor in the 1st panel had no extra text manipulations and should get none on reopen",
19084            );
19085            assert_eq!(
19086                editor
19087                    .selections
19088                    .all::<Point>(cx)
19089                    .into_iter()
19090                    .map(|s| s.range())
19091                    .collect::<Vec<_>>(),
19092                expected_ranges,
19093                "Previous editor in the 1st panel had selections and should get them restored on reopen",
19094            );
19095        })
19096    });
19097    pane_2.update(cx, |pane, cx| {
19098        let open_editor = pane.active_item().unwrap().downcast::<Editor>().unwrap();
19099        open_editor.update(cx, |editor, cx| {
19100            assert_eq!(
19101                editor.display_text(cx),
19102                r#"fn main() {
19103⋯rintln!("1");
19104⋯intln!("2");
19105⋯ntln!("3");
19106println!("4");
19107println!("5");
19108}"#,
19109                "Previous editor in the 2nd pane had folds and should restore those on reopen in the same pane",
19110            );
19111            assert_eq!(
19112                editor
19113                    .selections
19114                    .all::<Point>(cx)
19115                    .into_iter()
19116                    .map(|s| s.range())
19117                    .collect::<Vec<_>>(),
19118                vec![Point::zero()..Point::zero()],
19119                "Previous editor in the 2nd pane had no selections changed hence should restore none",
19120            );
19121        })
19122    });
19123}
19124
19125#[gpui::test]
19126async fn test_editor_does_not_restore_data_when_turned_off(cx: &mut TestAppContext) {
19127    init_test(cx, |_| {});
19128
19129    let fs = FakeFs::new(cx.executor());
19130    let main_text = r#"fn main() {
19131println!("1");
19132println!("2");
19133println!("3");
19134println!("4");
19135println!("5");
19136}"#;
19137    let lib_text = "mod foo {}";
19138    fs.insert_tree(
19139        path!("/a"),
19140        json!({
19141            "lib.rs": lib_text,
19142            "main.rs": main_text,
19143        }),
19144    )
19145    .await;
19146
19147    let project = Project::test(fs, [path!("/a").as_ref()], cx).await;
19148    let (workspace, cx) =
19149        cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
19150    let worktree_id = workspace.update(cx, |workspace, cx| {
19151        workspace.project().update(cx, |project, cx| {
19152            project.worktrees(cx).next().unwrap().read(cx).id()
19153        })
19154    });
19155
19156    let pane = workspace.update(cx, |workspace, _| workspace.active_pane().clone());
19157    let editor = workspace
19158        .update_in(cx, |workspace, window, cx| {
19159            workspace.open_path(
19160                (worktree_id, "main.rs"),
19161                Some(pane.downgrade()),
19162                true,
19163                window,
19164                cx,
19165            )
19166        })
19167        .unwrap()
19168        .await
19169        .downcast::<Editor>()
19170        .unwrap();
19171    pane.update(cx, |pane, cx| {
19172        let open_editor = pane.active_item().unwrap().downcast::<Editor>().unwrap();
19173        open_editor.update(cx, |editor, cx| {
19174            assert_eq!(
19175                editor.display_text(cx),
19176                main_text,
19177                "Original main.rs text on initial open",
19178            );
19179        })
19180    });
19181    editor.update_in(cx, |editor, window, cx| {
19182        editor.fold_ranges(vec![Point::new(0, 0)..Point::new(0, 0)], false, window, cx);
19183    });
19184
19185    cx.update_global(|store: &mut SettingsStore, cx| {
19186        store.update_user_settings::<WorkspaceSettings>(cx, |s| {
19187            s.restore_on_file_reopen = Some(false);
19188        });
19189    });
19190    editor.update_in(cx, |editor, window, cx| {
19191        editor.fold_ranges(
19192            vec![
19193                Point::new(1, 0)..Point::new(1, 1),
19194                Point::new(2, 0)..Point::new(2, 2),
19195                Point::new(3, 0)..Point::new(3, 3),
19196            ],
19197            false,
19198            window,
19199            cx,
19200        );
19201    });
19202    pane.update_in(cx, |pane, window, cx| {
19203        pane.close_all_items(&CloseAllItems::default(), window, cx)
19204            .unwrap()
19205    })
19206    .await
19207    .unwrap();
19208    pane.update(cx, |pane, _| {
19209        assert!(pane.active_item().is_none());
19210    });
19211    cx.update_global(|store: &mut SettingsStore, cx| {
19212        store.update_user_settings::<WorkspaceSettings>(cx, |s| {
19213            s.restore_on_file_reopen = Some(true);
19214        });
19215    });
19216
19217    let _editor_reopened = workspace
19218        .update_in(cx, |workspace, window, cx| {
19219            workspace.open_path(
19220                (worktree_id, "main.rs"),
19221                Some(pane.downgrade()),
19222                true,
19223                window,
19224                cx,
19225            )
19226        })
19227        .unwrap()
19228        .await
19229        .downcast::<Editor>()
19230        .unwrap();
19231    pane.update(cx, |pane, cx| {
19232        let open_editor = pane.active_item().unwrap().downcast::<Editor>().unwrap();
19233        open_editor.update(cx, |editor, cx| {
19234            assert_eq!(
19235                editor.display_text(cx),
19236                main_text,
19237                "No folds: even after enabling the restoration, previous editor's data should not be saved to be used for the restoration"
19238            );
19239        })
19240    });
19241}
19242
19243fn empty_range(row: usize, column: usize) -> Range<DisplayPoint> {
19244    let point = DisplayPoint::new(DisplayRow(row as u32), column as u32);
19245    point..point
19246}
19247
19248fn assert_selection_ranges(marked_text: &str, editor: &mut Editor, cx: &mut Context<Editor>) {
19249    let (text, ranges) = marked_text_ranges(marked_text, true);
19250    assert_eq!(editor.text(cx), text);
19251    assert_eq!(
19252        editor.selections.ranges(cx),
19253        ranges,
19254        "Assert selections are {}",
19255        marked_text
19256    );
19257}
19258
19259pub fn handle_signature_help_request(
19260    cx: &mut EditorLspTestContext,
19261    mocked_response: lsp::SignatureHelp,
19262) -> impl Future<Output = ()> + use<> {
19263    let mut request =
19264        cx.set_request_handler::<lsp::request::SignatureHelpRequest, _, _>(move |_, _, _| {
19265            let mocked_response = mocked_response.clone();
19266            async move { Ok(Some(mocked_response)) }
19267        });
19268
19269    async move {
19270        request.next().await;
19271    }
19272}
19273
19274/// Handle completion request passing a marked string specifying where the completion
19275/// should be triggered from using '|' character, what range should be replaced, and what completions
19276/// should be returned using '<' and '>' to delimit the range.
19277///
19278/// Also see `handle_completion_request_with_insert_and_replace`.
19279#[track_caller]
19280pub fn handle_completion_request(
19281    cx: &mut EditorLspTestContext,
19282    marked_string: &str,
19283    completions: Vec<&'static str>,
19284    counter: Arc<AtomicUsize>,
19285) -> impl Future<Output = ()> {
19286    let complete_from_marker: TextRangeMarker = '|'.into();
19287    let replace_range_marker: TextRangeMarker = ('<', '>').into();
19288    let (_, mut marked_ranges) = marked_text_ranges_by(
19289        marked_string,
19290        vec![complete_from_marker.clone(), replace_range_marker.clone()],
19291    );
19292
19293    let complete_from_position =
19294        cx.to_lsp(marked_ranges.remove(&complete_from_marker).unwrap()[0].start);
19295    let replace_range =
19296        cx.to_lsp_range(marked_ranges.remove(&replace_range_marker).unwrap()[0].clone());
19297
19298    let mut request =
19299        cx.set_request_handler::<lsp::request::Completion, _, _>(move |url, params, _| {
19300            let completions = completions.clone();
19301            counter.fetch_add(1, atomic::Ordering::Release);
19302            async move {
19303                assert_eq!(params.text_document_position.text_document.uri, url.clone());
19304                assert_eq!(
19305                    params.text_document_position.position,
19306                    complete_from_position
19307                );
19308                Ok(Some(lsp::CompletionResponse::Array(
19309                    completions
19310                        .iter()
19311                        .map(|completion_text| lsp::CompletionItem {
19312                            label: completion_text.to_string(),
19313                            text_edit: Some(lsp::CompletionTextEdit::Edit(lsp::TextEdit {
19314                                range: replace_range,
19315                                new_text: completion_text.to_string(),
19316                            })),
19317                            ..Default::default()
19318                        })
19319                        .collect(),
19320                )))
19321            }
19322        });
19323
19324    async move {
19325        request.next().await;
19326    }
19327}
19328
19329/// Similar to `handle_completion_request`, but a [`CompletionTextEdit::InsertAndReplace`] will be
19330/// given instead, which also contains an `insert` range.
19331///
19332/// This function uses the cursor position to mimic what Rust-Analyzer provides as the `insert` range,
19333/// that is, `replace_range.start..cursor_pos`.
19334pub fn handle_completion_request_with_insert_and_replace(
19335    cx: &mut EditorLspTestContext,
19336    marked_string: &str,
19337    completions: Vec<&'static str>,
19338    counter: Arc<AtomicUsize>,
19339) -> impl Future<Output = ()> {
19340    let complete_from_marker: TextRangeMarker = '|'.into();
19341    let replace_range_marker: TextRangeMarker = ('<', '>').into();
19342    let (_, mut marked_ranges) = marked_text_ranges_by(
19343        marked_string,
19344        vec![complete_from_marker.clone(), replace_range_marker.clone()],
19345    );
19346
19347    let complete_from_position =
19348        cx.to_lsp(marked_ranges.remove(&complete_from_marker).unwrap()[0].start);
19349    let replace_range =
19350        cx.to_lsp_range(marked_ranges.remove(&replace_range_marker).unwrap()[0].clone());
19351
19352    let mut request =
19353        cx.set_request_handler::<lsp::request::Completion, _, _>(move |url, params, _| {
19354            let completions = completions.clone();
19355            counter.fetch_add(1, atomic::Ordering::Release);
19356            async move {
19357                assert_eq!(params.text_document_position.text_document.uri, url.clone());
19358                assert_eq!(
19359                    params.text_document_position.position, complete_from_position,
19360                    "marker `|` position doesn't match",
19361                );
19362                Ok(Some(lsp::CompletionResponse::Array(
19363                    completions
19364                        .iter()
19365                        .map(|completion_text| lsp::CompletionItem {
19366                            label: completion_text.to_string(),
19367                            text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
19368                                lsp::InsertReplaceEdit {
19369                                    insert: lsp::Range {
19370                                        start: replace_range.start,
19371                                        end: complete_from_position,
19372                                    },
19373                                    replace: replace_range,
19374                                    new_text: completion_text.to_string(),
19375                                },
19376                            )),
19377                            ..Default::default()
19378                        })
19379                        .collect(),
19380                )))
19381            }
19382        });
19383
19384    async move {
19385        request.next().await;
19386    }
19387}
19388
19389fn handle_resolve_completion_request(
19390    cx: &mut EditorLspTestContext,
19391    edits: Option<Vec<(&'static str, &'static str)>>,
19392) -> impl Future<Output = ()> {
19393    let edits = edits.map(|edits| {
19394        edits
19395            .iter()
19396            .map(|(marked_string, new_text)| {
19397                let (_, marked_ranges) = marked_text_ranges(marked_string, false);
19398                let replace_range = cx.to_lsp_range(marked_ranges[0].clone());
19399                lsp::TextEdit::new(replace_range, new_text.to_string())
19400            })
19401            .collect::<Vec<_>>()
19402    });
19403
19404    let mut request =
19405        cx.set_request_handler::<lsp::request::ResolveCompletionItem, _, _>(move |_, _, _| {
19406            let edits = edits.clone();
19407            async move {
19408                Ok(lsp::CompletionItem {
19409                    additional_text_edits: edits,
19410                    ..Default::default()
19411                })
19412            }
19413        });
19414
19415    async move {
19416        request.next().await;
19417    }
19418}
19419
19420pub(crate) fn update_test_language_settings(
19421    cx: &mut TestAppContext,
19422    f: impl Fn(&mut AllLanguageSettingsContent),
19423) {
19424    cx.update(|cx| {
19425        SettingsStore::update_global(cx, |store, cx| {
19426            store.update_user_settings::<AllLanguageSettings>(cx, f);
19427        });
19428    });
19429}
19430
19431pub(crate) fn update_test_project_settings(
19432    cx: &mut TestAppContext,
19433    f: impl Fn(&mut ProjectSettings),
19434) {
19435    cx.update(|cx| {
19436        SettingsStore::update_global(cx, |store, cx| {
19437            store.update_user_settings::<ProjectSettings>(cx, f);
19438        });
19439    });
19440}
19441
19442pub(crate) fn init_test(cx: &mut TestAppContext, f: fn(&mut AllLanguageSettingsContent)) {
19443    cx.update(|cx| {
19444        assets::Assets.load_test_fonts(cx);
19445        let store = SettingsStore::test(cx);
19446        cx.set_global(store);
19447        theme::init(theme::LoadThemes::JustBase, cx);
19448        release_channel::init(SemanticVersion::default(), cx);
19449        client::init_settings(cx);
19450        language::init(cx);
19451        Project::init_settings(cx);
19452        workspace::init_settings(cx);
19453        crate::init(cx);
19454    });
19455
19456    update_test_language_settings(cx, f);
19457}
19458
19459#[track_caller]
19460fn assert_hunk_revert(
19461    not_reverted_text_with_selections: &str,
19462    expected_hunk_statuses_before: Vec<DiffHunkStatusKind>,
19463    expected_reverted_text_with_selections: &str,
19464    base_text: &str,
19465    cx: &mut EditorLspTestContext,
19466) {
19467    cx.set_state(not_reverted_text_with_selections);
19468    cx.set_head_text(base_text);
19469    cx.executor().run_until_parked();
19470
19471    let actual_hunk_statuses_before = cx.update_editor(|editor, window, cx| {
19472        let snapshot = editor.snapshot(window, cx);
19473        let reverted_hunk_statuses = snapshot
19474            .buffer_snapshot
19475            .diff_hunks_in_range(0..snapshot.buffer_snapshot.len())
19476            .map(|hunk| hunk.status().kind)
19477            .collect::<Vec<_>>();
19478
19479        editor.git_restore(&Default::default(), window, cx);
19480        reverted_hunk_statuses
19481    });
19482    cx.executor().run_until_parked();
19483    cx.assert_editor_state(expected_reverted_text_with_selections);
19484    assert_eq!(actual_hunk_statuses_before, expected_hunk_statuses_before);
19485}