alma 0.1.0

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
//! Literal Vim-style search state and helpers.

use bevy::prelude::Resource;

use super::{
    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;

/// 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 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) -> SearchCaseSensitivity {
        if self.text.chars().any(char::is_uppercase) {
            SearchCaseSensitivity::Sensitive
        } else {
            SearchCaseSensitivity::Insensitive
        }
    }

    /// Returns whether the query is empty.
    #[must_use]
    pub 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) -> 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)
    }

    /// Repeats the last submitted query in `direction`.
    pub fn repeat(
        &mut self,
        text: &str,
        cursor_byte_index: usize,
        direction: SearchDirection,
    ) -> 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)
    }

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

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

    /// 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,
    ) -> 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)
    }

    /// 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,
    ) -> SearchOutcome {
        let outcome = find_literal(text, cursor_byte_index, query, direction, true).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,
    wrap: bool,
) -> Option<usize> {
    if text.is_empty() || query.is_empty() {
        return None;
    }

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

/// 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>,
) -> Vec<std::ops::Range<usize>> {
    let Some(matcher) = LiteralMatcher::new(query) else {
        return Vec::new();
    };

    let start = clamp_to_boundary(text, visible_range.start.min(text.len()));
    let end = clamp_to_boundary(text, visible_range.end.min(text.len()));
    let mut ranges = Vec::new();

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

    ranges
}

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

    find_first_match_at_or_after(text, start, &matcher)
        .or_else(|| {
            wrap.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,
    wrap: bool,
) -> Option<usize> {
    let start = clamp_to_boundary(text, cursor_byte_index);
    let matcher = LiteralMatcher::new(query)?;

    find_last_match_before(text, start, &matcher)
        .or_else(|| {
            wrap.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) -> Option<Self> {
        (!query.is_empty()).then(|| Self {
            query_chars: query.as_str().chars().collect(),
            case_sensitivity: query.case_sensitivity(),
        })
    }

    /// 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;

    #[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, true),
            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,
                true,
            ),
            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, true),
            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,
                true,
            ),
            Some("one ".len())
        );
        assert_eq!(
            find_literal("one two", 0, &query, SearchDirection::Backward, true),
            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, true),
            None
        );
        assert_eq!(
            state.repeat_forward("abc", 0),
            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(), SearchCaseSensitivity::Insensitive);
        assert_eq!(
            find_literal("ALMA alma", 0, &query, SearchDirection::Forward, true),
            Some("ALMA ".len())
        );
        assert_eq!(
            find_literal("ALMA", 0, &query, SearchDirection::Forward, true),
            Some(0)
        );
    }

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

        assert_eq!(query.case_sensitivity(), SearchCaseSensitivity::Sensitive);
        assert_eq!(
            find_literal("ALMA alva", 0, &query, SearchDirection::Forward, true),
            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, true),
            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),
            SearchOutcome::Match {
                byte_index: "one ".len()
            }
        );
        assert_eq!(
            state.repeat_forward("one two one two", "one two".len()),
            SearchOutcome::Match {
                byte_index: "one two one ".len()
            }
        );
        assert_eq!(
            state.repeat_backward("one two one two", "one two one ".len()),
            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()),
            SearchOutcome::Match {
                byte_index: "one two one ".len()
            }
        );
        assert_eq!(
            state.repeat_relative(text, "one two one ".len(), SearchRepeatDirection::Next),
            SearchOutcome::Match {
                byte_index: "one ".len()
            }
        );
        assert_eq!(
            state.repeat_relative(text, "one ".len(), SearchRepeatDirection::Previous),
            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),
            SearchOutcome::Error(VimError::NoPreviousRegularExpression)
        );

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

        state.start(SearchDirection::Forward);
        assert_eq!(
            state.submit("one two one two", "one ".len()),
            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()),
            vec![0..4, 5..9]
        );
    }
}