search.rs

  1use std::{iter::Peekable, str::Chars, time::Duration};
  2
  3use editor::Editor;
  4use gpui::{actions, impl_actions, ViewContext};
  5use language::Point;
  6use search::{buffer_search, BufferSearchBar, SearchOptions};
  7use serde_derive::Deserialize;
  8use workspace::{notifications::NotifyResultExt, searchable::Direction};
  9
 10use crate::{
 11    command::CommandRange,
 12    motion::Motion,
 13    state::{Mode, SearchState},
 14    Vim,
 15};
 16
 17#[derive(Clone, Deserialize, PartialEq)]
 18#[serde(rename_all = "camelCase")]
 19pub(crate) struct MoveToNext {
 20    #[serde(default)]
 21    partial_word: bool,
 22}
 23
 24#[derive(Clone, Deserialize, PartialEq)]
 25#[serde(rename_all = "camelCase")]
 26pub(crate) struct MoveToPrev {
 27    #[serde(default)]
 28    partial_word: bool,
 29}
 30
 31#[derive(Clone, Deserialize, PartialEq)]
 32pub(crate) struct Search {
 33    #[serde(default)]
 34    backwards: bool,
 35}
 36
 37#[derive(Debug, Clone, PartialEq, Deserialize)]
 38pub struct FindCommand {
 39    pub query: String,
 40    pub backwards: bool,
 41}
 42
 43#[derive(Debug, Clone, PartialEq, Deserialize)]
 44pub struct ReplaceCommand {
 45    pub(crate) range: Option<CommandRange>,
 46    pub(crate) replacement: Replacement,
 47}
 48
 49#[derive(Debug, Default, PartialEq, Deserialize, Clone)]
 50pub(crate) struct Replacement {
 51    search: String,
 52    replacement: String,
 53    should_replace_all: bool,
 54    is_case_sensitive: bool,
 55}
 56
 57actions!(vim, [SearchSubmit, MoveToNextMatch, MoveToPrevMatch]);
 58impl_actions!(
 59    vim,
 60    [FindCommand, ReplaceCommand, Search, MoveToPrev, MoveToNext]
 61);
 62
 63pub(crate) fn register(editor: &mut Editor, cx: &mut ViewContext<Vim>) {
 64    Vim::action(editor, cx, Vim::move_to_next);
 65    Vim::action(editor, cx, Vim::move_to_prev);
 66    Vim::action(editor, cx, Vim::move_to_next_match);
 67    Vim::action(editor, cx, Vim::move_to_prev_match);
 68    Vim::action(editor, cx, Vim::search);
 69    Vim::action(editor, cx, Vim::search_deploy);
 70    Vim::action(editor, cx, Vim::find_command);
 71    Vim::action(editor, cx, Vim::replace_command);
 72}
 73
 74impl Vim {
 75    fn move_to_next(&mut self, action: &MoveToNext, cx: &mut ViewContext<Self>) {
 76        self.move_to_internal(Direction::Next, !action.partial_word, cx)
 77    }
 78
 79    fn move_to_prev(&mut self, action: &MoveToPrev, cx: &mut ViewContext<Self>) {
 80        self.move_to_internal(Direction::Prev, !action.partial_word, cx)
 81    }
 82
 83    fn move_to_next_match(&mut self, _: &MoveToNextMatch, cx: &mut ViewContext<Self>) {
 84        self.move_to_match_internal(Direction::Next, cx)
 85    }
 86
 87    fn move_to_prev_match(&mut self, _: &MoveToPrevMatch, cx: &mut ViewContext<Self>) {
 88        self.move_to_match_internal(Direction::Prev, cx)
 89    }
 90
 91    fn search(&mut self, action: &Search, cx: &mut ViewContext<Self>) {
 92        let Some(pane) = self.pane(cx) else { return };
 93        let direction = if action.backwards {
 94            Direction::Prev
 95        } else {
 96            Direction::Next
 97        };
 98        let count = self.take_count(cx).unwrap_or(1);
 99        let prior_selections = self.editor_selections(cx);
100        pane.update(cx, |pane, cx| {
101            if let Some(search_bar) = pane.toolbar().read(cx).item_of_type::<BufferSearchBar>() {
102                search_bar.update(cx, |search_bar, cx| {
103                    if !search_bar.show(cx) {
104                        return;
105                    }
106                    let query = search_bar.query(cx);
107
108                    search_bar.select_query(cx);
109                    cx.focus_self();
110
111                    if query.is_empty() {
112                        search_bar.set_replacement(None, cx);
113                        search_bar.set_search_options(SearchOptions::REGEX, cx);
114                    }
115                    self.search = SearchState {
116                        direction,
117                        count,
118                        initial_query: query.clone(),
119                        prior_selections,
120                        prior_operator: self.operator_stack.last().cloned(),
121                        prior_mode: self.mode,
122                    }
123                });
124            }
125        })
126    }
127
128    // hook into the existing to clear out any vim search state on cmd+f or edit -> find.
129    fn search_deploy(&mut self, _: &buffer_search::Deploy, cx: &mut ViewContext<Self>) {
130        self.search = Default::default();
131        cx.propagate();
132    }
133
134    pub fn search_submit(&mut self, cx: &mut ViewContext<Self>) {
135        self.store_visual_marks(cx);
136        let Some(pane) = self.pane(cx) else { return };
137        let result = pane.update(cx, |pane, cx| {
138            let Some(search_bar) = pane.toolbar().read(cx).item_of_type::<BufferSearchBar>() else {
139                return None;
140            };
141            search_bar.update(cx, |search_bar, cx| {
142                let mut count = self.search.count;
143                let direction = self.search.direction;
144                // in the case that the query has changed, the search bar
145                // will have selected the next match already.
146                if (search_bar.query(cx) != self.search.initial_query)
147                    && self.search.direction == Direction::Next
148                {
149                    count = count.saturating_sub(1)
150                }
151                self.search.count = 1;
152                search_bar.select_match(direction, count, cx);
153                search_bar.focus_editor(&Default::default(), cx);
154
155                let prior_selections: Vec<_> = self.search.prior_selections.drain(..).collect();
156                let prior_mode = self.search.prior_mode;
157                let prior_operator = self.search.prior_operator.take();
158
159                let query = search_bar.query(cx).into();
160                Vim::globals(cx).registers.insert('/', query);
161                Some((prior_selections, prior_mode, prior_operator))
162            })
163        });
164
165        let Some((mut prior_selections, prior_mode, prior_operator)) = result else {
166            return;
167        };
168
169        let new_selections = self.editor_selections(cx);
170
171        // If the active editor has changed during a search, don't panic.
172        if prior_selections.iter().any(|s| {
173            self.update_editor(cx, |_, editor, cx| {
174                !s.start.is_valid(&editor.snapshot(cx).buffer_snapshot)
175            })
176            .unwrap_or(true)
177        }) {
178            prior_selections.clear();
179        }
180
181        if prior_mode != self.mode {
182            self.switch_mode(prior_mode, true, cx);
183        }
184        if let Some(operator) = prior_operator {
185            self.push_operator(operator, cx);
186        };
187        self.search_motion(
188            Motion::ZedSearchResult {
189                prior_selections,
190                new_selections,
191            },
192            cx,
193        );
194    }
195
196    pub fn move_to_match_internal(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
197        let Some(pane) = self.pane(cx) else { return };
198        let count = self.take_count(cx).unwrap_or(1);
199        let prior_selections = self.editor_selections(cx);
200
201        let success = pane.update(cx, |pane, cx| {
202            let Some(search_bar) = pane.toolbar().read(cx).item_of_type::<BufferSearchBar>() else {
203                return false;
204            };
205            search_bar.update(cx, |search_bar, cx| {
206                if !search_bar.has_active_match() || !search_bar.show(cx) {
207                    return false;
208                }
209                search_bar.select_match(direction, count, cx);
210                true
211            })
212        });
213        if !success {
214            return;
215        }
216
217        let new_selections = self.editor_selections(cx);
218        self.search_motion(
219            Motion::ZedSearchResult {
220                prior_selections,
221                new_selections,
222            },
223            cx,
224        );
225    }
226
227    pub fn move_to_internal(
228        &mut self,
229        direction: Direction,
230        whole_word: bool,
231        cx: &mut ViewContext<Self>,
232    ) {
233        let Some(pane) = self.pane(cx) else { return };
234        let count = self.take_count(cx).unwrap_or(1);
235        let prior_selections = self.editor_selections(cx);
236        let vim = cx.view().clone();
237
238        let searched = pane.update(cx, |pane, cx| {
239            let Some(search_bar) = pane.toolbar().read(cx).item_of_type::<BufferSearchBar>() else {
240                return false;
241            };
242            let search = search_bar.update(cx, |search_bar, cx| {
243                let options = SearchOptions::CASE_SENSITIVE | SearchOptions::REGEX;
244                if !search_bar.show(cx) {
245                    return None;
246                }
247                let Some(query) = search_bar.query_suggestion(cx) else {
248                    drop(search_bar.search("", None, cx));
249                    return None;
250                };
251                let mut query = regex::escape(&query);
252                if whole_word {
253                    query = format!(r"\<{}\>", query);
254                }
255                Some(search_bar.search(&query, Some(options), cx))
256            });
257
258            let Some(search) = search else { return false };
259
260            let search_bar = search_bar.downgrade();
261            cx.spawn(|_, mut cx| async move {
262                search.await?;
263                search_bar.update(&mut cx, |search_bar, cx| {
264                    search_bar.select_match(direction, count, cx);
265
266                    vim.update(cx, |vim, cx| {
267                        let new_selections = vim.editor_selections(cx);
268                        vim.search_motion(
269                            Motion::ZedSearchResult {
270                                prior_selections,
271                                new_selections,
272                            },
273                            cx,
274                        )
275                    });
276                })?;
277                anyhow::Ok(())
278            })
279            .detach_and_log_err(cx);
280            true
281        });
282        if !searched {
283            self.clear_operator(cx)
284        }
285
286        if self.mode.is_visual() {
287            self.switch_mode(Mode::Normal, false, cx)
288        }
289    }
290
291    fn find_command(&mut self, action: &FindCommand, cx: &mut ViewContext<Self>) {
292        let Some(pane) = self.pane(cx) else { return };
293        pane.update(cx, |pane, cx| {
294            if let Some(search_bar) = pane.toolbar().read(cx).item_of_type::<BufferSearchBar>() {
295                let search = search_bar.update(cx, |search_bar, cx| {
296                    if !search_bar.show(cx) {
297                        return None;
298                    }
299                    let mut query = action.query.clone();
300                    if query == "" {
301                        query = search_bar.query(cx);
302                    };
303
304                    Some(search_bar.search(
305                        &query,
306                        Some(SearchOptions::CASE_SENSITIVE | SearchOptions::REGEX),
307                        cx,
308                    ))
309                });
310                let Some(search) = search else { return };
311                let search_bar = search_bar.downgrade();
312                let direction = if action.backwards {
313                    Direction::Prev
314                } else {
315                    Direction::Next
316                };
317                cx.spawn(|_, mut cx| async move {
318                    search.await?;
319                    search_bar.update(&mut cx, |search_bar, cx| {
320                        search_bar.select_match(direction, 1, cx)
321                    })?;
322                    anyhow::Ok(())
323                })
324                .detach_and_log_err(cx);
325            }
326        })
327    }
328
329    fn replace_command(&mut self, action: &ReplaceCommand, cx: &mut ViewContext<Self>) {
330        let replacement = action.replacement.clone();
331        let Some(((pane, workspace), editor)) =
332            self.pane(cx).zip(self.workspace(cx)).zip(self.editor())
333        else {
334            return;
335        };
336        if let Some(range) = &action.range {
337            if let Some(result) = self.update_editor(cx, |vim, editor, cx| {
338                let range = range.buffer_range(vim, editor, cx)?;
339                let snapshot = &editor.snapshot(cx).buffer_snapshot;
340                let end_point = Point::new(range.end.0, snapshot.line_len(range.end));
341                let range = snapshot.anchor_before(Point::new(range.start.0, 0))
342                    ..snapshot.anchor_after(end_point);
343                editor.set_search_within_ranges(&[range], cx);
344                anyhow::Ok(())
345            }) {
346                workspace.update(cx, |workspace, cx| {
347                    result.notify_err(workspace, cx);
348                })
349            }
350        }
351        let vim = cx.view().clone();
352        pane.update(cx, |pane, cx| {
353            let Some(search_bar) = pane.toolbar().read(cx).item_of_type::<BufferSearchBar>() else {
354                return;
355            };
356            let search = search_bar.update(cx, |search_bar, cx| {
357                if !search_bar.show(cx) {
358                    return None;
359                }
360
361                let mut options = SearchOptions::REGEX;
362                if replacement.is_case_sensitive {
363                    options.set(SearchOptions::CASE_SENSITIVE, true)
364                }
365                let search = if replacement.search == "" {
366                    search_bar.query(cx)
367                } else {
368                    replacement.search
369                };
370
371                search_bar.set_replacement(Some(&replacement.replacement), cx);
372                Some(search_bar.search(&search, Some(options), cx))
373            });
374            let Some(search) = search else { return };
375            let search_bar = search_bar.downgrade();
376            cx.spawn(|_, mut cx| async move {
377                search.await?;
378                search_bar.update(&mut cx, |search_bar, cx| {
379                    if replacement.should_replace_all {
380                        search_bar.select_last_match(cx);
381                        search_bar.replace_all(&Default::default(), cx);
382                        cx.spawn(|_, mut cx| async move {
383                            cx.background_executor()
384                                .timer(Duration::from_millis(200))
385                                .await;
386                            editor
387                                .update(&mut cx, |editor, cx| editor.clear_search_within_ranges(cx))
388                                .ok();
389                        })
390                        .detach();
391                        vim.update(cx, |vim, cx| {
392                            vim.move_cursor(
393                                Motion::StartOfLine {
394                                    display_lines: false,
395                                },
396                                None,
397                                cx,
398                            )
399                        });
400                    }
401                })?;
402                anyhow::Ok(())
403            })
404            .detach_and_log_err(cx);
405        })
406    }
407}
408
409impl Replacement {
410    // convert a vim query into something more usable by zed.
411    // we don't attempt to fully convert between the two regex syntaxes,
412    // but we do flip \( and \) to ( and ) (and vice-versa) in the pattern,
413    // and convert \0..\9 to $0..$9 in the replacement so that common idioms work.
414    pub(crate) fn parse(mut chars: Peekable<Chars>) -> Option<Replacement> {
415        let Some(delimiter) = chars
416            .next()
417            .filter(|c| !c.is_alphanumeric() && *c != '"' && *c != '|' && *c != '\'')
418        else {
419            return None;
420        };
421
422        let mut search = String::new();
423        let mut replacement = String::new();
424        let mut flags = String::new();
425
426        let mut buffer = &mut search;
427
428        let mut escaped = false;
429        // 0 - parsing search
430        // 1 - parsing replacement
431        // 2 - parsing flags
432        let mut phase = 0;
433
434        for c in chars {
435            if escaped {
436                escaped = false;
437                if phase == 1 && c.is_digit(10) {
438                    buffer.push('$')
439                // unescape escaped parens
440                } else if phase == 0 && c == '(' || c == ')' {
441                } else if c != delimiter {
442                    buffer.push('\\')
443                }
444                buffer.push(c)
445            } else if c == '\\' {
446                escaped = true;
447            } else if c == delimiter {
448                if phase == 0 {
449                    buffer = &mut replacement;
450                    phase = 1;
451                } else if phase == 1 {
452                    buffer = &mut flags;
453                    phase = 2;
454                } else {
455                    break;
456                }
457            } else {
458                // escape unescaped parens
459                if phase == 0 && c == '(' || c == ')' {
460                    buffer.push('\\')
461                }
462                buffer.push(c)
463            }
464        }
465
466        let mut replacement = Replacement {
467            search,
468            replacement,
469            should_replace_all: true,
470            is_case_sensitive: true,
471        };
472
473        for c in flags.chars() {
474            match c {
475                'g' | 'I' => {}
476                'c' | 'n' => replacement.should_replace_all = false,
477                'i' => replacement.is_case_sensitive = false,
478                _ => {}
479            }
480        }
481
482        Some(replacement)
483    }
484}
485
486#[cfg(test)]
487mod test {
488    use std::time::Duration;
489
490    use crate::{
491        state::Mode,
492        test::{NeovimBackedTestContext, VimTestContext},
493    };
494    use editor::EditorSettings;
495    use editor::{display_map::DisplayRow, DisplayPoint};
496    use indoc::indoc;
497    use search::BufferSearchBar;
498    use settings::SettingsStore;
499
500    #[gpui::test]
501    async fn test_move_to_next(cx: &mut gpui::TestAppContext) {
502        let mut cx = VimTestContext::new(cx, true).await;
503        cx.set_state("ˇhi\nhigh\nhi\n", Mode::Normal);
504
505        cx.simulate_keystrokes("*");
506        cx.run_until_parked();
507        cx.assert_state("hi\nhigh\nˇhi\n", Mode::Normal);
508
509        cx.simulate_keystrokes("*");
510        cx.run_until_parked();
511        cx.assert_state("ˇhi\nhigh\nhi\n", Mode::Normal);
512
513        cx.simulate_keystrokes("#");
514        cx.run_until_parked();
515        cx.assert_state("hi\nhigh\nˇhi\n", Mode::Normal);
516
517        cx.simulate_keystrokes("#");
518        cx.run_until_parked();
519        cx.assert_state("ˇhi\nhigh\nhi\n", Mode::Normal);
520
521        cx.simulate_keystrokes("2 *");
522        cx.run_until_parked();
523        cx.assert_state("ˇhi\nhigh\nhi\n", Mode::Normal);
524
525        cx.simulate_keystrokes("g *");
526        cx.run_until_parked();
527        cx.assert_state("hi\nˇhigh\nhi\n", Mode::Normal);
528
529        cx.simulate_keystrokes("n");
530        cx.assert_state("hi\nhigh\nˇhi\n", Mode::Normal);
531
532        cx.simulate_keystrokes("g #");
533        cx.run_until_parked();
534        cx.assert_state("hi\nˇhigh\nhi\n", Mode::Normal);
535    }
536
537    #[gpui::test]
538    async fn test_move_to_next_with_no_search_wrap(cx: &mut gpui::TestAppContext) {
539        let mut cx = VimTestContext::new(cx, true).await;
540
541        cx.update_global(|store: &mut SettingsStore, cx| {
542            store.update_user_settings::<EditorSettings>(cx, |s| s.search_wrap = Some(false));
543        });
544
545        cx.set_state("ˇhi\nhigh\nhi\n", Mode::Normal);
546
547        cx.simulate_keystrokes("*");
548        cx.run_until_parked();
549        cx.assert_state("hi\nhigh\nˇhi\n", Mode::Normal);
550
551        cx.simulate_keystrokes("*");
552        cx.run_until_parked();
553        cx.assert_state("hi\nhigh\nˇhi\n", Mode::Normal);
554
555        cx.simulate_keystrokes("#");
556        cx.run_until_parked();
557        cx.assert_state("ˇhi\nhigh\nhi\n", Mode::Normal);
558
559        cx.simulate_keystrokes("3 *");
560        cx.run_until_parked();
561        cx.assert_state("ˇhi\nhigh\nhi\n", Mode::Normal);
562
563        cx.simulate_keystrokes("g *");
564        cx.run_until_parked();
565        cx.assert_state("hi\nˇhigh\nhi\n", Mode::Normal);
566
567        cx.simulate_keystrokes("n");
568        cx.assert_state("hi\nhigh\nˇhi\n", Mode::Normal);
569
570        cx.simulate_keystrokes("g #");
571        cx.run_until_parked();
572        cx.assert_state("hi\nˇhigh\nhi\n", Mode::Normal);
573    }
574
575    #[gpui::test]
576    async fn test_search(cx: &mut gpui::TestAppContext) {
577        let mut cx = VimTestContext::new(cx, true).await;
578
579        cx.set_state("aa\nbˇb\ncc\ncc\ncc\n", Mode::Normal);
580        cx.simulate_keystrokes("/ c c");
581
582        let search_bar = cx.workspace(|workspace, cx| {
583            workspace
584                .active_pane()
585                .read(cx)
586                .toolbar()
587                .read(cx)
588                .item_of_type::<BufferSearchBar>()
589                .expect("Buffer search bar should be deployed")
590        });
591
592        cx.update_view(search_bar, |bar, cx| {
593            assert_eq!(bar.query(cx), "cc");
594        });
595
596        cx.run_until_parked();
597
598        cx.update_editor(|editor, cx| {
599            let highlights = editor.all_text_background_highlights(cx);
600            assert_eq!(3, highlights.len());
601            assert_eq!(
602                DisplayPoint::new(DisplayRow(2), 0)..DisplayPoint::new(DisplayRow(2), 2),
603                highlights[0].0
604            )
605        });
606
607        cx.simulate_keystrokes("enter");
608        cx.assert_state("aa\nbb\nˇcc\ncc\ncc\n", Mode::Normal);
609
610        // n to go to next/N to go to previous
611        cx.simulate_keystrokes("n");
612        cx.assert_state("aa\nbb\ncc\nˇcc\ncc\n", Mode::Normal);
613        cx.simulate_keystrokes("shift-n");
614        cx.assert_state("aa\nbb\nˇcc\ncc\ncc\n", Mode::Normal);
615
616        // ?<enter> to go to previous
617        cx.simulate_keystrokes("? enter");
618        cx.assert_state("aa\nbb\ncc\ncc\nˇcc\n", Mode::Normal);
619        cx.simulate_keystrokes("? enter");
620        cx.assert_state("aa\nbb\ncc\nˇcc\ncc\n", Mode::Normal);
621
622        // /<enter> to go to next
623        cx.simulate_keystrokes("/ enter");
624        cx.assert_state("aa\nbb\ncc\ncc\nˇcc\n", Mode::Normal);
625
626        // ?{search}<enter> to search backwards
627        cx.simulate_keystrokes("? b enter");
628        cx.assert_state("aa\nbˇb\ncc\ncc\ncc\n", Mode::Normal);
629
630        // works with counts
631        cx.simulate_keystrokes("4 / c");
632        cx.simulate_keystrokes("enter");
633        cx.assert_state("aa\nbb\ncc\ncˇc\ncc\n", Mode::Normal);
634
635        // check that searching resumes from cursor, not previous match
636        cx.set_state("ˇaa\nbb\ndd\ncc\nbb\n", Mode::Normal);
637        cx.simulate_keystrokes("/ d");
638        cx.simulate_keystrokes("enter");
639        cx.assert_state("aa\nbb\nˇdd\ncc\nbb\n", Mode::Normal);
640        cx.update_editor(|editor, cx| editor.move_to_beginning(&Default::default(), cx));
641        cx.assert_state("ˇaa\nbb\ndd\ncc\nbb\n", Mode::Normal);
642        cx.simulate_keystrokes("/ b");
643        cx.simulate_keystrokes("enter");
644        cx.assert_state("aa\nˇbb\ndd\ncc\nbb\n", Mode::Normal);
645
646        // check that searching switches to normal mode if in visual mode
647        cx.set_state("ˇone two one", Mode::Normal);
648        cx.simulate_keystrokes("v l l");
649        cx.assert_editor_state("«oneˇ» two one");
650        cx.simulate_keystrokes("*");
651        cx.assert_state("one two ˇone", Mode::Normal);
652
653        // check that searching with unable search wrap
654        cx.update_global(|store: &mut SettingsStore, cx| {
655            store.update_user_settings::<EditorSettings>(cx, |s| s.search_wrap = Some(false));
656        });
657        cx.set_state("aa\nbˇb\ncc\ncc\ncc\n", Mode::Normal);
658        cx.simulate_keystrokes("/ c c enter");
659
660        cx.assert_state("aa\nbb\nˇcc\ncc\ncc\n", Mode::Normal);
661
662        // n to go to next/N to go to previous
663        cx.simulate_keystrokes("n");
664        cx.assert_state("aa\nbb\ncc\nˇcc\ncc\n", Mode::Normal);
665        cx.simulate_keystrokes("shift-n");
666        cx.assert_state("aa\nbb\nˇcc\ncc\ncc\n", Mode::Normal);
667
668        // ?<enter> to go to previous
669        cx.simulate_keystrokes("? enter");
670        cx.assert_state("aa\nbb\nˇcc\ncc\ncc\n", Mode::Normal);
671        cx.simulate_keystrokes("? enter");
672        cx.assert_state("aa\nbb\nˇcc\ncc\ncc\n", Mode::Normal);
673    }
674
675    #[gpui::test]
676    async fn test_non_vim_search(cx: &mut gpui::TestAppContext) {
677        let mut cx = VimTestContext::new(cx, false).await;
678        cx.cx.set_state("ˇone one one one");
679        cx.simulate_keystrokes("cmd-f");
680        cx.run_until_parked();
681
682        cx.assert_editor_state("«oneˇ» one one one");
683        cx.simulate_keystrokes("enter");
684        cx.assert_editor_state("one «oneˇ» one one");
685        cx.simulate_keystrokes("shift-enter");
686        cx.assert_editor_state("«oneˇ» one one one");
687    }
688
689    #[gpui::test]
690    async fn test_visual_star_hash(cx: &mut gpui::TestAppContext) {
691        let mut cx = NeovimBackedTestContext::new(cx).await;
692
693        cx.set_shared_state("ˇa.c. abcd a.c. abcd").await;
694        cx.simulate_shared_keystrokes("v 3 l *").await;
695        cx.shared_state().await.assert_eq("a.c. abcd ˇa.c. abcd");
696    }
697
698    #[gpui::test]
699    async fn test_d_search(cx: &mut gpui::TestAppContext) {
700        let mut cx = NeovimBackedTestContext::new(cx).await;
701
702        cx.set_shared_state("ˇa.c. abcd a.c. abcd").await;
703        cx.simulate_shared_keystrokes("d / c d").await;
704        cx.simulate_shared_keystrokes("enter").await;
705        cx.shared_state().await.assert_eq("ˇcd a.c. abcd");
706    }
707
708    #[gpui::test]
709    async fn test_v_search(cx: &mut gpui::TestAppContext) {
710        let mut cx = NeovimBackedTestContext::new(cx).await;
711
712        cx.set_shared_state("ˇa.c. abcd a.c. abcd").await;
713        cx.simulate_shared_keystrokes("v / c d").await;
714        cx.simulate_shared_keystrokes("enter").await;
715        cx.shared_state().await.assert_eq("«a.c. abcˇ»d a.c. abcd");
716
717        cx.set_shared_state("a a aˇ a a a").await;
718        cx.simulate_shared_keystrokes("v / a").await;
719        cx.simulate_shared_keystrokes("enter").await;
720        cx.shared_state().await.assert_eq("a a a« aˇ» a a");
721        cx.simulate_shared_keystrokes("/ enter").await;
722        cx.shared_state().await.assert_eq("a a a« a aˇ» a");
723        cx.simulate_shared_keystrokes("? enter").await;
724        cx.shared_state().await.assert_eq("a a a« aˇ» a a");
725        cx.simulate_shared_keystrokes("? enter").await;
726        cx.shared_state().await.assert_eq("a a «ˇa »a a a");
727        cx.simulate_shared_keystrokes("/ enter").await;
728        cx.shared_state().await.assert_eq("a a a« aˇ» a a");
729        cx.simulate_shared_keystrokes("/ enter").await;
730        cx.shared_state().await.assert_eq("a a a« a aˇ» a");
731    }
732
733    #[gpui::test]
734    async fn test_visual_block_search(cx: &mut gpui::TestAppContext) {
735        let mut cx = NeovimBackedTestContext::new(cx).await;
736
737        cx.set_shared_state(indoc! {
738            "ˇone two
739             three four
740             five six
741             "
742        })
743        .await;
744        cx.simulate_shared_keystrokes("ctrl-v j / f").await;
745        cx.simulate_shared_keystrokes("enter").await;
746        cx.shared_state().await.assert_eq(indoc! {
747            "«one twoˇ»
748             «three fˇ»our
749             five six
750             "
751        });
752    }
753
754    // cargo test -p vim --features neovim test_replace_with_range_at_start
755    #[gpui::test]
756    async fn test_replace_with_range_at_start(cx: &mut gpui::TestAppContext) {
757        let mut cx = NeovimBackedTestContext::new(cx).await;
758
759        cx.set_shared_state(indoc! {
760            "ˇa
761            a
762            a
763            a
764            a
765            a
766            a
767             "
768        })
769        .await;
770        cx.simulate_shared_keystrokes(": 2 , 5 s / ^ / b").await;
771        cx.simulate_shared_keystrokes("enter").await;
772        cx.shared_state().await.assert_eq(indoc! {
773            "a
774            ba
775            ba
776            ba
777            ˇba
778            a
779            a
780             "
781        });
782        cx.executor().advance_clock(Duration::from_millis(250));
783        cx.run_until_parked();
784
785        cx.simulate_shared_keystrokes("/ a enter").await;
786        cx.shared_state().await.assert_eq(indoc! {
787            "a
788                ba
789                ba
790                ba
791                bˇa
792                a
793                a
794                 "
795        });
796    }
797
798    // cargo test -p vim --features neovim test_replace_with_range
799    #[gpui::test]
800    async fn test_replace_with_range(cx: &mut gpui::TestAppContext) {
801        let mut cx = NeovimBackedTestContext::new(cx).await;
802
803        cx.set_shared_state(indoc! {
804            "ˇa
805            a
806            a
807            a
808            a
809            a
810            a
811             "
812        })
813        .await;
814        cx.simulate_shared_keystrokes(": 2 , 5 s / a / b").await;
815        cx.simulate_shared_keystrokes("enter").await;
816        cx.shared_state().await.assert_eq(indoc! {
817            "a
818            b
819            b
820            b
821            ˇb
822            a
823            a
824             "
825        });
826        cx.executor().advance_clock(Duration::from_millis(250));
827        cx.run_until_parked();
828
829        cx.simulate_shared_keystrokes("/ a enter").await;
830        cx.shared_state().await.assert_eq(indoc! {
831            "a
832                b
833                b
834                b
835                b
836                ˇa
837                a
838                 "
839        });
840    }
841}