visual.rs

   1use std::sync::Arc;
   2
   3use collections::HashMap;
   4use editor::{
   5    display_map::{DisplaySnapshot, ToDisplayPoint},
   6    movement,
   7    scroll::Autoscroll,
   8    Bias, DisplayPoint, Editor,
   9};
  10use gpui::{actions, ViewContext, WindowContext};
  11use language::{Point, Selection, SelectionGoal};
  12use multi_buffer::MultiBufferRow;
  13use search::BufferSearchBar;
  14use util::ResultExt;
  15use workspace::{searchable::Direction, Workspace};
  16
  17use crate::{
  18    motion::{start_of_line, Motion},
  19    normal::substitute::substitute,
  20    object::Object,
  21    state::{Mode, Operator},
  22    utils::{copy_selections_content, yank_selections_content},
  23    Vim,
  24};
  25
  26actions!(
  27    vim,
  28    [
  29        ToggleVisual,
  30        ToggleVisualLine,
  31        ToggleVisualBlock,
  32        VisualDelete,
  33        VisualYank,
  34        OtherEnd,
  35        SelectNext,
  36        SelectPrevious,
  37        SelectNextMatch,
  38        SelectPreviousMatch,
  39    ]
  40);
  41
  42pub fn register(workspace: &mut Workspace, _: &mut ViewContext<Workspace>) {
  43    workspace.register_action(|_, _: &ToggleVisual, cx: &mut ViewContext<Workspace>| {
  44        toggle_mode(Mode::Visual, cx)
  45    });
  46    workspace.register_action(|_, _: &ToggleVisualLine, cx: &mut ViewContext<Workspace>| {
  47        toggle_mode(Mode::VisualLine, cx)
  48    });
  49    workspace.register_action(
  50        |_, _: &ToggleVisualBlock, cx: &mut ViewContext<Workspace>| {
  51            toggle_mode(Mode::VisualBlock, cx)
  52        },
  53    );
  54    workspace.register_action(other_end);
  55    workspace.register_action(|_, _: &VisualDelete, cx| {
  56        Vim::update(cx, |vim, cx| {
  57            vim.record_current_action(cx);
  58            delete(vim, cx);
  59        });
  60    });
  61    workspace.register_action(|_, _: &VisualYank, cx| {
  62        Vim::update(cx, |vim, cx| {
  63            yank(vim, cx);
  64        });
  65    });
  66
  67    workspace.register_action(select_next);
  68    workspace.register_action(select_previous);
  69    workspace.register_action(|workspace, _: &SelectNextMatch, cx| {
  70        Vim::update(cx, |vim, cx| {
  71            select_match(workspace, vim, Direction::Next, cx);
  72        });
  73    });
  74    workspace.register_action(|workspace, _: &SelectPreviousMatch, cx| {
  75        Vim::update(cx, |vim, cx| {
  76            select_match(workspace, vim, Direction::Prev, cx);
  77        });
  78    });
  79}
  80
  81pub fn visual_motion(motion: Motion, times: Option<usize>, cx: &mut WindowContext) {
  82    Vim::update(cx, |vim, cx| {
  83        vim.update_active_editor(cx, |vim, editor, cx| {
  84            let text_layout_details = editor.text_layout_details(cx);
  85            if vim.state().mode == Mode::VisualBlock
  86                && !matches!(
  87                    motion,
  88                    Motion::EndOfLine {
  89                        display_lines: false
  90                    }
  91                )
  92            {
  93                let is_up_or_down = matches!(motion, Motion::Up { .. } | Motion::Down { .. });
  94                visual_block_motion(is_up_or_down, editor, cx, |map, point, goal| {
  95                    motion.move_point(map, point, goal, times, &text_layout_details)
  96                })
  97            } else {
  98                editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
  99                    s.move_with(|map, selection| {
 100                        let was_reversed = selection.reversed;
 101                        let mut current_head = selection.head();
 102
 103                        // our motions assume the current character is after the cursor,
 104                        // but in (forward) visual mode the current character is just
 105                        // before the end of the selection.
 106
 107                        // If the file ends with a newline (which is common) we don't do this.
 108                        // so that if you go to the end of such a file you can use "up" to go
 109                        // to the previous line and have it work somewhat as expected.
 110                        #[allow(clippy::nonminimal_bool)]
 111                        if !selection.reversed
 112                            && !selection.is_empty()
 113                            && !(selection.end.column() == 0 && selection.end == map.max_point())
 114                        {
 115                            current_head = movement::left(map, selection.end)
 116                        }
 117
 118                        let Some((new_head, goal)) = motion.move_point(
 119                            map,
 120                            current_head,
 121                            selection.goal,
 122                            times,
 123                            &text_layout_details,
 124                        ) else {
 125                            return;
 126                        };
 127
 128                        selection.set_head(new_head, goal);
 129
 130                        // ensure the current character is included in the selection.
 131                        if !selection.reversed {
 132                            let next_point = if vim.state().mode == Mode::VisualBlock {
 133                                movement::saturating_right(map, selection.end)
 134                            } else {
 135                                movement::right(map, selection.end)
 136                            };
 137
 138                            if !(next_point.column() == 0 && next_point == map.max_point()) {
 139                                selection.end = next_point;
 140                            }
 141                        }
 142
 143                        // vim always ensures the anchor character stays selected.
 144                        // if our selection has reversed, we need to move the opposite end
 145                        // to ensure the anchor is still selected.
 146                        if was_reversed && !selection.reversed {
 147                            selection.start = movement::left(map, selection.start);
 148                        } else if !was_reversed && selection.reversed {
 149                            selection.end = movement::right(map, selection.end);
 150                        }
 151                    })
 152                });
 153            }
 154        });
 155    });
 156}
 157
 158pub fn visual_block_motion(
 159    preserve_goal: bool,
 160    editor: &mut Editor,
 161    cx: &mut ViewContext<Editor>,
 162    mut move_selection: impl FnMut(
 163        &DisplaySnapshot,
 164        DisplayPoint,
 165        SelectionGoal,
 166    ) -> Option<(DisplayPoint, SelectionGoal)>,
 167) {
 168    let text_layout_details = editor.text_layout_details(cx);
 169    editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 170        let map = &s.display_map();
 171        let mut head = s.newest_anchor().head().to_display_point(map);
 172        let mut tail = s.oldest_anchor().tail().to_display_point(map);
 173
 174        let mut head_x = map.x_for_display_point(head, &text_layout_details);
 175        let mut tail_x = map.x_for_display_point(tail, &text_layout_details);
 176
 177        let (start, end) = match s.newest_anchor().goal {
 178            SelectionGoal::HorizontalRange { start, end } if preserve_goal => (start, end),
 179            SelectionGoal::HorizontalPosition(start) if preserve_goal => (start, start),
 180            _ => (tail_x.0, head_x.0),
 181        };
 182        let mut goal = SelectionGoal::HorizontalRange { start, end };
 183
 184        let was_reversed = tail_x > head_x;
 185        if !was_reversed && !preserve_goal {
 186            head = movement::saturating_left(map, head);
 187        }
 188
 189        let Some((new_head, _)) = move_selection(&map, head, goal) else {
 190            return;
 191        };
 192        head = new_head;
 193        head_x = map.x_for_display_point(head, &text_layout_details);
 194
 195        let is_reversed = tail_x > head_x;
 196        if was_reversed && !is_reversed {
 197            tail = movement::saturating_left(map, tail);
 198            tail_x = map.x_for_display_point(tail, &text_layout_details);
 199        } else if !was_reversed && is_reversed {
 200            tail = movement::saturating_right(map, tail);
 201            tail_x = map.x_for_display_point(tail, &text_layout_details);
 202        }
 203        if !is_reversed && !preserve_goal {
 204            head = movement::saturating_right(map, head);
 205            head_x = map.x_for_display_point(head, &text_layout_details);
 206        }
 207
 208        let positions = if is_reversed {
 209            head_x..tail_x
 210        } else {
 211            tail_x..head_x
 212        };
 213
 214        if !preserve_goal {
 215            goal = SelectionGoal::HorizontalRange {
 216                start: positions.start.0,
 217                end: positions.end.0,
 218            };
 219        }
 220
 221        let mut selections = Vec::new();
 222        let mut row = tail.row();
 223
 224        loop {
 225            let laid_out_line = map.layout_row(row, &text_layout_details);
 226            let start = DisplayPoint::new(
 227                row,
 228                laid_out_line.closest_index_for_x(positions.start) as u32,
 229            );
 230            let mut end =
 231                DisplayPoint::new(row, laid_out_line.closest_index_for_x(positions.end) as u32);
 232            if end <= start {
 233                if start.column() == map.line_len(start.row()) {
 234                    end = start;
 235                } else {
 236                    end = movement::saturating_right(map, start);
 237                }
 238            }
 239
 240            if positions.start <= laid_out_line.width {
 241                let selection = Selection {
 242                    id: s.new_selection_id(),
 243                    start: start.to_point(map),
 244                    end: end.to_point(map),
 245                    reversed: is_reversed,
 246                    goal,
 247                };
 248
 249                selections.push(selection);
 250            }
 251            if row == head.row() {
 252                break;
 253            }
 254            if tail.row() > head.row() {
 255                row.0 -= 1
 256            } else {
 257                row.0 += 1
 258            }
 259        }
 260
 261        s.select(selections);
 262    })
 263}
 264
 265pub fn visual_object(object: Object, cx: &mut WindowContext) {
 266    Vim::update(cx, |vim, cx| {
 267        if let Some(Operator::Object { around }) = vim.active_operator() {
 268            vim.pop_operator(cx);
 269            let current_mode = vim.state().mode;
 270            let target_mode = object.target_visual_mode(current_mode);
 271            if target_mode != current_mode {
 272                vim.switch_mode(target_mode, true, cx);
 273            }
 274
 275            vim.update_active_editor(cx, |_, editor, cx| {
 276                editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 277                    s.move_with(|map, selection| {
 278                        let mut mut_selection = selection.clone();
 279
 280                        // all our motions assume that the current character is
 281                        // after the cursor; however in the case of a visual selection
 282                        // the current character is before the cursor.
 283                        // But this will affect the judgment of the html tag
 284                        // so the html tag needs to skip this logic.
 285                        if !selection.reversed && object != Object::Tag {
 286                            mut_selection.set_head(
 287                                movement::left(map, mut_selection.head()),
 288                                mut_selection.goal,
 289                            );
 290                        }
 291
 292                        if let Some(range) = object.range(map, mut_selection, around) {
 293                            if !range.is_empty() {
 294                                let expand_both_ways = object.always_expands_both_ways()
 295                                    || selection.is_empty()
 296                                    || movement::right(map, selection.start) == selection.end;
 297
 298                                if expand_both_ways {
 299                                    selection.start = range.start;
 300                                    selection.end = range.end;
 301                                } else if selection.reversed {
 302                                    selection.start = range.start;
 303                                } else {
 304                                    selection.end = range.end;
 305                                }
 306                            }
 307
 308                            // In the visual selection result of a paragraph object, the cursor is
 309                            // placed at the start of the last line. And in the visual mode, the
 310                            // selection end is located after the end character. So, adjustment of
 311                            // selection end is needed.
 312                            //
 313                            // We don't do this adjustment for a one-line blank paragraph since the
 314                            // trailing newline is included in its selection from the beginning.
 315                            if object == Object::Paragraph && range.start != range.end {
 316                                let row_of_selection_end_line = selection.end.to_point(map).row;
 317                                let new_selection_end = if map
 318                                    .buffer_snapshot
 319                                    .line_len(MultiBufferRow(row_of_selection_end_line))
 320                                    == 0
 321                                {
 322                                    Point::new(row_of_selection_end_line + 1, 0)
 323                                } else {
 324                                    Point::new(row_of_selection_end_line, 1)
 325                                };
 326                                selection.end = new_selection_end.to_display_point(map);
 327                            }
 328                        }
 329                    });
 330                });
 331            });
 332        }
 333    });
 334}
 335
 336fn toggle_mode(mode: Mode, cx: &mut ViewContext<Workspace>) {
 337    Vim::update(cx, |vim, cx| {
 338        if vim.state().mode == mode {
 339            vim.switch_mode(Mode::Normal, false, cx);
 340        } else {
 341            vim.switch_mode(mode, false, cx);
 342        }
 343    })
 344}
 345
 346pub fn other_end(_: &mut Workspace, _: &OtherEnd, cx: &mut ViewContext<Workspace>) {
 347    Vim::update(cx, |vim, cx| {
 348        vim.update_active_editor(cx, |_, editor, cx| {
 349            editor.change_selections(None, cx, |s| {
 350                s.move_with(|_, selection| {
 351                    selection.reversed = !selection.reversed;
 352                })
 353            })
 354        })
 355    });
 356}
 357
 358pub fn delete(vim: &mut Vim, cx: &mut WindowContext) {
 359    vim.update_active_editor(cx, |vim, editor, cx| {
 360        let mut original_columns: HashMap<_, _> = Default::default();
 361        let line_mode = editor.selections.line_mode;
 362
 363        editor.transact(cx, |editor, cx| {
 364            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 365                s.move_with(|map, selection| {
 366                    if line_mode {
 367                        let mut position = selection.head();
 368                        if !selection.reversed {
 369                            position = movement::left(map, position);
 370                        }
 371                        original_columns.insert(selection.id, position.to_point(map).column);
 372                    }
 373                    selection.goal = SelectionGoal::None;
 374                });
 375            });
 376            copy_selections_content(vim, editor, line_mode, cx);
 377            editor.insert("", cx);
 378
 379            // Fixup cursor position after the deletion
 380            editor.set_clip_at_line_ends(true, cx);
 381            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 382                s.move_with(|map, selection| {
 383                    let mut cursor = selection.head().to_point(map);
 384
 385                    if let Some(column) = original_columns.get(&selection.id) {
 386                        cursor.column = *column
 387                    }
 388                    let cursor = map.clip_point(cursor.to_display_point(map), Bias::Left);
 389                    selection.collapse_to(cursor, selection.goal)
 390                });
 391                if vim.state().mode == Mode::VisualBlock {
 392                    s.select_anchors(vec![s.first_anchor()])
 393                }
 394            });
 395        })
 396    });
 397    vim.switch_mode(Mode::Normal, true, cx);
 398}
 399
 400pub fn yank(vim: &mut Vim, cx: &mut WindowContext) {
 401    vim.update_active_editor(cx, |vim, editor, cx| {
 402        let line_mode = editor.selections.line_mode;
 403        yank_selections_content(vim, editor, line_mode, cx);
 404        editor.change_selections(None, cx, |s| {
 405            s.move_with(|map, selection| {
 406                if line_mode {
 407                    selection.start = start_of_line(map, false, selection.start);
 408                };
 409                selection.collapse_to(selection.start, SelectionGoal::None)
 410            });
 411            if vim.state().mode == Mode::VisualBlock {
 412                s.select_anchors(vec![s.first_anchor()])
 413            }
 414        });
 415    });
 416    vim.switch_mode(Mode::Normal, true, cx);
 417}
 418
 419pub(crate) fn visual_replace(text: Arc<str>, cx: &mut WindowContext) {
 420    Vim::update(cx, |vim, cx| {
 421        vim.stop_recording();
 422        vim.update_active_editor(cx, |_, editor, cx| {
 423            editor.transact(cx, |editor, cx| {
 424                let (display_map, selections) = editor.selections.all_adjusted_display(cx);
 425
 426                // Selections are biased right at the start. So we need to store
 427                // anchors that are biased left so that we can restore the selections
 428                // after the change
 429                let stable_anchors = editor
 430                    .selections
 431                    .disjoint_anchors()
 432                    .into_iter()
 433                    .map(|selection| {
 434                        let start = selection.start.bias_left(&display_map.buffer_snapshot);
 435                        start..start
 436                    })
 437                    .collect::<Vec<_>>();
 438
 439                let mut edits = Vec::new();
 440                for selection in selections.iter() {
 441                    let selection = selection.clone();
 442                    for row_range in
 443                        movement::split_display_range_by_lines(&display_map, selection.range())
 444                    {
 445                        let range = row_range.start.to_offset(&display_map, Bias::Right)
 446                            ..row_range.end.to_offset(&display_map, Bias::Right);
 447                        let text = text.repeat(range.len());
 448                        edits.push((range, text));
 449                    }
 450                }
 451
 452                editor.buffer().update(cx, |buffer, cx| {
 453                    buffer.edit(edits, None, cx);
 454                });
 455                editor.change_selections(None, cx, |s| s.select_ranges(stable_anchors));
 456            });
 457        });
 458        vim.switch_mode(Mode::Normal, false, cx);
 459    });
 460}
 461
 462pub fn select_next(_: &mut Workspace, _: &SelectNext, cx: &mut ViewContext<Workspace>) {
 463    Vim::update(cx, |vim, cx| {
 464        let count =
 465            vim.take_count(cx)
 466                .unwrap_or_else(|| if vim.state().mode.is_visual() { 1 } else { 2 });
 467        vim.update_active_editor(cx, |_, editor, cx| {
 468            for _ in 0..count {
 469                if editor
 470                    .select_next(&Default::default(), cx)
 471                    .log_err()
 472                    .is_none()
 473                {
 474                    break;
 475                }
 476            }
 477        })
 478    });
 479}
 480
 481pub fn select_previous(_: &mut Workspace, _: &SelectPrevious, cx: &mut ViewContext<Workspace>) {
 482    Vim::update(cx, |vim, cx| {
 483        let count =
 484            vim.take_count(cx)
 485                .unwrap_or_else(|| if vim.state().mode.is_visual() { 1 } else { 2 });
 486        vim.update_active_editor(cx, |_, editor, cx| {
 487            for _ in 0..count {
 488                if editor
 489                    .select_previous(&Default::default(), cx)
 490                    .log_err()
 491                    .is_none()
 492                {
 493                    break;
 494                }
 495            }
 496        })
 497    });
 498}
 499
 500pub fn select_match(
 501    workspace: &mut Workspace,
 502    vim: &mut Vim,
 503    direction: Direction,
 504    cx: &mut WindowContext,
 505) {
 506    let count = vim.take_count(cx).unwrap_or(1);
 507    let pane = workspace.active_pane().clone();
 508    let vim_is_normal = vim.state().mode == Mode::Normal;
 509    let mut start_selection = 0usize;
 510    let mut end_selection = 0usize;
 511
 512    vim.update_active_editor(cx, |_, editor, _| {
 513        editor.set_collapse_matches(false);
 514    });
 515    if vim_is_normal {
 516        pane.update(cx, |pane, cx| {
 517            if let Some(search_bar) = pane.toolbar().read(cx).item_of_type::<BufferSearchBar>() {
 518                search_bar.update(cx, |search_bar, cx| {
 519                    // without update_match_index there is a bug when the cursor is before the first match
 520                    search_bar.update_match_index(cx);
 521                    search_bar.select_match(direction.opposite(), 1, cx);
 522                });
 523            }
 524        });
 525    }
 526    vim.update_active_editor(cx, |_, editor, cx| {
 527        let latest = editor.selections.newest::<usize>(cx);
 528        start_selection = latest.start;
 529        end_selection = latest.end;
 530    });
 531
 532    let mut match_exists = false;
 533    pane.update(cx, |pane, cx| {
 534        if let Some(search_bar) = pane.toolbar().read(cx).item_of_type::<BufferSearchBar>() {
 535            search_bar.update(cx, |search_bar, cx| {
 536                search_bar.update_match_index(cx);
 537                search_bar.select_match(direction, count, cx);
 538                match_exists = search_bar.match_exists(cx);
 539            });
 540        }
 541    });
 542    if !match_exists {
 543        vim.clear_operator(cx);
 544        vim.stop_replaying();
 545        return;
 546    }
 547    vim.update_active_editor(cx, |_, editor, cx| {
 548        let latest = editor.selections.newest::<usize>(cx);
 549        if vim_is_normal {
 550            start_selection = latest.start;
 551            end_selection = latest.end;
 552        } else {
 553            start_selection = start_selection.min(latest.start);
 554            end_selection = end_selection.max(latest.end);
 555        }
 556        if direction == Direction::Prev {
 557            std::mem::swap(&mut start_selection, &mut end_selection);
 558        }
 559        editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 560            s.select_ranges([start_selection..end_selection]);
 561        });
 562        editor.set_collapse_matches(true);
 563    });
 564
 565    match vim.maybe_pop_operator() {
 566        Some(Operator::Change) => substitute(vim, None, false, cx),
 567        Some(Operator::Delete) => {
 568            vim.stop_recording();
 569            delete(vim, cx)
 570        }
 571        Some(Operator::Yank) => yank(vim, cx),
 572        _ => {} // Ignoring other operators
 573    }
 574}
 575
 576#[cfg(test)]
 577mod test {
 578    use indoc::indoc;
 579    use workspace::item::Item;
 580
 581    use crate::{
 582        state::Mode,
 583        test::{NeovimBackedTestContext, VimTestContext},
 584    };
 585
 586    #[gpui::test]
 587    async fn test_enter_visual_mode(cx: &mut gpui::TestAppContext) {
 588        let mut cx = NeovimBackedTestContext::new(cx).await;
 589
 590        cx.set_shared_state(indoc! {
 591            "The ˇquick brown
 592            fox jumps over
 593            the lazy dog"
 594        })
 595        .await;
 596        let cursor = cx.update_editor(|editor, cx| editor.pixel_position_of_cursor(cx));
 597
 598        // entering visual mode should select the character
 599        // under cursor
 600        cx.simulate_shared_keystrokes("v").await;
 601        cx.shared_state()
 602            .await
 603            .assert_eq(indoc! { "The «qˇ»uick brown
 604            fox jumps over
 605            the lazy dog"});
 606        cx.update_editor(|editor, cx| assert_eq!(cursor, editor.pixel_position_of_cursor(cx)));
 607
 608        // forwards motions should extend the selection
 609        cx.simulate_shared_keystrokes("w j").await;
 610        cx.shared_state().await.assert_eq(indoc! { "The «quick brown
 611            fox jumps oˇ»ver
 612            the lazy dog"});
 613
 614        cx.simulate_shared_keystrokes("escape").await;
 615        cx.shared_state().await.assert_eq(indoc! { "The quick brown
 616            fox jumps ˇover
 617            the lazy dog"});
 618
 619        // motions work backwards
 620        cx.simulate_shared_keystrokes("v k b").await;
 621        cx.shared_state()
 622            .await
 623            .assert_eq(indoc! { "The «ˇquick brown
 624            fox jumps o»ver
 625            the lazy dog"});
 626
 627        // works on empty lines
 628        cx.set_shared_state(indoc! {"
 629            a
 630            ˇ
 631            b
 632            "})
 633            .await;
 634        let cursor = cx.update_editor(|editor, cx| editor.pixel_position_of_cursor(cx));
 635        cx.simulate_shared_keystrokes("v").await;
 636        cx.shared_state().await.assert_eq(indoc! {"
 637            a
 638            «
 639            ˇ»b
 640        "});
 641        cx.update_editor(|editor, cx| assert_eq!(cursor, editor.pixel_position_of_cursor(cx)));
 642
 643        // toggles off again
 644        cx.simulate_shared_keystrokes("v").await;
 645        cx.shared_state().await.assert_eq(indoc! {"
 646            a
 647            ˇ
 648            b
 649            "});
 650
 651        // works at the end of a document
 652        cx.set_shared_state(indoc! {"
 653            a
 654            b
 655            ˇ"})
 656            .await;
 657
 658        cx.simulate_shared_keystrokes("v").await;
 659        cx.shared_state().await.assert_eq(indoc! {"
 660            a
 661            b
 662            ˇ"});
 663    }
 664
 665    #[gpui::test]
 666    async fn test_enter_visual_line_mode(cx: &mut gpui::TestAppContext) {
 667        let mut cx = NeovimBackedTestContext::new(cx).await;
 668
 669        cx.set_shared_state(indoc! {
 670            "The ˇquick brown
 671            fox jumps over
 672            the lazy dog"
 673        })
 674        .await;
 675        cx.simulate_shared_keystrokes("shift-v").await;
 676        cx.shared_state()
 677            .await
 678            .assert_eq(indoc! { "The «qˇ»uick brown
 679            fox jumps over
 680            the lazy dog"});
 681        cx.simulate_shared_keystrokes("x").await;
 682        cx.shared_state().await.assert_eq(indoc! { "fox ˇjumps over
 683        the lazy dog"});
 684
 685        // it should work on empty lines
 686        cx.set_shared_state(indoc! {"
 687            a
 688            ˇ
 689            b"})
 690            .await;
 691        cx.simulate_shared_keystrokes("shift-v").await;
 692        cx.shared_state().await.assert_eq(indoc! {"
 693            a
 694            «
 695            ˇ»b"});
 696        cx.simulate_shared_keystrokes("x").await;
 697        cx.shared_state().await.assert_eq(indoc! {"
 698            a
 699            ˇb"});
 700
 701        // it should work at the end of the document
 702        cx.set_shared_state(indoc! {"
 703            a
 704            b
 705            ˇ"})
 706            .await;
 707        let cursor = cx.update_editor(|editor, cx| editor.pixel_position_of_cursor(cx));
 708        cx.simulate_shared_keystrokes("shift-v").await;
 709        cx.shared_state().await.assert_eq(indoc! {"
 710            a
 711            b
 712            ˇ"});
 713        cx.update_editor(|editor, cx| assert_eq!(cursor, editor.pixel_position_of_cursor(cx)));
 714        cx.simulate_shared_keystrokes("x").await;
 715        cx.shared_state().await.assert_eq(indoc! {"
 716            a
 717            ˇb"});
 718    }
 719
 720    #[gpui::test]
 721    async fn test_visual_delete(cx: &mut gpui::TestAppContext) {
 722        let mut cx = NeovimBackedTestContext::new(cx).await;
 723
 724        cx.simulate("v w", "The quick ˇbrown")
 725            .await
 726            .assert_matches();
 727
 728        cx.simulate("v w x", "The quick ˇbrown")
 729            .await
 730            .assert_matches();
 731        cx.simulate(
 732            "v w j x",
 733            indoc! {"
 734                The ˇquick brown
 735                fox jumps over
 736                the lazy dog"},
 737        )
 738        .await
 739        .assert_matches();
 740        // Test pasting code copied on delete
 741        cx.simulate_shared_keystrokes("j p").await;
 742        cx.shared_state().await.assert_matches();
 743
 744        cx.simulate_at_each_offset(
 745            "v w j x",
 746            indoc! {"
 747                The ˇquick brown
 748                fox jumps over
 749                the ˇlazy dog"},
 750        )
 751        .await
 752        .assert_matches();
 753        cx.simulate_at_each_offset(
 754            "v b k x",
 755            indoc! {"
 756                The ˇquick brown
 757                fox jumps ˇover
 758                the ˇlazy dog"},
 759        )
 760        .await
 761        .assert_matches();
 762    }
 763
 764    #[gpui::test]
 765    async fn test_visual_line_delete(cx: &mut gpui::TestAppContext) {
 766        let mut cx = NeovimBackedTestContext::new(cx).await;
 767
 768        cx.set_shared_state(indoc! {"
 769                The quˇick brown
 770                fox jumps over
 771                the lazy dog"})
 772            .await;
 773        cx.simulate_shared_keystrokes("shift-v x").await;
 774        cx.shared_state().await.assert_matches();
 775
 776        // Test pasting code copied on delete
 777        cx.simulate_shared_keystrokes("p").await;
 778        cx.shared_state().await.assert_matches();
 779
 780        cx.set_shared_state(indoc! {"
 781                The quick brown
 782                fox jumps over
 783                the laˇzy dog"})
 784            .await;
 785        cx.simulate_shared_keystrokes("shift-v x").await;
 786        cx.shared_state().await.assert_matches();
 787        cx.shared_clipboard().await.assert_eq("the lazy dog\n");
 788
 789        cx.set_shared_state(indoc! {"
 790                                The quˇick brown
 791                                fox jumps over
 792                                the lazy dog"})
 793            .await;
 794        cx.simulate_shared_keystrokes("shift-v j x").await;
 795        cx.shared_state().await.assert_matches();
 796        // Test pasting code copied on delete
 797        cx.simulate_shared_keystrokes("p").await;
 798        cx.shared_state().await.assert_matches();
 799
 800        cx.set_shared_state(indoc! {"
 801            The ˇlong line
 802            should not
 803            crash
 804            "})
 805            .await;
 806        cx.simulate_shared_keystrokes("shift-v $ x").await;
 807        cx.shared_state().await.assert_matches();
 808    }
 809
 810    #[gpui::test]
 811    async fn test_visual_yank(cx: &mut gpui::TestAppContext) {
 812        let mut cx = NeovimBackedTestContext::new(cx).await;
 813
 814        cx.set_shared_state("The quick ˇbrown").await;
 815        cx.simulate_shared_keystrokes("v w y").await;
 816        cx.shared_state().await.assert_eq("The quick ˇbrown");
 817        cx.shared_clipboard().await.assert_eq("brown");
 818
 819        cx.set_shared_state(indoc! {"
 820                The ˇquick brown
 821                fox jumps over
 822                the lazy dog"})
 823            .await;
 824        cx.simulate_shared_keystrokes("v w j y").await;
 825        cx.shared_state().await.assert_eq(indoc! {"
 826                    The ˇquick brown
 827                    fox jumps over
 828                    the lazy dog"});
 829        cx.shared_clipboard().await.assert_eq(indoc! {"
 830                quick brown
 831                fox jumps o"});
 832
 833        cx.set_shared_state(indoc! {"
 834                    The quick brown
 835                    fox jumps over
 836                    the ˇlazy dog"})
 837            .await;
 838        cx.simulate_shared_keystrokes("v w j y").await;
 839        cx.shared_state().await.assert_eq(indoc! {"
 840                    The quick brown
 841                    fox jumps over
 842                    the ˇlazy dog"});
 843        cx.shared_clipboard().await.assert_eq("lazy d");
 844        cx.simulate_shared_keystrokes("shift-v y").await;
 845        cx.shared_clipboard().await.assert_eq("the lazy dog\n");
 846
 847        cx.set_shared_state(indoc! {"
 848                    The ˇquick brown
 849                    fox jumps over
 850                    the lazy dog"})
 851            .await;
 852        cx.simulate_shared_keystrokes("v b k y").await;
 853        cx.shared_state().await.assert_eq(indoc! {"
 854                    ˇThe quick brown
 855                    fox jumps over
 856                    the lazy dog"});
 857        assert_eq!(
 858            cx.read_from_clipboard()
 859                .map(|item| item.text().clone())
 860                .unwrap(),
 861            "The q"
 862        );
 863
 864        cx.set_shared_state(indoc! {"
 865                    The quick brown
 866                    fox ˇjumps over
 867                    the lazy dog"})
 868            .await;
 869        cx.simulate_shared_keystrokes("shift-v shift-g shift-y")
 870            .await;
 871        cx.shared_state().await.assert_eq(indoc! {"
 872                    The quick brown
 873                    ˇfox jumps over
 874                    the lazy dog"});
 875        cx.shared_clipboard()
 876            .await
 877            .assert_eq("fox jumps over\nthe lazy dog\n");
 878    }
 879
 880    #[gpui::test]
 881    async fn test_visual_block_mode(cx: &mut gpui::TestAppContext) {
 882        let mut cx = NeovimBackedTestContext::new(cx).await;
 883
 884        cx.set_shared_state(indoc! {
 885            "The ˇquick brown
 886             fox jumps over
 887             the lazy dog"
 888        })
 889        .await;
 890        cx.simulate_shared_keystrokes("ctrl-v").await;
 891        cx.shared_state().await.assert_eq(indoc! {
 892            "The «qˇ»uick brown
 893            fox jumps over
 894            the lazy dog"
 895        });
 896        cx.simulate_shared_keystrokes("2 down").await;
 897        cx.shared_state().await.assert_eq(indoc! {
 898            "The «qˇ»uick brown
 899            fox «jˇ»umps over
 900            the «lˇ»azy dog"
 901        });
 902        cx.simulate_shared_keystrokes("e").await;
 903        cx.shared_state().await.assert_eq(indoc! {
 904            "The «quicˇ»k brown
 905            fox «jumpˇ»s over
 906            the «lazyˇ» dog"
 907        });
 908        cx.simulate_shared_keystrokes("^").await;
 909        cx.shared_state().await.assert_eq(indoc! {
 910            "«ˇThe q»uick brown
 911            «ˇfox j»umps over
 912            «ˇthe l»azy dog"
 913        });
 914        cx.simulate_shared_keystrokes("$").await;
 915        cx.shared_state().await.assert_eq(indoc! {
 916            "The «quick brownˇ»
 917            fox «jumps overˇ»
 918            the «lazy dogˇ»"
 919        });
 920        cx.simulate_shared_keystrokes("shift-f space").await;
 921        cx.shared_state().await.assert_eq(indoc! {
 922            "The «quickˇ» brown
 923            fox «jumpsˇ» over
 924            the «lazy ˇ»dog"
 925        });
 926
 927        // toggling through visual mode works as expected
 928        cx.simulate_shared_keystrokes("v").await;
 929        cx.shared_state().await.assert_eq(indoc! {
 930            "The «quick brown
 931            fox jumps over
 932            the lazy ˇ»dog"
 933        });
 934        cx.simulate_shared_keystrokes("ctrl-v").await;
 935        cx.shared_state().await.assert_eq(indoc! {
 936            "The «quickˇ» brown
 937            fox «jumpsˇ» over
 938            the «lazy ˇ»dog"
 939        });
 940
 941        cx.set_shared_state(indoc! {
 942            "The ˇquick
 943             brown
 944             fox
 945             jumps over the
 946
 947             lazy dog
 948            "
 949        })
 950        .await;
 951        cx.simulate_shared_keystrokes("ctrl-v down down").await;
 952        cx.shared_state().await.assert_eq(indoc! {
 953            "The«ˇ q»uick
 954            bro«ˇwn»
 955            foxˇ
 956            jumps over the
 957
 958            lazy dog
 959            "
 960        });
 961        cx.simulate_shared_keystrokes("down").await;
 962        cx.shared_state().await.assert_eq(indoc! {
 963            "The «qˇ»uick
 964            brow«nˇ»
 965            fox
 966            jump«sˇ» over the
 967
 968            lazy dog
 969            "
 970        });
 971        cx.simulate_shared_keystrokes("left").await;
 972        cx.shared_state().await.assert_eq(indoc! {
 973            "The«ˇ q»uick
 974            bro«ˇwn»
 975            foxˇ
 976            jum«ˇps» over the
 977
 978            lazy dog
 979            "
 980        });
 981        cx.simulate_shared_keystrokes("s o escape").await;
 982        cx.shared_state().await.assert_eq(indoc! {
 983            "Theˇouick
 984            broo
 985            foxo
 986            jumo over the
 987
 988            lazy dog
 989            "
 990        });
 991
 992        // https://github.com/zed-industries/zed/issues/6274
 993        cx.set_shared_state(indoc! {
 994            "Theˇ quick brown
 995
 996            fox jumps over
 997            the lazy dog
 998            "
 999        })
1000        .await;
1001        cx.simulate_shared_keystrokes("l ctrl-v j j").await;
1002        cx.shared_state().await.assert_eq(indoc! {
1003            "The «qˇ»uick brown
1004
1005            fox «jˇ»umps over
1006            the lazy dog
1007            "
1008        });
1009    }
1010
1011    #[gpui::test]
1012    async fn test_visual_block_issue_2123(cx: &mut gpui::TestAppContext) {
1013        let mut cx = NeovimBackedTestContext::new(cx).await;
1014
1015        cx.set_shared_state(indoc! {
1016            "The ˇquick brown
1017            fox jumps over
1018            the lazy dog
1019            "
1020        })
1021        .await;
1022        cx.simulate_shared_keystrokes("ctrl-v right down").await;
1023        cx.shared_state().await.assert_eq(indoc! {
1024            "The «quˇ»ick brown
1025            fox «juˇ»mps over
1026            the lazy dog
1027            "
1028        });
1029    }
1030
1031    #[gpui::test]
1032    async fn test_visual_block_insert(cx: &mut gpui::TestAppContext) {
1033        let mut cx = NeovimBackedTestContext::new(cx).await;
1034
1035        cx.set_shared_state(indoc! {
1036            "ˇThe quick brown
1037            fox jumps over
1038            the lazy dog
1039            "
1040        })
1041        .await;
1042        cx.simulate_shared_keystrokes("ctrl-v 9 down").await;
1043        cx.shared_state().await.assert_eq(indoc! {
1044            "«Tˇ»he quick brown
1045            «fˇ»ox jumps over
1046            «tˇ»he lazy dog
1047            ˇ"
1048        });
1049
1050        cx.simulate_shared_keystrokes("shift-i k escape").await;
1051        cx.shared_state().await.assert_eq(indoc! {
1052            "ˇkThe quick brown
1053            kfox jumps over
1054            kthe lazy dog
1055            k"
1056        });
1057
1058        cx.set_shared_state(indoc! {
1059            "ˇThe quick brown
1060            fox jumps over
1061            the lazy dog
1062            "
1063        })
1064        .await;
1065        cx.simulate_shared_keystrokes("ctrl-v 9 down").await;
1066        cx.shared_state().await.assert_eq(indoc! {
1067            "«Tˇ»he quick brown
1068            «fˇ»ox jumps over
1069            «tˇ»he lazy dog
1070            ˇ"
1071        });
1072        cx.simulate_shared_keystrokes("c k escape").await;
1073        cx.shared_state().await.assert_eq(indoc! {
1074            "ˇkhe quick brown
1075            kox jumps over
1076            khe lazy dog
1077            k"
1078        });
1079    }
1080
1081    #[gpui::test]
1082    async fn test_visual_object(cx: &mut gpui::TestAppContext) {
1083        let mut cx = NeovimBackedTestContext::new(cx).await;
1084
1085        cx.set_shared_state("hello (in [parˇens] o)").await;
1086        cx.simulate_shared_keystrokes("ctrl-v l").await;
1087        cx.simulate_shared_keystrokes("a ]").await;
1088        cx.shared_state()
1089            .await
1090            .assert_eq("hello (in «[parens]ˇ» o)");
1091        cx.simulate_shared_keystrokes("i (").await;
1092        cx.shared_state()
1093            .await
1094            .assert_eq("hello («in [parens] oˇ»)");
1095
1096        cx.set_shared_state("hello in a wˇord again.").await;
1097        cx.simulate_shared_keystrokes("ctrl-v l i w").await;
1098        cx.shared_state()
1099            .await
1100            .assert_eq("hello in a w«ordˇ» again.");
1101        assert_eq!(cx.mode(), Mode::VisualBlock);
1102        cx.simulate_shared_keystrokes("o a s").await;
1103        cx.shared_state()
1104            .await
1105            .assert_eq("«ˇhello in a word» again.");
1106    }
1107
1108    #[gpui::test]
1109    async fn test_mode_across_command(cx: &mut gpui::TestAppContext) {
1110        let mut cx = VimTestContext::new(cx, true).await;
1111
1112        cx.set_state("aˇbc", Mode::Normal);
1113        cx.simulate_keystrokes("ctrl-v");
1114        assert_eq!(cx.mode(), Mode::VisualBlock);
1115        cx.simulate_keystrokes("cmd-shift-p escape");
1116        assert_eq!(cx.mode(), Mode::VisualBlock);
1117    }
1118
1119    #[gpui::test]
1120    async fn test_gn(cx: &mut gpui::TestAppContext) {
1121        let mut cx = NeovimBackedTestContext::new(cx).await;
1122
1123        cx.set_shared_state("aaˇ aa aa aa aa").await;
1124        cx.simulate_shared_keystrokes("/ a a enter").await;
1125        cx.shared_state().await.assert_eq("aa ˇaa aa aa aa");
1126        cx.simulate_shared_keystrokes("g n").await;
1127        cx.shared_state().await.assert_eq("aa «aaˇ» aa aa aa");
1128        cx.simulate_shared_keystrokes("g n").await;
1129        cx.shared_state().await.assert_eq("aa «aa aaˇ» aa aa");
1130        cx.simulate_shared_keystrokes("escape d g n").await;
1131        cx.shared_state().await.assert_eq("aa aa ˇ aa aa");
1132
1133        cx.set_shared_state("aaˇ aa aa aa aa").await;
1134        cx.simulate_shared_keystrokes("/ a a enter").await;
1135        cx.shared_state().await.assert_eq("aa ˇaa aa aa aa");
1136        cx.simulate_shared_keystrokes("3 g n").await;
1137        cx.shared_state().await.assert_eq("aa aa aa «aaˇ» aa");
1138
1139        cx.set_shared_state("aaˇ aa aa aa aa").await;
1140        cx.simulate_shared_keystrokes("/ a a enter").await;
1141        cx.shared_state().await.assert_eq("aa ˇaa aa aa aa");
1142        cx.simulate_shared_keystrokes("g shift-n").await;
1143        cx.shared_state().await.assert_eq("aa «ˇaa» aa aa aa");
1144        cx.simulate_shared_keystrokes("g shift-n").await;
1145        cx.shared_state().await.assert_eq("«ˇaa aa» aa aa aa");
1146    }
1147
1148    #[gpui::test]
1149    async fn test_dgn_repeat(cx: &mut gpui::TestAppContext) {
1150        let mut cx = NeovimBackedTestContext::new(cx).await;
1151
1152        cx.set_shared_state("aaˇ aa aa aa aa").await;
1153        cx.simulate_shared_keystrokes("/ a a enter").await;
1154        cx.shared_state().await.assert_eq("aa ˇaa aa aa aa");
1155        cx.simulate_shared_keystrokes("d g n").await;
1156
1157        cx.shared_state().await.assert_eq("aa ˇ aa aa aa");
1158        cx.simulate_shared_keystrokes(".").await;
1159        cx.shared_state().await.assert_eq("aa  ˇ aa aa");
1160        cx.simulate_shared_keystrokes(".").await;
1161        cx.shared_state().await.assert_eq("aa   ˇ aa");
1162    }
1163
1164    #[gpui::test]
1165    async fn test_cgn_repeat(cx: &mut gpui::TestAppContext) {
1166        let mut cx = NeovimBackedTestContext::new(cx).await;
1167
1168        cx.set_shared_state("aaˇ aa aa aa aa").await;
1169        cx.simulate_shared_keystrokes("/ a a enter").await;
1170        cx.shared_state().await.assert_eq("aa ˇaa aa aa aa");
1171        cx.simulate_shared_keystrokes("c g n x escape").await;
1172        cx.shared_state().await.assert_eq("aa ˇx aa aa aa");
1173        cx.simulate_shared_keystrokes(".").await;
1174        cx.shared_state().await.assert_eq("aa x ˇx aa aa");
1175    }
1176
1177    #[gpui::test]
1178    async fn test_cgn_nomatch(cx: &mut gpui::TestAppContext) {
1179        let mut cx = NeovimBackedTestContext::new(cx).await;
1180
1181        cx.set_shared_state("aaˇ aa aa aa aa").await;
1182        cx.simulate_shared_keystrokes("/ b b enter").await;
1183        cx.shared_state().await.assert_eq("aaˇ aa aa aa aa");
1184        cx.simulate_shared_keystrokes("c g n x escape").await;
1185        cx.shared_state().await.assert_eq("aaˇaa aa aa aa");
1186        cx.simulate_shared_keystrokes(".").await;
1187        cx.shared_state().await.assert_eq("aaˇa aa aa aa");
1188
1189        cx.set_shared_state("aaˇ bb aa aa aa").await;
1190        cx.simulate_shared_keystrokes("/ b b enter").await;
1191        cx.shared_state().await.assert_eq("aa ˇbb aa aa aa");
1192        cx.simulate_shared_keystrokes("c g n x escape").await;
1193        cx.shared_state().await.assert_eq("aa ˇx aa aa aa");
1194        cx.simulate_shared_keystrokes(".").await;
1195        cx.shared_state().await.assert_eq("aa ˇx aa aa aa");
1196    }
1197}