alma 0.1.1

A Bevy-native modal text editor with Vim-style navigation.
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
//! Literal Vim-style search state and helpers.

use bevy::prelude::Resource;
use std::num::NonZeroUsize;

use crate::StatusInfoText;

use super::{
    config::VimOptions,
    error::VimError,
    motion::{clamp_to_boundary, clamp_to_cursor_position},
};

/// Maximum accepted search query length in Unicode scalar values.
const MAX_SEARCH_QUERY_CHARS: usize = 256;
/// Maximum bytes scanned per visible range for search highlighting.
const DEFAULT_SEARCH_HIGHLIGHT_SCAN_BYTES: usize = 64 * 1024;

/// Direction for literal search.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum SearchDirection {
    /// Search toward larger byte indices.
    Forward,
    /// Search toward smaller byte indices.
    Backward,
}

/// Direction for Vim search repeat commands.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum SearchRepeatDirection {
    /// Continue in the direction used by the previous submitted search.
    Next,
    /// Search opposite the previous submitted search direction.
    Previous,
}

/// User-provided literal search query.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct SearchQuery {
    /// Literal query text.
    text: String,
}

impl SearchQuery {
    /// Creates an empty search query.
    #[must_use]
    pub const fn new() -> Self {
        Self {
            text: String::new(),
        }
    }

    /// Reads the query text.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.text
    }

    /// Returns query text escaped for one-line status prompt rendering.
    #[must_use]
    pub fn status_text(&self) -> StatusInfoText {
        StatusInfoText::escaped_display(&self.text)
    }

    /// Returns the query length in bytes.
    #[must_use]
    pub const fn byte_len(&self) -> usize {
        self.text.len()
    }

    /// Returns the case policy implied by the query text.
    ///
    /// This mirrors Vim smartcase-style search: any uppercase scalar makes the search
    /// case-sensitive; otherwise literal matching ignores case.
    #[must_use]
    pub fn case_sensitivity(&self, options: &VimOptions) -> SearchCaseSensitivity {
        if !options.ignore_case || (options.smart_case && self.text.chars().any(char::is_uppercase))
        {
            SearchCaseSensitivity::Sensitive
        } else {
            SearchCaseSensitivity::Insensitive
        }
    }

    /// Returns whether the query is empty.
    #[must_use]
    pub const fn is_empty(&self) -> bool {
        self.text.is_empty()
    }

    /// Appends text, truncating at the configured scalar limit.
    pub fn push_str(&mut self, text: &str) {
        let remaining = MAX_SEARCH_QUERY_CHARS.saturating_sub(self.text.chars().count());
        self.text.extend(text.chars().take(remaining));
    }

    /// Removes the previous Unicode scalar value.
    pub fn pop_char(&mut self) {
        let _removed = self.text.pop();
    }
}

/// Case policy for a submitted search query.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum SearchCaseSensitivity {
    /// Match query characters exactly.
    Sensitive,
    /// Match query characters without regard to case.
    Insensitive,
}

/// Outcome from submitting or repeating a search.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum SearchOutcome {
    /// Search moved to a matching byte index.
    Match {
        /// Byte index of the matching cursor cell.
        byte_index: usize,
    },
    /// Search failed with a Vim command-line error.
    Error(VimError),
}

/// Current search command state.
#[derive(Clone, Debug, Default, Eq, PartialEq, Resource)]
pub struct SearchState {
    /// Query currently being edited after `/`.
    active_query: Option<SearchQuery>,
    /// Direction for the active query.
    active_direction: Option<SearchDirection>,
    /// Last submitted query, reused by `n` and `N`.
    last_query: Option<SearchQuery>,
    /// Last submitted direction.
    last_direction: Option<SearchDirection>,
    /// Last terminal search outcome for status rendering.
    last_outcome: Option<SearchOutcome>,
}

/// Bevy resource wrapper for Vim search state.
pub type VimSearchState = SearchState;

impl SearchState {
    /// Starts editing a forward search query.
    pub fn start(&mut self, direction: SearchDirection) {
        self.active_query = Some(SearchQuery::new());
        self.active_direction = Some(direction);
        self.last_outcome = None;
    }

    /// Cancels active query editing.
    pub fn cancel(&mut self) {
        self.active_query = None;
        self.active_direction = None;
    }

    /// Returns whether a query is being edited.
    #[must_use]
    pub const fn is_active(&self) -> bool {
        self.active_query.is_some()
    }

    /// Reads the active query, if any.
    #[must_use]
    pub const fn active_query(&self) -> Option<&SearchQuery> {
        self.active_query.as_ref()
    }

    /// Reads the active query direction, if any.
    #[must_use]
    pub const fn active_direction(&self) -> Option<SearchDirection> {
        self.active_direction
    }

    /// Reads the last search outcome, if any.
    #[must_use]
    pub const fn last_outcome(&self) -> Option<SearchOutcome> {
        self.last_outcome
    }

    /// Reads the last submitted search query, if any.
    #[must_use]
    pub const fn last_query(&self) -> Option<&SearchQuery> {
        self.last_query.as_ref()
    }

    /// Reads the last submitted search direction, if any.
    #[must_use]
    pub const fn last_direction(&self) -> Option<SearchDirection> {
        self.last_direction
    }

    /// Appends text to the active query.
    pub fn push_text(&mut self, text: &str) {
        if let Some(query) = &mut self.active_query {
            query.push_str(text);
        }
    }

    /// Deletes the previous scalar from the active query.
    pub fn backspace(&mut self) {
        if let Some(query) = &mut self.active_query {
            query.pop_char();
        }
    }

    /// Submits the active query as a forward literal search.
    pub fn submit(
        &mut self,
        text: &str,
        cursor_byte_index: usize,
        options: &VimOptions,
    ) -> SearchOutcome {
        let Some(query) = self.active_query.take() else {
            return self.fail(VimError::NoPreviousRegularExpression);
        };
        let direction = self
            .active_direction
            .take()
            .unwrap_or(SearchDirection::Forward);

        let submitted_query = if query.is_empty() {
            let Some(last_query) = self.last_query.clone() else {
                return self.fail(VimError::NoPreviousRegularExpression);
            };

            last_query
        } else {
            self.last_query = Some(query.clone());
            query
        };

        self.last_direction = Some(direction);
        self.search_for_query(
            text,
            cursor_byte_index,
            &submitted_query,
            direction,
            options,
        )
    }

    /// Repeats the last submitted query in `direction`.
    pub fn repeat(
        &mut self,
        text: &str,
        cursor_byte_index: usize,
        direction: SearchDirection,
        options: &VimOptions,
    ) -> SearchOutcome {
        let Some(query) = &self.last_query else {
            return self.fail(VimError::NoPreviousRegularExpression);
        };

        let query = query.clone();
        self.last_direction = Some(direction);
        self.search_for_query(text, cursor_byte_index, &query, direction, options)
    }

    /// Repeats the last search forward.
    pub fn repeat_forward(
        &mut self,
        text: &str,
        cursor_byte_index: usize,
        options: &VimOptions,
    ) -> SearchOutcome {
        self.repeat(text, cursor_byte_index, SearchDirection::Forward, options)
    }

    /// Repeats the last search backward.
    pub fn repeat_backward(
        &mut self,
        text: &str,
        cursor_byte_index: usize,
        options: &VimOptions,
    ) -> SearchOutcome {
        self.repeat(text, cursor_byte_index, SearchDirection::Backward, options)
    }

    /// Repeats the last submitted query using Vim `n`/`N` semantics.
    pub fn repeat_relative(
        &mut self,
        text: &str,
        cursor_byte_index: usize,
        repeat_direction: SearchRepeatDirection,
        options: &VimOptions,
    ) -> SearchOutcome {
        let Some(last_direction) = self.last_direction else {
            return self.fail(VimError::NoPreviousRegularExpression);
        };
        let direction = match repeat_direction {
            SearchRepeatDirection::Next => last_direction,
            SearchRepeatDirection::Previous => last_direction.reversed(),
        };

        self.repeat(text, cursor_byte_index, direction, options)
    }

    /// Searches for a specific query and records the outcome.
    fn search_for_query(
        &mut self,
        text: &str,
        cursor_byte_index: usize,
        query: &SearchQuery,
        direction: SearchDirection,
        options: &VimOptions,
    ) -> SearchOutcome {
        let outcome = find_literal(text, cursor_byte_index, query, direction, options).map_or(
            SearchOutcome::Error(VimError::PatternNotFound),
            |byte_index| SearchOutcome::Match { byte_index },
        );
        self.last_outcome = Some(outcome);
        outcome
    }

    /// Records and returns a failed search outcome.
    const fn fail(&mut self, error: VimError) -> SearchOutcome {
        let outcome = SearchOutcome::Error(error);
        self.last_outcome = Some(outcome);
        outcome
    }
}

impl SearchDirection {
    /// Returns the opposite search direction.
    #[must_use]
    pub const fn reversed(self) -> Self {
        match self {
            Self::Forward => Self::Backward,
            Self::Backward => Self::Forward,
        }
    }
}

/// Finds a literal query from `cursor_byte_index`.
#[must_use]
pub fn find_literal(
    text: &str,
    cursor_byte_index: usize,
    query: &SearchQuery,
    direction: SearchDirection,
    options: &VimOptions,
) -> Option<usize> {
    if text.is_empty() || query.is_empty() {
        return None;
    }

    match direction {
        SearchDirection::Forward => find_forward(text, cursor_byte_index, query, options),
        SearchDirection::Backward => find_backward(text, cursor_byte_index, query, options),
    }
}

/// Returns byte ranges for every literal match that intersects `visible_range`.
#[must_use]
pub fn literal_match_ranges_in_range(
    text: &str,
    query: &SearchQuery,
    visible_range: std::ops::Range<usize>,
    options: &VimOptions,
) -> Vec<std::ops::Range<usize>> {
    let Some(matcher) = LiteralMatcher::new(query, options) else {
        return Vec::new();
    };
    let search_range = SearchHighlightRange::new(
        text,
        query,
        visible_range,
        SearchHighlightScanBudget::default(),
    );
    let mut ranges = Vec::new();

    for byte_index in text[search_range.scan.clone()]
        .char_indices()
        .map(|(offset, _character)| search_range.scan.start + offset)
    {
        if let Some(match_end) = matcher.match_end(text, byte_index)
            && match_end > search_range.visible.start
            && byte_index < search_range.visible.end
        {
            ranges.push(byte_index..match_end);
        }
    }

    ranges
}

/// Non-zero byte budget for one search-highlight scan.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
struct SearchHighlightScanBudget {
    /// Maximum number of bytes the highlighter may scan.
    max_bytes: NonZeroUsize,
}

impl SearchHighlightScanBudget {
    /// Creates a scan budget.
    const fn new(max_bytes: NonZeroUsize) -> Self {
        Self { max_bytes }
    }

    /// Returns the maximum number of bytes the highlighter may scan.
    const fn get(self) -> usize {
        self.max_bytes.get()
    }
}

impl Default for SearchHighlightScanBudget {
    fn default() -> Self {
        Self::new(
            NonZeroUsize::new(DEFAULT_SEARCH_HIGHLIGHT_SCAN_BYTES)
                .expect("default search highlight scan budget must be non-zero"),
        )
    }
}

/// Validated ranges for search highlighting.
struct SearchHighlightRange {
    /// Exact visible range whose intersections should be highlighted.
    visible: std::ops::Range<usize>,
    /// Boundary-aligned range to scan for matches that may begin before visibility.
    scan: std::ops::Range<usize>,
}

impl SearchHighlightRange {
    /// Builds a scan range that can find every match intersecting `visible_range`.
    fn new(
        text: &str,
        query: &SearchQuery,
        visible_range: std::ops::Range<usize>,
        budget: SearchHighlightScanBudget,
    ) -> Self {
        let visible_start = clamp_to_boundary(text, visible_range.start.min(text.len()));
        let scan_start = clamp_to_boundary(text, visible_start.saturating_sub(query.byte_len()));
        let budgeted_scan_end = scan_start.saturating_add(budget.get()).min(text.len());
        let visible_end = clamp_to_boundary(
            text,
            visible_range
                .end
                .min(text.len())
                .min(budgeted_scan_end)
                .max(visible_start),
        );

        Self {
            visible: visible_start..visible_end,
            scan: scan_start..visible_end,
        }
    }
}

/// Finds the next literal match, starting after the cursor cell.
fn find_forward(
    text: &str,
    cursor_byte_index: usize,
    query: &SearchQuery,
    options: &VimOptions,
) -> Option<usize> {
    let start = next_search_start(text, cursor_byte_index);
    let matcher = LiteralMatcher::new(query, options)?;

    find_first_match_at_or_after(text, start, &matcher)
        .or_else(|| {
            options
                .wrap_scan
                .then(|| find_first_match_before(text, start, &matcher))
                .flatten()
        })
        .map(|byte_index| clamp_to_cursor_position(text, byte_index))
}

/// Finds the previous literal match, starting before the cursor cell.
fn find_backward(
    text: &str,
    cursor_byte_index: usize,
    query: &SearchQuery,
    options: &VimOptions,
) -> Option<usize> {
    let start = clamp_to_boundary(text, cursor_byte_index);
    let matcher = LiteralMatcher::new(query, options)?;

    find_last_match_before(text, start, &matcher)
        .or_else(|| {
            options
                .wrap_scan
                .then(|| find_last_match_at_or_after(text, start, &matcher))
                .flatten()
        })
        .map(|byte_index| clamp_to_cursor_position(text, byte_index))
}

/// Prepared literal matcher for a search query.
struct LiteralMatcher {
    /// Query scalar values.
    query_chars: Vec<char>,
    /// Case matching policy.
    case_sensitivity: SearchCaseSensitivity,
}

impl LiteralMatcher {
    /// Creates a matcher for a non-empty query.
    fn new(query: &SearchQuery, options: &VimOptions) -> Option<Self> {
        (!query.is_empty()).then(|| Self {
            query_chars: query.as_str().chars().collect(),
            case_sensitivity: query.case_sensitivity(options),
        })
    }

    /// Returns whether the query matches at `byte_index`.
    fn matches_at(&self, text: &str, byte_index: usize) -> bool {
        self.match_end(text, byte_index).is_some()
    }

    /// Returns the match end byte index when the query matches at `byte_index`.
    fn match_end(&self, text: &str, byte_index: usize) -> Option<usize> {
        if !text.is_char_boundary(byte_index) {
            return None;
        }

        let mut text_characters = text[byte_index..].chars();
        let mut end = byte_index;

        for query_character in self.query_chars.iter().copied() {
            let text_character = text_characters.next()?;

            if !characters_match(text_character, query_character, self.case_sensitivity) {
                return None;
            }

            end += text_character.len_utf8();
        }

        Some(end)
    }
}

/// Finds the first match at or after `start`.
fn find_first_match_at_or_after(
    text: &str,
    start: usize,
    matcher: &LiteralMatcher,
) -> Option<usize> {
    text[start..]
        .char_indices()
        .map(|(offset, _character)| start + offset)
        .find(|byte_index| matcher.matches_at(text, *byte_index))
}

/// Finds the first match that starts before `start`.
fn find_first_match_before(text: &str, start: usize, matcher: &LiteralMatcher) -> Option<usize> {
    text.char_indices()
        .map(|(byte_index, _character)| byte_index)
        .take_while(|byte_index| *byte_index < start)
        .find(|byte_index| matcher.matches_at(text, *byte_index))
}

/// Finds the last match that starts before `start`.
fn find_last_match_before(text: &str, start: usize, matcher: &LiteralMatcher) -> Option<usize> {
    text.char_indices()
        .map(|(byte_index, _character)| byte_index)
        .take_while(|byte_index| *byte_index < start)
        .filter(|byte_index| matcher.matches_at(text, *byte_index))
        .last()
}

/// Finds the last match at or after `start`.
fn find_last_match_at_or_after(
    text: &str,
    start: usize,
    matcher: &LiteralMatcher,
) -> Option<usize> {
    text[start..]
        .char_indices()
        .map(|(offset, _character)| start + offset)
        .rfind(|byte_index| matcher.matches_at(text, *byte_index))
}

/// Returns whether two scalar values match under the selected case policy.
fn characters_match(
    text_character: char,
    query_character: char,
    case_sensitivity: SearchCaseSensitivity,
) -> bool {
    match case_sensitivity {
        SearchCaseSensitivity::Sensitive => text_character == query_character,
        SearchCaseSensitivity::Insensitive => text_character
            .to_lowercase()
            .eq(query_character.to_lowercase()),
    }
}

/// Returns the byte index after the current cursor cell.
fn next_search_start(text: &str, cursor_byte_index: usize) -> usize {
    let cursor = clamp_to_cursor_position(text, cursor_byte_index);

    text[cursor..]
        .chars()
        .next()
        .map_or(cursor, |character| cursor + character.len_utf8())
        .min(text.len())
}

#[cfg(test)]
mod tests {
    use super::{
        SearchCaseSensitivity, SearchDirection, SearchOutcome, SearchQuery, SearchRepeatDirection,
        SearchState, find_literal,
    };
    use crate::vim::{VimError, VimOptions};

    fn options() -> VimOptions {
        VimOptions::default()
    }

    #[test]
    fn forward_search_finds_match_after_cursor() {
        let mut query = SearchQuery::new();
        query.push_str("two");

        assert_eq!(
            find_literal(
                "one two one two",
                0,
                &query,
                SearchDirection::Forward,
                &options()
            ),
            Some("one ".len())
        );
    }

    #[test]
    fn forward_search_wraps_to_first_match() {
        let mut query = SearchQuery::new();
        query.push_str("one");

        assert_eq!(
            find_literal(
                "one two",
                "one two".len(),
                &query,
                SearchDirection::Forward,
                &options(),
            ),
            Some(0)
        );
    }

    #[test]
    fn forward_search_wrap_can_find_match_starting_at_cursor() {
        let mut query = SearchQuery::new();
        query.push_str("ALMA");

        assert_eq!(
            find_literal("ALMA", 0, &query, SearchDirection::Forward, &options()),
            Some(0)
        );
    }

    #[test]
    fn backward_search_finds_previous_match_and_wraps() {
        let mut query = SearchQuery::new();
        query.push_str("two");

        assert_eq!(
            find_literal(
                "one two one two",
                "one two one".len(),
                &query,
                SearchDirection::Backward,
                &options(),
            ),
            Some("one ".len())
        );
        assert_eq!(
            find_literal("one two", 0, &query, SearchDirection::Backward, &options()),
            Some("one ".len())
        );
    }

    #[test]
    fn empty_or_missing_query_does_not_move() {
        let query = SearchQuery::new();
        let mut state = SearchState::default();

        assert_eq!(
            find_literal("abc", 0, &query, SearchDirection::Forward, &options()),
            None
        );
        assert_eq!(
            state.repeat_forward("abc", 0, &options()),
            SearchOutcome::Error(VimError::NoPreviousRegularExpression)
        );
    }

    #[test]
    fn lowercase_queries_match_case_insensitively() {
        let mut query = SearchQuery::new();
        query.push_str("alma");

        assert_eq!(
            query.case_sensitivity(&options()),
            SearchCaseSensitivity::Insensitive
        );
        assert_eq!(
            find_literal("ALMA alma", 0, &query, SearchDirection::Forward, &options()),
            Some("ALMA ".len())
        );
        assert_eq!(
            find_literal("ALMA", 0, &query, SearchDirection::Forward, &options()),
            Some(0)
        );
    }

    #[test]
    fn uppercase_queries_match_case_sensitively() {
        let mut query = SearchQuery::new();
        query.push_str("Alma");

        assert_eq!(
            query.case_sensitivity(&options()),
            SearchCaseSensitivity::Sensitive
        );
        assert_eq!(
            find_literal("ALMA alva", 0, &query, SearchDirection::Forward, &options()),
            None
        );
    }

    #[test]
    fn unicode_search_stays_boundary_safe() {
        let mut query = SearchQuery::new();
        query.push_str("λ");

        assert_eq!(
            find_literal("Aλ Bλ", 0, &query, SearchDirection::Forward, &options()),
            Some("A".len())
        );
    }

    #[test]
    fn repeat_keys_reuse_last_submitted_query() {
        let mut state = SearchState::default();
        state.start(SearchDirection::Forward);
        state.push_text("two");

        assert_eq!(
            state.submit("one two one two", 0, &options()),
            SearchOutcome::Match {
                byte_index: "one ".len()
            }
        );
        assert_eq!(
            state.repeat_forward("one two one two", "one two".len(), &options()),
            SearchOutcome::Match {
                byte_index: "one two one ".len()
            }
        );
        assert_eq!(
            state.repeat_backward("one two one two", "one two one ".len(), &options()),
            SearchOutcome::Match {
                byte_index: "one ".len()
            }
        );
    }

    #[test]
    fn relative_repeat_keys_follow_last_search_direction() {
        let text = "one two one two";
        let mut state = SearchState::default();
        state.start(SearchDirection::Backward);
        state.push_text("two");

        assert_eq!(
            state.submit(text, text.len(), &options()),
            SearchOutcome::Match {
                byte_index: "one two one ".len()
            }
        );
        assert_eq!(
            state.repeat_relative(
                text,
                "one two one ".len(),
                SearchRepeatDirection::Next,
                &options()
            ),
            SearchOutcome::Match {
                byte_index: "one ".len()
            }
        );
        assert_eq!(
            state.repeat_relative(
                text,
                "one ".len(),
                SearchRepeatDirection::Previous,
                &options()
            ),
            SearchOutcome::Match {
                byte_index: "one two one ".len()
            }
        );
    }

    #[test]
    fn empty_submit_repeats_previous_search_or_reports_e35() {
        let mut state = SearchState::default();

        state.start(SearchDirection::Forward);
        assert_eq!(
            state.submit("one two", 0, &options()),
            SearchOutcome::Error(VimError::NoPreviousRegularExpression)
        );

        state.start(SearchDirection::Forward);
        state.push_text("two");
        assert_eq!(
            state.submit("one two one two", 0, &options()),
            SearchOutcome::Match {
                byte_index: "one ".len()
            }
        );

        state.start(SearchDirection::Forward);
        assert_eq!(
            state.submit("one two one two", "one ".len(), &options()),
            SearchOutcome::Match {
                byte_index: "one two one ".len()
            }
        );
    }

    #[test]
    fn literal_match_ranges_cover_visible_occurrences() {
        let mut query = SearchQuery::new();
        query.push_str("alma");

        assert_eq!(
            super::literal_match_ranges_in_range(
                "ALMA alma λ",
                &query,
                0.."ALMA alma λ".len(),
                &options()
            ),
            vec![0..4, 5..9]
        );
    }

    #[test]
    fn literal_match_ranges_include_matches_starting_before_visible_range() {
        let mut query = SearchQuery::new();
        query.push_str("a\nb");
        let text = "a\nbc";

        assert_eq!(
            super::literal_match_ranges_in_range(text, &query, 1..text.len(), &options()),
            vec![0..3]
        );
    }

    #[test]
    fn literal_match_ranges_are_bounded_for_long_visible_lines() {
        let mut query = SearchQuery::new();
        query.push_str("zz");
        let text = format!(
            "{}zz",
            "a".repeat(super::DEFAULT_SEARCH_HIGHLIGHT_SCAN_BYTES + 128)
        );

        assert_eq!(
            super::literal_match_ranges_in_range(text.as_str(), &query, 0..text.len(), &options()),
            Vec::<std::ops::Range<usize>>::new()
        );
    }

    #[test]
    fn search_options_control_case_and_wrapping() {
        let mut query = SearchQuery::new();
        query.push_str("alma");
        let sensitive = VimOptions {
            ignore_case: false,
            ..VimOptions::default()
        };
        let no_smart_case = VimOptions {
            smart_case: false,
            ..VimOptions::default()
        };
        let no_wrap = VimOptions {
            wrap_scan: false,
            ..VimOptions::default()
        };

        assert_eq!(
            find_literal("ALMA alma", 0, &query, SearchDirection::Forward, &sensitive),
            Some("ALMA ".len())
        );

        query = SearchQuery::new();
        query.push_str("Alma");
        assert_eq!(
            find_literal(
                "ALMA Alma",
                "ALMA Alma".len(),
                &query,
                SearchDirection::Forward,
                &no_smart_case
            ),
            Some(0)
        );
        query = SearchQuery::new();
        query.push_str("alma");
        assert_eq!(
            find_literal(
                "alma",
                "alma".len(),
                &query,
                SearchDirection::Forward,
                &no_wrap
            ),
            None
        );
    }
}