escriba-search 0.1.27

Incremental buffer search for escriba — vim-grade `/` and `?` with smartcase, regex, wrap-around, whole-word `*`/`#`, hlsearch and search history. Pure and side-effect-free: a function of (text, pattern, cursor).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
//! Search session state: the live prompt, the committed pattern, and history.
//!
//! # The shape, and why
//!
//! Two things get confused in editor search implementations, always with the
//! same symptom — highlights that linger after Escape, or `n` repeating a
//! pattern the user cancelled:
//!
//! - the **prompt** (`/foo` being typed, not yet accepted), and
//! - the **committed** pattern (what `n` / `N` repeat, what stays highlighted).
//!
//! They are modelled as separate fields, and the prompt is an `Option<Prompt>`
//! rather than a bool-plus-string. A session that is not open therefore has no
//! text and no direction to read: "typing into a closed prompt" is not a state
//! that can be constructed, instead of one guarded by an `if is_open` that some
//! future call site forgets.
//!
//! Cancelling drops the `Prompt` and leaves the committed pattern untouched,
//! which is exactly vim's behaviour and falls out of the shape rather than
//! being restored by hand.

use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

use crate::engine::{Direction, SearchMatch, Step, find_all, step, step_inclusive};
use crate::pattern::{CaseMode, PatternError, SearchPattern};

/// How many past searches to keep. vim's default is 50.
pub const HISTORY_LIMIT: usize = 50;

/// An open search prompt — the user is typing `/…` or `?…`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Prompt {
    /// Which key opened it, and therefore which way `<CR>` will search.
    pub direction: Direction,
    /// What has been typed so far (without the leading `/` or `?`).
    pub text: String,
    /// Where the cursor was when the prompt opened. Incremental search
    /// previews from here, and Escape returns here — so it must be captured at
    /// open time, not read live.
    pub origin: usize,
    /// Where the next typed character goes, in CHARS from the start of
    /// `text` — never bytes.
    ///
    /// Chars because a pattern is text a human is editing, and a byte caret
    /// lands mid-codepoint the first time someone searches for `héllo`. The
    /// invariant `caret <= text.chars().count()` holds at every mutation
    /// below; `caret == len` is the ordinary "typing at the end" state.
    caret: usize,
    /// Position in history while arrowing through it; `None` = editing fresh
    /// text rather than browsing.
    history_index: Option<usize>,
    /// The in-progress text stashed when history browsing began, so arrowing
    /// back down past the newest entry restores what the user actually typed.
    stashed: Option<String>,
}

/// Where a caret movement lands.
///
/// A closed set, so "move the caret" cannot mean an unhandled direction. Each
/// resolves against the CURRENT length, so none can leave the caret out of
/// bounds — the clamping is in one place rather than at each call site.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default, Serialize, Deserialize, JsonSchema)]
pub enum CaretMove {
    #[default]
    Left,
    Right,
    Start,
    End,
}

impl CaretMove {
    /// Total, and saturating at both ends.
    #[must_use]
    pub const fn resolve(self, caret: usize, len: usize) -> usize {
        match self {
            Self::Left => caret.saturating_sub(1),
            Self::Right => {
                if caret < len {
                    caret + 1
                } else {
                    len
                }
            }
            Self::Start => 0,
            Self::End => len,
        }
    }
}

impl Prompt {
    /// The caret as a char index. `caret == text.chars().count()` means "at
    /// the end", which is the common case.
    #[must_use]
    pub const fn caret(&self) -> usize {
        self.caret
    }

    /// The caret as a BYTE index into `text`, for string surgery.
    ///
    /// The one place chars become bytes, so a mid-codepoint index cannot be
    /// constructed by an edit op doing its own arithmetic.
    #[must_use]
    fn byte_of_caret(&self) -> usize {
        self.text
            .char_indices()
            .nth(self.caret)
            .map_or(self.text.len(), |(b, _)| b)
    }
}

/// The result of committing a prompt.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Accepted {
    /// A new pattern was compiled and committed.
    Committed,
    /// The prompt was empty, so the previous pattern was reused — vim's bare
    /// `/<CR>`.
    ReusedPrevious,
    /// Nothing to do: empty prompt and no previous pattern.
    NothingToRepeat,
    /// The pattern did not compile; the prompt stays open so the user can fix
    /// it rather than losing what they typed.
    Invalid(PatternError),
}

/// Everything search needs to remember.
#[derive(Debug, Clone, Default)]
pub struct SearchState {
    prompt: Option<Prompt>,
    pattern: Option<SearchPattern>,
    /// Direction of the committed search — what `n` repeats. Distinct from the
    /// prompt's direction, which is discarded on cancel.
    direction: Direction,
    matches: Vec<SearchMatch>,
    /// vim's `hlsearch`: whether matches stay lit after the search completes.
    /// `:noh` clears this without forgetting the pattern, so `n` still works.
    highlight: bool,
    history: Vec<String>,
    case: CaseMode,
}

impl SearchState {
    #[must_use]
    pub fn new(case: CaseMode) -> Self {
        Self {
            case,
            highlight: true,
            ..Self::default()
        }
    }

    // ── prompt lifecycle ────────────────────────────────────────────────

    /// Open a prompt. `origin` is the cursor position to preview from and to
    /// return to on cancel.
    pub fn open(&mut self, direction: Direction, origin: usize) {
        self.prompt = Some(Prompt {
            direction,
            text: String::new(),
            origin,
            caret: 0,
            history_index: None,
            stashed: None,
        });
    }

    #[must_use]
    pub const fn prompt(&self) -> Option<&Prompt> {
        self.prompt.as_ref()
    }

    #[must_use]
    pub const fn is_prompting(&self) -> bool {
        self.prompt.is_some()
    }

    /// Type a character into the prompt. No-op when no prompt is open.
    pub fn push(&mut self, ch: char) {
        if let Some(p) = self.prompt.as_mut() {
            let at = p.byte_of_caret();
            p.text.insert(at, ch);
            p.caret += 1;
            // Editing ends history browsing — the text is the user's now.
            p.history_index = None;
        }
    }

    /// Move the caret. Saturates at both ends rather than wrapping — a caret
    /// that wraps from the start to the end deletes the wrong character next.
    pub fn move_caret(&mut self, to: CaretMove) {
        if let Some(p) = self.prompt.as_mut() {
            p.caret = to.resolve(p.caret, p.text.chars().count());
        }
    }

    /// Delete the character AT the caret (`<Del>`). No-op at the end.
    ///
    /// Distinct from [`Self::backspace`], which deletes the one before it and
    /// can close the prompt. Forward-delete never closes the prompt: emptying
    /// the text by deleting rightwards is not the "backspaced past the `/`"
    /// gesture that means "I changed my mind".
    pub fn delete_at_caret(&mut self) {
        if let Some(p) = self.prompt.as_mut() {
            let at = p.byte_of_caret();
            if at < p.text.len() {
                p.text.remove(at);
                p.history_index = None;
            }
        }
    }

    /// `<C-w>` — delete the word before the caret.
    ///
    /// Trailing whitespace goes first, then the run of non-whitespace, which
    /// is what makes a second `<C-w>` delete a whole second word rather than
    /// only the gap.
    pub fn delete_word_before_caret(&mut self) {
        let Some(p) = self.prompt.as_mut() else {
            return;
        };
        let chars: Vec<char> = p.text.chars().collect();
        let mut i = p.caret;
        while i > 0 && chars[i - 1].is_whitespace() {
            i -= 1;
        }
        while i > 0 && !chars[i - 1].is_whitespace() {
            i -= 1;
        }
        let kept: String = chars[..i].iter().chain(chars[p.caret..].iter()).collect();
        p.text = kept;
        p.caret = i;
        p.history_index = None;
    }

    /// `<C-u>` — delete from the caret back to the start.
    pub fn clear_before_caret(&mut self) {
        if let Some(p) = self.prompt.as_mut() {
            let at = p.byte_of_caret();
            p.text.drain(..at);
            p.caret = 0;
            p.history_index = None;
        }
    }

    /// Backspace. Returns `true` if the prompt closed because it was already
    /// empty (vim closes the prompt when you backspace past the `/`).
    pub fn backspace(&mut self) -> bool {
        let Some(p) = self.prompt.as_mut() else {
            return false;
        };
        p.history_index = None;
        if p.caret == 0 {
            // Backspacing past the `/` closes the prompt — but only when there
            // is nothing to the left. With text ahead of the caret this is a
            // no-op, not a cancel: losing a pattern because the caret happened
            // to be at the start would be the worst kind of surprise.
            if p.text.is_empty() {
                self.prompt = None;
                return true;
            }
            return false;
        }
        let at = p.byte_of_caret();
        let prev = p.text[..at]
            .char_indices()
            .next_back()
            .map_or(0, |(i, _)| i);
        p.text.remove(prev);
        p.caret -= 1;
        false
    }

    /// Abandon the prompt. The committed pattern and its highlights survive —
    /// cancelling a new search does not erase the old one.
    ///
    /// Returns the cursor position to restore, if a prompt was open.
    pub fn cancel(&mut self) -> Option<usize> {
        self.prompt.take().map(|p| p.origin)
    }

    /// Commit the prompt.
    pub fn accept(&mut self, text: &str) -> Accepted {
        let Some(p) = self.prompt.take() else {
            return Accepted::NothingToRepeat;
        };
        let direction = p.direction;

        if p.text.is_empty() {
            // Bare `/<CR>`: repeat the previous pattern in the NEW direction.
            return if self.pattern.is_some() {
                self.direction = direction;
                self.refresh(text);
                Accepted::ReusedPrevious
            } else {
                Accepted::NothingToRepeat
            };
        }

        match SearchPattern::compile(&p.text, self.case) {
            Ok(pattern) => {
                self.remember(&p.text);
                self.pattern = Some(pattern);
                self.direction = direction;
                self.highlight = true;
                self.refresh(text);
                Accepted::Committed
            }
            Err(e) => {
                // Put the prompt back so the typed text is not lost.
                self.prompt = Some(p);
                Accepted::Invalid(e)
            }
        }
    }

    // ── history ─────────────────────────────────────────────────────────

    fn remember(&mut self, raw: &str) {
        // Re-searching something moves it to the front rather than duplicating.
        self.history.retain(|h| h != raw);
        self.history.push(raw.to_string());
        if self.history.len() > HISTORY_LIMIT {
            self.history.remove(0);
        }
    }

    #[must_use]
    pub fn history(&self) -> &[String] {
        &self.history
    }

    /// Arrow up/down through history while prompting. `back` = older.
    pub fn history_step(&mut self, back: bool) {
        if self.history.is_empty() {
            return;
        }
        let len = self.history.len();
        let Some(p) = self.prompt.as_mut() else {
            return;
        };
        match (p.history_index, back) {
            // Enter history: stash what is being typed so it can come back.
            (None, true) => {
                p.stashed = Some(p.text.clone());
                p.history_index = Some(len - 1);
                p.text.clone_from(&self.history[len - 1]);
            }
            (Some(i), true) if i > 0 => {
                p.history_index = Some(i - 1);
                p.text.clone_from(&self.history[i - 1]);
            }
            (Some(i), false) if i + 1 < len => {
                p.history_index = Some(i + 1);
                p.text.clone_from(&self.history[i + 1]);
            }
            // Stepping forward past the newest entry restores the stash.
            (Some(_), false) => {
                p.history_index = None;
                p.text = p.stashed.take().unwrap_or_default();
            }
            _ => {}
        }
        // A recalled pattern arrives whole; the caret belongs at its end,
        // which is where a user expects to continue typing.
        p.caret = p.text.chars().count();
    }

    // ── searching ───────────────────────────────────────────────────────

    /// Recompute matches against `text`. Call after an edit, or after the
    /// buffer changes under a live highlight.
    pub fn refresh(&mut self, text: &str) {
        self.matches = self
            .pattern
            .as_ref()
            .map_or_else(Vec::new, |p| find_all(text, p));
    }

    /// Incremental preview for the current prompt text, without committing.
    /// Returns where the cursor would land.
    #[must_use]
    pub fn preview(&self, text: &str) -> Option<Step> {
        let p = self.prompt.as_ref()?;
        if p.text.is_empty() {
            return None;
        }
        let pattern = SearchPattern::compile(&p.text, self.case).ok()?;
        let matches = find_all(text, &pattern);
        // Inclusive: typing `/foo` while sitting ON a `foo` must light up that
        // one. `n` deliberately uses the exclusive `step` instead.
        step_inclusive(&matches, p.origin, p.direction)
    }

    /// How many matches the CURRENT PROMPT text would find.
    ///
    /// The denominator of `[3/17]` while typing — the half that makes the
    /// count a safety measurement rather than a curiosity: `[1/1]` says a
    /// rename is safe, `[1/240]` says narrow the pattern first, and both
    /// answers arrive before Enter.
    ///
    /// `0` covers all three "nothing to count" cases — no prompt, empty
    /// prompt, uncompilable pattern — because a caller showing a count cannot
    /// act on the difference; [`Self::prompt_is_empty`] separates them when it
    /// matters.
    #[must_use]
    pub fn preview_total(&self, text: &str) -> usize {
        let Some(p) = self.prompt.as_ref() else {
            return 0;
        };
        if p.text.is_empty() {
            return 0;
        }
        SearchPattern::compile(&p.text, self.case)
            .ok()
            .map_or(0, |pattern| find_all(text, &pattern).len())
    }

    /// Is a prompt open with nothing typed into it yet?
    ///
    /// Distinguishes "you have not typed a pattern" from "your pattern matches
    /// nothing" — the first should stay silent, the second should say `[0/0]`.
    #[must_use]
    pub fn prompt_is_empty(&self) -> bool {
        self.prompt.as_ref().is_none_or(|p| p.text.is_empty())
    }

    /// Where committing the prompt should land, given the prompt's origin.
    ///
    /// **Uses `step_inclusive`, exactly as [`Self::preview`] does** — that is
    /// the entire contract: what the preview showed is where Enter lands.
    ///
    /// `repeat(origin - 1)` is NOT a substitute, and the difference is not
    /// theoretical. `repeat` is exclusive, so it needs the caller to back up
    /// one to include a match sitting on the origin; `saturating_sub` cannot
    /// back up past 0, so a match at offset 0 — the first word of the file —
    /// became unreachable and the commit silently jumped to the *second*
    /// match. `engine.rs` documents this saturation trap on `step_inclusive`
    /// itself; this method is why that type exists.
    #[must_use]
    pub fn commit_step(&self, origin: usize) -> Option<Step> {
        step_inclusive(&self.matches, origin, self.direction)
    }

    /// `n` (`reverse = false`) / `N` (`reverse = true`).
    #[must_use]
    pub fn repeat(&self, from: usize, reverse: bool) -> Option<Step> {
        let dir = if reverse {
            self.direction.reversed()
        } else {
            self.direction
        };
        step(&self.matches, from, dir)
    }

    /// `*` / `#` — search the word under the cursor, whole-word and literal.
    /// Returns where to jump, or `None` if there is no word or no match.
    pub fn search_word(&mut self, text: &str, cursor: usize, direction: Direction) -> Option<Step> {
        let word = crate::engine::word_at(text, cursor)?;
        let pattern = SearchPattern::whole_word(&word, self.case).ok()?;
        self.remember(pattern.raw());
        self.pattern = Some(pattern);
        self.direction = direction;
        self.highlight = true;
        self.refresh(text);
        self.repeat(cursor, false)
    }

    // ── committed view ──────────────────────────────────────────────────

    #[must_use]
    pub const fn pattern(&self) -> Option<&SearchPattern> {
        self.pattern.as_ref()
    }

    #[must_use]
    pub const fn direction(&self) -> Direction {
        self.direction
    }

    #[must_use]
    pub fn matches(&self) -> &[SearchMatch] {
        &self.matches
    }

    /// Matches the renderer should light up. Empty when `hlsearch` is off, so
    /// the caller needs no separate check.
    #[must_use]
    pub fn highlights(&self) -> &[SearchMatch] {
        if self.highlight { &self.matches } else { &[] }
    }

    #[must_use]
    pub const fn highlight_enabled(&self) -> bool {
        self.highlight
    }

    /// Re-enable highlighting for the committed pattern.
    ///
    /// `n` after an auto-clear must light the matches again — vim does the
    /// same. Without this, highlighting would be a one-shot that the first
    /// motion extinguished permanently.
    pub fn relight(&mut self) {
        self.highlight = true;
    }

    /// `:noh` — stop highlighting, but keep the pattern so `n` still works.
    pub fn clear_highlight(&mut self) {
        self.highlight = false;
    }

    pub fn set_case(&mut self, case: CaseMode) {
        self.case = case;
    }

    #[must_use]
    pub const fn case(&self) -> CaseMode {
        self.case
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    const TEXT: &str = "foo bar\nbaz foo\nqux foo end";

    fn committed(pat: &str) -> SearchState {
        let mut s = SearchState::new(CaseMode::Sensitive);
        s.open(Direction::Forward, 0);
        for c in pat.chars() {
            s.push(c);
        }
        assert_eq!(s.accept(TEXT), Accepted::Committed);
        s
    }

    #[test]
    fn typing_then_accepting_commits_and_finds() {
        let s = committed("foo");
        assert_eq!(s.pattern().unwrap().raw(), "foo");
        assert_eq!(s.matches().len(), 3);
        assert!(!s.is_prompting(), "prompt closes on accept");
    }

    #[test]
    fn cancel_keeps_the_previous_search_intact() {
        let mut s = committed("foo");
        s.open(Direction::Forward, 5);
        s.push('z');
        let origin = s.cancel();
        assert_eq!(origin, Some(5), "cancel returns the cursor home");
        assert_eq!(s.pattern().unwrap().raw(), "foo", "old pattern survives");
        assert_eq!(s.matches().len(), 3, "old highlights survive");
        assert!(!s.is_prompting());
    }

    #[test]
    fn backspacing_past_the_slash_closes_the_prompt() {
        let mut s = SearchState::new(CaseMode::Smart);
        s.open(Direction::Forward, 0);
        s.push('a');
        assert!(!s.backspace(), "still has text");
        assert!(s.backspace(), "empty -> closes");
        assert!(!s.is_prompting());
    }

    #[test]
    fn an_invalid_pattern_keeps_the_prompt_open_so_typing_is_not_lost() {
        let mut s = SearchState::new(CaseMode::Smart);
        s.open(Direction::Forward, 0);
        for c in "a[b".chars() {
            s.push(c);
        }
        assert!(matches!(s.accept(TEXT), Accepted::Invalid(_)));
        assert!(s.is_prompting(), "prompt must stay open");
        assert_eq!(s.prompt().unwrap().text, "a[b", "text must survive");
    }

    #[test]
    fn bare_enter_reuses_the_previous_pattern() {
        let mut s = committed("foo");
        s.open(Direction::Backward, 0);
        assert_eq!(s.accept(TEXT), Accepted::ReusedPrevious);
        assert_eq!(s.pattern().unwrap().raw(), "foo");
        assert_eq!(s.direction(), Direction::Backward, "direction updates");
    }

    #[test]
    fn bare_enter_with_no_history_does_nothing() {
        let mut s = SearchState::new(CaseMode::Smart);
        s.open(Direction::Forward, 0);
        assert_eq!(s.accept(TEXT), Accepted::NothingToRepeat);
    }

    #[test]
    fn n_and_N_move_opposite_ways() {
        let s = committed("foo");
        let fwd = s.repeat(0, false).unwrap();
        let back = s.repeat(20, true).unwrap();
        assert!(fwd.target.start > 0);
        assert!(back.target.start < 20);
    }

    #[test]
    fn N_after_a_backward_search_goes_forward() {
        let mut s = SearchState::new(CaseMode::Sensitive);
        s.open(Direction::Backward, 0);
        for c in "foo".chars() {
            s.push(c);
        }
        s.accept(TEXT);
        assert_eq!(s.direction(), Direction::Backward);
        // N reverses a backward search into a forward one. TEXT has `foo` at
        // 0, 12 and 20; forward-from-0 is exclusive, so it lands on 12.
        let n = s.repeat(0, true).unwrap();
        assert_eq!(n.target.start, 12, "first match strictly after 0");
    }

    #[test]
    fn noh_stops_highlighting_but_n_still_works() {
        let mut s = committed("foo");
        assert_eq!(s.highlights().len(), 3);
        s.clear_highlight();
        assert!(s.highlights().is_empty(), "nothing lit");
        assert_eq!(s.matches().len(), 3, "but matches are remembered");
        assert!(s.repeat(0, false).is_some(), "and n still moves");
    }

    #[test]
    fn incremental_preview_does_not_commit() {
        let mut s = SearchState::new(CaseMode::Sensitive);
        s.open(Direction::Forward, 0);
        for c in "baz".chars() {
            s.push(c);
        }
        assert!(s.preview(TEXT).is_some(), "preview finds it");
        assert!(s.pattern().is_none(), "but nothing is committed yet");
        assert!(s.matches().is_empty());
    }

    #[test]
    fn preview_finds_a_match_starting_at_the_cursor() {
        let mut s = SearchState::new(CaseMode::Sensitive);
        s.open(Direction::Forward, 0); // cursor sits on "foo" at 0
        for c in "foo".chars() {
            s.push(c);
        }
        assert_eq!(
            s.preview(TEXT).unwrap().target.start,
            0,
            "must light the one under the cursor"
        );
    }

    #[test]
    fn preview_of_an_invalid_pattern_is_none_not_a_panic() {
        let mut s = SearchState::new(CaseMode::Smart);
        s.open(Direction::Forward, 0);
        for c in "a[b".chars() {
            s.push(c);
        }
        assert!(s.preview(TEXT).is_none());
    }

    #[test]
    fn history_records_accepted_searches_newest_last() {
        let mut s = SearchState::new(CaseMode::Sensitive);
        for p in ["foo", "bar", "baz"] {
            s.open(Direction::Forward, 0);
            for c in p.chars() {
                s.push(c);
            }
            s.accept(TEXT);
        }
        assert_eq!(s.history(), ["foo", "bar", "baz"]);
    }

    #[test]
    fn repeating_a_search_moves_it_to_the_front_without_duplicating() {
        let mut s = SearchState::new(CaseMode::Sensitive);
        for p in ["foo", "bar", "foo"] {
            s.open(Direction::Forward, 0);
            for c in p.chars() {
                s.push(c);
            }
            s.accept(TEXT);
        }
        assert_eq!(s.history(), ["bar", "foo"], "no duplicate 'foo'");
    }

    #[test]
    fn arrowing_up_walks_back_through_history() {
        let mut s = SearchState::new(CaseMode::Sensitive);
        for p in ["one", "two"] {
            s.open(Direction::Forward, 0);
            for c in p.chars() {
                s.push(c);
            }
            s.accept(TEXT);
        }
        s.open(Direction::Forward, 0);
        s.history_step(true);
        assert_eq!(s.prompt().unwrap().text, "two");
        s.history_step(true);
        assert_eq!(s.prompt().unwrap().text, "one");
        s.history_step(false);
        assert_eq!(s.prompt().unwrap().text, "two");
    }

    #[test]
    fn arrowing_back_down_restores_what_you_were_typing() {
        let mut s = SearchState::new(CaseMode::Sensitive);
        s.open(Direction::Forward, 0);
        for c in "old".chars() {
            s.push(c);
        }
        s.accept(TEXT);

        s.open(Direction::Forward, 0);
        for c in "typ".chars() {
            s.push(c);
        }
        s.history_step(true);
        assert_eq!(s.prompt().unwrap().text, "old");
        s.history_step(false);
        assert_eq!(s.prompt().unwrap().text, "typ", "the stash comes back");
    }

    #[test]
    fn history_is_bounded() {
        let mut s = SearchState::new(CaseMode::Sensitive);
        for i in 0..(HISTORY_LIMIT + 10) {
            s.open(Direction::Forward, 0);
            for c in i.to_string().chars() {
                s.push(c);
            }
            s.accept(TEXT);
        }
        assert_eq!(s.history().len(), HISTORY_LIMIT);
    }

    #[test]
    fn star_searches_the_whole_word_under_the_cursor() {
        let text = "foo foobar foo";
        let mut s = SearchState::new(CaseMode::Sensitive);
        let hit = s.search_word(text, 0, Direction::Forward).unwrap();
        // Whole-word: "foobar" must NOT match, so from 0 the next is at 11.
        assert_eq!(hit.target.start, 11);
        assert_eq!(s.matches().len(), 2, "two whole-word 'foo', not three");
    }

    #[test]
    fn star_on_a_wordless_line_is_none_and_changes_nothing() {
        let mut s = committed("foo");
        let before = s.matches().len();
        assert!(s.search_word("   \n", 0, Direction::Forward).is_none());
        assert_eq!(s.matches().len(), before, "state untouched");
    }

    #[test]
    fn typing_after_browsing_history_stops_browsing() {
        let mut s = SearchState::new(CaseMode::Sensitive);
        s.open(Direction::Forward, 0);
        for c in "old".chars() {
            s.push(c);
        }
        s.accept(TEXT);
        s.open(Direction::Forward, 0);
        s.history_step(true);
        assert_eq!(s.prompt().unwrap().text, "old");
        s.push('x');
        assert_eq!(s.prompt().unwrap().text, "oldx");
        // Arrowing down now restores nothing (we are editing, not browsing).
        s.history_step(false);
        assert_eq!(s.prompt().unwrap().text, "oldx");
    }

    #[test]
    fn refresh_tracks_an_edited_buffer() {
        let mut s = committed("foo");
        assert_eq!(s.matches().len(), 3);
        s.refresh("foo");
        assert_eq!(s.matches().len(), 1, "matches follow the new text");
    }

    #[test]
    fn pushing_into_a_closed_prompt_is_a_no_op_not_a_panic() {
        let mut s = SearchState::new(CaseMode::Smart);
        s.push('x');
        assert!(!s.is_prompting());
        assert!(!s.backspace());
        assert_eq!(s.cancel(), None);
    }

    // ── caret editing ───────────────────────────────────────────────────

    fn prompting(text: &str) -> SearchState {
        let mut st = SearchState::new(CaseMode::Smart);
        st.open(Direction::Forward, 0);
        for c in text.chars() {
            st.push(c);
        }
        st
    }

    fn shown(st: &SearchState) -> (String, usize) {
        let p = st.prompt().expect("prompting");
        (p.text.clone(), p.caret())
    }

    #[test]
    fn typing_appends_and_the_caret_follows() {
        let st = prompting("foo");
        assert_eq!(shown(&st), ("foo".to_string(), 3));
    }

    #[test]
    fn a_character_typed_mid_pattern_lands_at_the_caret() {
        // The complaint this exists for: fixing a typo in the middle.
        let mut st = prompting("fo");
        st.move_caret(CaretMove::Left);
        st.push('X');
        assert_eq!(shown(&st), ("fXo".to_string(), 2), "inserted AT the caret");
    }

    #[test]
    fn backspace_deletes_before_the_caret_not_at_the_end() {
        let mut st = prompting("abc");
        st.move_caret(CaretMove::Left); // between b and c
        assert!(!st.backspace());
        assert_eq!(shown(&st), ("ac".to_string(), 1), "deleted `b`, not `c`");
    }

    #[test]
    fn delete_at_caret_removes_the_character_ahead() {
        let mut st = prompting("abc");
        st.move_caret(CaretMove::Start);
        st.delete_at_caret();
        assert_eq!(shown(&st), ("bc".to_string(), 0));
    }

    #[test]
    fn forward_delete_never_closes_the_prompt() {
        // Emptying the text rightwards is not the "backspaced past the /"
        // gesture, so the prompt must survive it.
        let mut st = prompting("a");
        st.move_caret(CaretMove::Start);
        st.delete_at_caret();
        assert!(st.is_prompting(), "prompt must stay open");
        assert_eq!(shown(&st), (String::new(), 0));
    }

    #[test]
    fn backspace_at_the_start_with_text_ahead_is_a_no_op_not_a_cancel() {
        // Losing a typed pattern because the caret happened to be at column 0
        // would be the worst kind of surprise.
        let mut st = prompting("abc");
        st.move_caret(CaretMove::Start);
        assert!(!st.backspace(), "must not report a close");
        assert!(st.is_prompting(), "prompt survives");
        assert_eq!(shown(&st), ("abc".to_string(), 0), "text untouched");
    }

    #[test]
    fn backspace_on_an_empty_prompt_still_closes_it() {
        // The vim gesture must keep working.
        let mut st = prompting("");
        assert!(st.backspace(), "empty + backspace closes");
        assert!(!st.is_prompting());
    }

    #[test]
    fn caret_movement_saturates_at_both_ends() {
        let mut st = prompting("ab");
        for _ in 0..5 {
            st.move_caret(CaretMove::Left);
        }
        assert_eq!(shown(&st).1, 0, "cannot go left of the start");
        for _ in 0..5 {
            st.move_caret(CaretMove::Right);
        }
        assert_eq!(shown(&st).1, 2, "cannot go right of the end");
    }

    #[test]
    fn start_and_end_jump_the_caret() {
        let mut st = prompting("hello");
        st.move_caret(CaretMove::Start);
        assert_eq!(shown(&st).1, 0);
        st.move_caret(CaretMove::End);
        assert_eq!(shown(&st).1, 5);
    }

    #[test]
    fn the_caret_counts_CHARS_not_bytes() {
        // A byte caret lands mid-codepoint the first time anyone searches for
        // an accented word, and `String::insert` then panics.
        let mut st = prompting("héllo");
        st.move_caret(CaretMove::Start);
        st.move_caret(CaretMove::Right);
        st.move_caret(CaretMove::Right); // after `é`
        st.push('X');
        assert_eq!(shown(&st), ("héXllo".to_string(), 3));
    }

    #[test]
    fn editing_multibyte_text_backwards_does_not_panic() {
        let mut st = prompting("🔥é日");
        st.move_caret(CaretMove::End);
        assert!(!st.backspace());
        assert!(!st.backspace());
        assert_eq!(shown(&st), ("🔥".to_string(), 1));
    }

    #[test]
    fn ctrl_w_deletes_the_word_before_the_caret() {
        let mut st = prompting("foo bar");
        st.delete_word_before_caret();
        assert_eq!(shown(&st), ("foo ".to_string(), 4));
    }

    #[test]
    fn a_second_ctrl_w_eats_the_gap_and_the_next_word() {
        // Whitespace first, then the word — otherwise the second press only
        // removes the space and feels broken.
        let mut st = prompting("foo bar");
        st.delete_word_before_caret();
        st.delete_word_before_caret();
        assert_eq!(shown(&st), (String::new(), 0));
    }

    #[test]
    fn ctrl_w_keeps_what_is_ahead_of_the_caret() {
        let mut st = prompting("foo bar");
        st.move_caret(CaretMove::Start);
        st.move_caret(CaretMove::Right);
        st.move_caret(CaretMove::Right);
        st.move_caret(CaretMove::Right); // after "foo"
        st.delete_word_before_caret();
        assert_eq!(shown(&st), (" bar".to_string(), 0));
    }

    #[test]
    fn ctrl_u_clears_back_to_the_start_only() {
        let mut st = prompting("abcdef");
        st.move_caret(CaretMove::Start);
        for _ in 0..3 {
            st.move_caret(CaretMove::Right);
        }
        st.clear_before_caret();
        assert_eq!(shown(&st), ("def".to_string(), 0));
    }

    #[test]
    fn history_recall_parks_the_caret_at_the_end() {
        let mut st = SearchState::new(CaseMode::Smart);
        st.open(Direction::Forward, 0);
        for c in "alpha".chars() {
            st.push(c);
        }
        let _ = st.accept("alpha beta");

        st.open(Direction::Forward, 0);
        st.history_step(true);
        let (text, caret) = shown(&st);
        assert_eq!(caret, text.chars().count(), "continue typing at the end");
    }

    #[test]
    fn the_caret_never_exceeds_the_text_length() {
        // The standing invariant, exercised across a mixed edit sequence.
        let mut st = prompting("hello");
        let ops: &[CaretMove] = &[
            CaretMove::End,
            CaretMove::Left,
            CaretMove::Start,
            CaretMove::Right,
        ];
        for op in ops {
            st.move_caret(*op);
            st.delete_at_caret();
            let (t, c) = shown(&st);
            assert!(c <= t.chars().count(), "caret {c} past {t:?}");
        }
    }
}