Skip to main content

indigo_core/
cursor.rs

1use crate::text::{Anchor, Text};
2use indigo_text::{
3    display_width::DisplayWidth as _,
4    edit::{self, Edit},
5    rope::{LINE_TYPE, RopeExt as _},
6};
7use indigo_wrap::{WBox, WMut, WRef, Wrap, WrapMut, WrapRef};
8use ropey::{Rope, RopeSlice};
9use std::{borrow::Cow, cmp::min, ops::Deref, thread};
10use thiserror::Error;
11
12#[derive(Debug, Error)]
13pub enum Error {
14    #[error("Byte index {byte_index} is not within text of length {length}")]
15    OutOfRange { byte_index: usize, length: usize },
16
17    #[error("Byte index {byte_index} is not the start of a grapheme")]
18    NotOnGrapheme { byte_index: usize },
19
20    #[error("Error from text")]
21    Text(#[source] anyhow::Error),
22}
23
24#[derive(Clone, Copy)]
25pub enum Direction {
26    Backward,
27    Forward,
28}
29
30#[derive(Clone, Copy, Debug, PartialEq)]
31pub enum GoalColumn {
32    Column(usize),
33    UntilLineEnd,
34    OntoLineEnd,
35}
36
37#[derive(Clone, Debug, Default)]
38pub struct CursorState {
39    pub byte_index: usize,
40}
41
42impl CursorState {
43    pub fn transform(&mut self, ops: &Edit, text: &Rope) {
44        let byte_index = ops.map_position(self.byte_index, edit::Bias::Forward);
45        self.byte_index = text
46            .snap_to_grapheme_start(byte_index)
47            .expect("Text is never empty");
48    }
49
50    #[must_use]
51    pub fn save(&self, text: &Text) -> CursorSnapshot {
52        let byte_index = text.create_anchor(self.byte_index);
53        CursorSnapshot { byte_index }
54    }
55}
56
57pub struct CursorSnapshot {
58    pub byte_index: Anchor,
59}
60
61impl CursorSnapshot {
62    #[must_use]
63    pub fn restore(&self, text: &Text) -> Option<CursorState> {
64        let byte_index = text
65            .snap_to_grapheme_start(text.resolve_anchor(&self.byte_index)?)
66            .expect("Text is never empty");
67        Some(CursorState { byte_index })
68    }
69}
70
71#[must_use]
72pub struct CursorView<'a, S: Wrap, T: Wrap> {
73    state: S::Wrap<'a, CursorState>,
74    text: T::Wrap<'a, Text>,
75    on_drop: Option<fn(&mut Self)>,
76}
77
78pub type Cursor<'a> = CursorView<'a, WRef, WRef>;
79
80pub type CursorMove<'a> = CursorView<'a, WMut, WRef>;
81
82pub type CursorEdit<'a> = CursorView<'a, WMut, WMut>;
83
84impl<S: WrapRef, T: Wrap> Deref for CursorView<'_, S, T> {
85    type Target = CursorState;
86
87    fn deref(&self) -> &Self::Target {
88        &self.state
89    }
90}
91
92impl<S: Wrap, T: Wrap> CursorView<'_, S, T> {
93    pub fn on_drop(mut self, f: fn(&mut Self)) -> Self {
94        self.on_drop = Some(f);
95        self
96    }
97}
98
99impl<'a, S: WrapRef, T: WrapRef> CursorView<'a, S, T> {
100    pub fn new(
101        text: T::WrapRef<'a, Text>,
102        state: S::WrapRef<'a, CursorState>,
103    ) -> anyhow::Result<Self> {
104        let cursor_view = Self {
105            state,
106            text,
107            on_drop: None,
108        };
109        if cfg!(debug_assertions) {
110            cursor_view.assert_invariants()?;
111        }
112        Ok(cursor_view)
113    }
114
115    pub fn text(&self) -> &Text {
116        &self.text
117    }
118
119    #[must_use]
120    pub fn line_index(&self) -> usize {
121        self.text.byte_to_line_idx(self.state.byte_index, LINE_TYPE)
122    }
123
124    #[must_use]
125    pub fn line_number(&self) -> usize {
126        self.line_index() + 1
127    }
128
129    #[must_use]
130    pub fn column_number(&self) -> usize {
131        let line_byte_index = self.text.line_to_byte_idx(self.line_index(), LINE_TYPE);
132        (self.state.byte_index - line_byte_index) + 1
133    }
134
135    #[must_use]
136    pub fn display_column(&self) -> usize {
137        self.text.display_column(self.state.byte_index)
138    }
139
140    #[must_use]
141    pub fn grapheme(&self) -> RopeSlice<'_> {
142        self.text.grapheme(self.state.byte_index)
143    }
144
145    #[must_use]
146    pub fn line(&self) -> RopeSlice<'_> {
147        self.text
148            .get_line(self.line_index(), LINE_TYPE)
149            .expect("Cursor's line always exists")
150    }
151
152    #[must_use]
153    pub fn is_at_start(&self) -> bool {
154        self.state.byte_index == 0
155    }
156
157    #[must_use]
158    pub fn is_at_end(&self) -> bool {
159        let end_offset = self
160            .text
161            .next_grapheme_boundary(self.state.byte_index)
162            .expect("Cursor is always on a grapheme");
163        end_offset == self.text.len()
164    }
165
166    #[must_use]
167    pub fn save(&self) -> CursorSnapshot {
168        self.state.save(&self.text)
169    }
170
171    pub fn assert_invariants(&self) -> anyhow::Result<()> {
172        self.text.assert_invariants().map_err(Error::Text)?;
173        if self.state.byte_index >= self.text.len() {
174            anyhow::bail!(Error::OutOfRange {
175                byte_index: self.state.byte_index,
176                length: self.text.len(),
177            });
178        }
179        if !self.text.is_grapheme_start(self.state.byte_index) {
180            anyhow::bail!(Error::NotOnGrapheme {
181                byte_index: self.state.byte_index,
182            });
183        }
184        Ok(())
185    }
186}
187
188impl<S: WrapMut, T: WrapRef> CursorView<'_, S, T> {
189    pub fn move_to(&mut self, byte_index: usize) {
190        let byte_index = self
191            .text
192            .snap_to_grapheme_start(byte_index)
193            .expect("Text is never empty");
194        self.state.byte_index = byte_index;
195    }
196
197    pub fn move_left(&mut self, count: usize) -> bool {
198        if count == 0 {
199            return false;
200        }
201        for _ in 0..count {
202            if let Some(prev) = self.text.prev_grapheme_boundary(self.state.byte_index) {
203                self.state.byte_index = prev;
204            } else {
205                return false;
206            }
207        }
208        true
209    }
210
211    pub fn move_right(&mut self, count: usize) -> bool {
212        if count == 0 {
213            return false;
214        }
215        for _ in 0..count {
216            match self.text.next_grapheme_boundary(self.state.byte_index) {
217                Some(next) if next < self.text.len() => self.state.byte_index = next,
218                _ => return false,
219            }
220        }
221        true
222    }
223
224    pub fn move_up(&mut self, goal_column: GoalColumn, count: usize) -> bool {
225        self.move_vertical(Direction::Backward, goal_column, count)
226    }
227
228    pub fn move_down(&mut self, goal_column: GoalColumn, count: usize) -> bool {
229        self.move_vertical(Direction::Forward, goal_column, count)
230    }
231
232    fn move_vertical(
233        &mut self,
234        direction: Direction,
235        goal_column: GoalColumn,
236        count: usize,
237    ) -> bool {
238        if count == 0 {
239            return false;
240        }
241        let old_byte_index = self.state.byte_index;
242        let current_line_index = self.text.byte_to_line_idx(self.state.byte_index, LINE_TYPE);
243        // Like Kakoune, clamp to the first or last line, and still apply the goal column. A cursor
244        // on the newline of the first or last line then moves onto that line's last grapheme.
245        let target_line_index = match direction {
246            Direction::Backward => current_line_index.saturating_sub(count),
247            Direction::Forward => min(
248                current_line_index.saturating_add(count),
249                self.text.len_lines_unix() - 1,
250            ),
251        };
252        let target_line_byte_index = self.text.line_to_byte_idx(target_line_index, LINE_TYPE);
253        let target_line_slice = self.text.line(target_line_index, LINE_TYPE);
254        let mut target_line_prefix = 0;
255        let mut target_byte_index = target_line_byte_index;
256        let mut reached_line_end = true;
257        for grapheme in target_line_slice.graphemes() {
258            if grapheme.chars().any(|c| c == '\n' || c == '\r') {
259                break;
260            }
261            let grapheme_width = grapheme.display_width();
262            if let GoalColumn::Column(n) = goal_column
263                && target_line_prefix + grapheme_width > n
264            {
265                reached_line_end = false;
266                break;
267            }
268            target_line_prefix += grapheme_width;
269            target_byte_index += grapheme.len();
270        }
271        // Only an empty line or `GoalColumn::OntoLineEnd` puts the cursor on the newline;
272        // otherwise stop on the last grapheme before it, like Kakoune.
273        if reached_line_end
274            && goal_column != GoalColumn::OntoLineEnd
275            && target_byte_index > target_line_byte_index
276        {
277            target_byte_index = self
278                .text
279                .prev_grapheme_boundary(target_byte_index)
280                .expect("Line is not empty, so a grapheme precedes its end");
281        }
282        self.state.byte_index = target_byte_index;
283        self.state.byte_index != old_byte_index
284    }
285
286    pub fn move_to_prev_byte(&mut self, byte: u8, count: usize) -> bool {
287        self.seek_prev(&[byte], count)
288    }
289
290    pub fn move_to_next_byte(&mut self, byte: u8, count: usize) -> bool {
291        self.seek_next(&[byte], count)
292    }
293
294    pub fn move_to_prev_blank(&mut self, count: usize) -> bool {
295        const BYTES: &[u8] = b" \t\n\r";
296        self.seek_prev(BYTES, count)
297    }
298
299    pub fn move_to_next_blank(&mut self, count: usize) -> bool {
300        const BYTES: &[u8] = b" \t\n\r";
301        self.seek_next(BYTES, count)
302    }
303
304    /// Land on the grapheme containing the `count`th previous matching byte. The cursor stays put
305    /// unless every step succeeds.
306    fn seek_prev(&mut self, bytes: &[u8], count: usize) -> bool {
307        if count == 0 {
308            return false;
309        }
310        let mut byte_index = self.state.byte_index;
311        for _ in 0..count {
312            let Some(found) = self.text.find_prev_byte(..byte_index, bytes) else {
313                return false;
314            };
315            byte_index = self.text.floor_grapheme_boundary(found);
316        }
317        self.state.byte_index = byte_index;
318        true
319    }
320
321    /// Land on the grapheme containing the `count`th next matching byte, searching strictly after
322    /// the grapheme the cursor occupies. The cursor stays put unless every step succeeds.
323    fn seek_next(&mut self, bytes: &[u8], count: usize) -> bool {
324        if count == 0 {
325            return false;
326        }
327        let mut byte_index = self.state.byte_index;
328        for _ in 0..count {
329            let start = self
330                .text
331                .next_grapheme_boundary(byte_index)
332                .expect("Cursor is always on a grapheme");
333            let Some(found) = self.text.find_next_byte(start.., bytes) else {
334                return false;
335            };
336            byte_index = self.text.floor_grapheme_boundary(found);
337        }
338        self.state.byte_index = byte_index;
339        true
340    }
341
342    pub fn move_to_start(&mut self) {
343        self.state.byte_index = 0;
344    }
345
346    pub fn move_to_end(&mut self) {
347        self.state.byte_index = self
348            .text
349            .last_grapheme_start()
350            .expect("Text is never empty");
351    }
352
353    pub fn move_to_bottom(&mut self) {
354        self.move_to_end();
355        self.move_to_line_start();
356    }
357
358    pub fn move_to_line_start(&mut self) {
359        let line_index = self.text.byte_to_line_idx(self.state.byte_index, LINE_TYPE);
360        self.state.byte_index = self.text.line_to_byte_idx(line_index, LINE_TYPE);
361    }
362
363    pub fn move_to_line_non_blank_start(&mut self) {
364        let line_index = self.text.byte_to_line_idx(self.state.byte_index, LINE_TYPE);
365        let line_start_byte_index = self.text.line_to_byte_idx(line_index, LINE_TYPE);
366        let line_slice = self.text.line(line_index, LINE_TYPE);
367        let mut byte_index = line_start_byte_index;
368        for grapheme in line_slice.graphemes() {
369            if grapheme.chars().any(|c| c == '\n' || c == '\r') {
370                break;
371            }
372            if !grapheme.chars().all(char::is_whitespace) {
373                break;
374            }
375            byte_index += grapheme.len();
376        }
377        self.state.byte_index = byte_index;
378    }
379
380    /// Move onto the line's end: its `'\n'` (or `"\r\n"`) grapheme. Always succeeds because
381    /// every line is terminated.
382    pub fn move_to_line_end(&mut self) {
383        let line_index = self.text.byte_to_line_idx(self.state.byte_index, LINE_TYPE);
384        let line_start_byte_index = self.text.line_to_byte_idx(line_index, LINE_TYPE);
385        let line_slice = self.text.line(line_index, LINE_TYPE);
386        let mut byte_index = line_start_byte_index;
387        for grapheme in line_slice.graphemes() {
388            if grapheme.chars().any(|c| c == '\n' || c == '\r') {
389                break;
390            }
391            byte_index += grapheme.len();
392        }
393        self.state.byte_index = byte_index;
394    }
395
396    /// Move onto the last grapheme before the line's end. Stays on the line end grapheme when
397    /// the line is empty.
398    pub fn move_until_line_end(&mut self) {
399        self.move_to_line_end();
400        let line_index = self.text.byte_to_line_idx(self.state.byte_index, LINE_TYPE);
401        let line_start_byte_index = self.text.line_to_byte_idx(line_index, LINE_TYPE);
402        if self.state.byte_index > line_start_byte_index {
403            self.state.byte_index = self
404                .text
405                .prev_grapheme_boundary(self.state.byte_index)
406                .expect("Not at start of text");
407        }
408    }
409
410    pub fn restore(&mut self, snapshot: &CursorSnapshot) -> bool {
411        if let Some(state) = snapshot.restore(&self.text) {
412            *self.state = state;
413            true
414        } else {
415            false
416        }
417    }
418}
419
420impl<S: WrapMut, T: WrapMut> CursorView<'_, S, T> {
421    pub fn insert_char(&mut self, char: char) -> Edit {
422        self.insert(char.encode_utf8(&mut [0; 4]))
423    }
424
425    /// Insert before the grapheme the cursor occupies. The cursor stays on its grapheme (i.e.
426    /// ends up after the inserted text).
427    #[tracing::instrument(skip_all)]
428    pub fn insert(&mut self, text: &str) -> Edit {
429        let pre_text_len = self.text.len();
430        let mut ops = Edit::new();
431        ops.retain(self.state.byte_index);
432        ops.insert(text);
433        ops.retain_rest(&self.text)
434            .expect("Operations fit within text");
435        self.text.apply(&ops).expect("Operations are well formed");
436        self.state.transform(&ops, &self.text);
437        debug_assert_eq!(self.text.len(), pre_text_len + text.len());
438        ops
439    }
440
441    /// Delete the grapheme before the cursor. Behavior traditionally associated with the
442    /// Backspace key.
443    #[tracing::instrument(skip_all)]
444    pub fn delete_before(&mut self) -> Option<Edit> {
445        let start = self.text.prev_grapheme_boundary(self.state.byte_index)?;
446        let mut ops = Edit::new();
447        ops.retain(start);
448        ops.delete(&Cow::from(self.text.slice(start..self.state.byte_index)));
449        ops.retain_rest(&self.text)
450            .expect("Operations fit within text");
451        self.text.apply(&ops).expect("Operations are well formed");
452        self.state.transform(&ops, &self.text);
453        Some(ops)
454    }
455
456    /// Delete the grapheme the cursor occupies, unless it is the text's final newline. Behavior
457    /// traditionally associated with the Delete key.
458    #[tracing::instrument(skip_all)]
459    pub fn delete_after(&mut self) -> Option<Edit> {
460        let end = self
461            .text
462            .next_grapheme_boundary(self.state.byte_index)
463            .expect("Cursor is always on a grapheme");
464        if end == self.text.len() {
465            // Deleting the final newline would break the `Text` invariant.
466            return None;
467        }
468        let mut ops = Edit::new();
469        ops.retain(self.state.byte_index);
470        ops.delete(&Cow::from(self.text.slice(self.state.byte_index..end)));
471        ops.retain_rest(&self.text)
472            .expect("Operations fit within text");
473        self.text.apply(&ops).expect("Operations are well formed");
474        self.state.transform(&ops, &self.text);
475        Some(ops)
476    }
477}
478
479impl<R> TryFrom<(R, usize)> for CursorView<'_, WBox, WBox>
480where
481    R: Into<Text>,
482{
483    type Error = anyhow::Error;
484    fn try_from((text, byte_index): (R, usize)) -> anyhow::Result<Self> {
485        let text = Box::new(text.into());
486        let state = Box::new(CursorState { byte_index });
487        Self::new(text, state)
488    }
489}
490
491impl<S: Wrap, T: Wrap> Drop for CursorView<'_, S, T> {
492    fn drop(&mut self) {
493        if !thread::panicking()
494            && let Some(f) = self.on_drop.take()
495        {
496            f(self);
497        }
498    }
499}
500
501#[cfg(test)]
502mod tests {
503    use super::*;
504    use hegel::{TestCase, generators as gs};
505
506    #[test]
507    fn delete_before_can_merge_graphemes_past_cursor() {
508        // Cursor sits on a combining mark (U+036B) preceded by a Control (SUB, U+001A).
509        // Deleting the Control causes '@' and the combining mark to merge into a single
510        // grapheme cluster, so the cursor's post-transform position is no longer a grapheme
511        // start, and the snap floors it onto the merged grapheme.
512        let mut cursor = CursorView::try_from(("@\u{1a}\u{36b}", 2)).unwrap();
513        cursor.delete_before();
514        cursor.assert_invariants().unwrap();
515        // '@' merged with the combining mark into "@\u{36b}" (one grapheme starting at 0).
516        assert_eq!(cursor.byte_index, 0);
517        assert_eq!(**cursor.text, "@\u{36b}\n");
518    }
519
520    #[test]
521    fn insert_changes_grapheme_boundary() {
522        // combining acute accent (´)
523        let mut cursor = CursorView::try_from(("\u{0301}", 0)).unwrap();
524        cursor.insert("e");
525        cursor.assert_invariants().unwrap();
526    }
527
528    #[test]
529    fn move_to_next_byte_repeated_after_multibyte_match() {
530        let mut cursor = CursorView::try_from(("\nۉ", 3)).unwrap();
531        cursor.move_to_line_non_blank_start();
532        cursor.move_to_next_byte(219, 2);
533        cursor.assert_invariants().unwrap();
534    }
535
536    #[test]
537    fn move_to_next_blank_repeated_after_crlf_match() {
538        // `Text::from("\r")` normalizes to "\r\n", a single CRLF grapheme.
539        let mut cursor = CursorView::try_from(("\r", 0)).unwrap();
540        cursor.insert("\n");
541        cursor.move_left(27);
542        cursor.move_to_next_blank(10);
543        cursor.delete_after();
544        cursor.assert_invariants().unwrap();
545    }
546
547    #[test]
548    fn restore_snaps_to_grapheme_start_after_insert() {
549        let mut cursor = CursorView::try_from(("\u{0301}", 0)).unwrap();
550        let snapshot = cursor.save();
551        cursor.insert("e");
552        assert!(cursor.restore(&snapshot));
553        cursor.assert_invariants().unwrap();
554    }
555
556    #[test]
557    fn delete_after_preserves_final_newline() {
558        let mut cursor = CursorView::try_from(("x", 1)).unwrap();
559        assert_eq!(cursor.grapheme(), Rope::from("\n").slice(..));
560        assert_eq!(cursor.delete_after(), None);
561        assert_eq!(**cursor.text, "x\n");
562    }
563
564    #[test]
565    fn expected_behavior_left_right() {
566        let mut cursor = CursorView::try_from(("", 0)).unwrap();
567        cursor.assert_invariants().unwrap();
568
569        cursor.insert("hello");
570        assert_eq!(**cursor.text, "hello\n");
571        assert_eq!(cursor.byte_index, 5);
572
573        cursor.delete_before();
574        cursor.delete_before();
575        assert_eq!(**cursor.text, "hel\n");
576        assert_eq!(cursor.byte_index, 3);
577
578        cursor.move_left(2);
579        assert_eq!(cursor.byte_index, 1);
580
581        cursor.delete_after();
582        assert_eq!(cursor.byte_index, 1);
583        assert_eq!(**cursor.text, "hl\n");
584
585        cursor.move_right(1);
586        assert_eq!(cursor.byte_index, 2);
587        // The trailing newline is the last grapheme; can't move past it.
588        cursor.move_right(1);
589        assert_eq!(cursor.byte_index, 2);
590
591        // Deleting the grapheme under the cursor would delete the final newline; refused.
592        cursor.delete_after();
593        assert_eq!(**cursor.text, "hl\n");
594        assert_eq!(cursor.byte_index, 2);
595
596        cursor.delete_before();
597        cursor.delete_before();
598        assert_eq!(**cursor.text, "\n");
599        assert_eq!(cursor.byte_index, 0);
600
601        cursor.delete_before();
602        assert_eq!(**cursor.text, "\n");
603        assert_eq!(cursor.byte_index, 0);
604    }
605
606    #[test]
607    fn expected_behavior_up_down() {
608        let mut cursor = CursorView::try_from(("", 0)).unwrap();
609        cursor.assert_invariants().unwrap();
610
611        let text = "0\n234\n6789AB\n";
612        cursor.insert(text);
613        // On the invariant trailing newline (the empty final line the insert pushed down).
614        assert_eq!(cursor.grapheme(), Rope::from("\n").slice(..));
615        assert_eq!(cursor.line().to_string(), "\n");
616        assert_eq!(cursor.byte_index, 13);
617        assert_eq!(cursor.display_column(), 0);
618
619        cursor.move_left(1);
620        // On the newline terminating line 2.
621        assert_eq!(cursor.grapheme(), Rope::from("\n").slice(..));
622        assert_eq!(cursor.byte_index, 12);
623        assert_eq!(cursor.display_column(), 6);
624
625        cursor.move_up(GoalColumn::Column(cursor.display_column()), 1);
626        // On "4", the last grapheme of line 1, which is shorter than the goal column.
627        assert_eq!(cursor.grapheme(), Rope::from("4").slice(..));
628        assert_eq!(cursor.line().to_string(), "234\n");
629        assert_eq!(cursor.byte_index, 4);
630        assert_eq!(cursor.display_column(), 2);
631
632        cursor.move_left(1);
633        // On "3" in line 1.
634        assert_eq!(cursor.grapheme(), Rope::from("3").slice(..));
635        assert_eq!(cursor.byte_index, 3);
636        assert_eq!(cursor.display_column(), 1);
637    }
638
639    #[test]
640    fn move_vertical_stops_before_newline() {
641        let mut cursor = CursorView::try_from(("a long line\nab\ncd\n", 7)).unwrap();
642        assert!(cursor.move_down(GoalColumn::Column(7), 1));
643        assert_eq!(cursor.grapheme(), Rope::from("b").slice(..));
644        assert_eq!(cursor.byte_index, 13);
645        // The goal column is sticky, so moving back up returns to the original grapheme.
646        assert!(cursor.move_up(GoalColumn::Column(7), 1));
647        assert_eq!(cursor.byte_index, 7);
648
649        // An empty line has nothing but its newline to land on.
650        let mut cursor = CursorView::try_from(("abc\n\nx\n", 2)).unwrap();
651        assert!(cursor.move_down(GoalColumn::Column(2), 1));
652        assert_eq!(cursor.grapheme(), Rope::from("\n").slice(..));
653        assert_eq!(cursor.byte_index, 4);
654
655        // Landing on a CRLF terminator steps back onto the last grapheme too.
656        let mut cursor = CursorView::try_from(("abc\r\nab\r\n", 2)).unwrap();
657        assert!(cursor.move_down(GoalColumn::Column(2), 1));
658        assert_eq!(cursor.grapheme(), Rope::from("b").slice(..));
659        assert_eq!(cursor.byte_index, 6);
660    }
661
662    #[test]
663    fn move_vertical_line_end_goal_columns() {
664        let mut cursor = CursorView::try_from(("ab\nabcdef\n", 1)).unwrap();
665        assert!(cursor.move_down(GoalColumn::UntilLineEnd, 1));
666        assert_eq!(cursor.grapheme(), Rope::from("f").slice(..));
667        assert_eq!(cursor.byte_index, 8);
668
669        let mut cursor = CursorView::try_from(("ab\nabcdef\n", 2)).unwrap();
670        assert!(cursor.move_down(GoalColumn::OntoLineEnd, 1));
671        assert_eq!(cursor.grapheme(), Rope::from("\n").slice(..));
672        assert_eq!(cursor.byte_index, 9);
673    }
674
675    #[test]
676    fn move_to_line_end() {
677        let mut cursor = CursorView::try_from(("x\ny\n", 2)).unwrap();
678        assert_eq!(cursor.grapheme(), Rope::from("y").slice(..));
679
680        cursor.move_to_line_end();
681        assert_eq!(cursor.byte_index, 3);
682        assert_eq!(cursor.grapheme(), Rope::from("\n").slice(..));
683
684        // Idempotent: already on the line end.
685        cursor.move_to_line_end();
686        assert_eq!(cursor.byte_index, 3);
687
688        cursor.move_until_line_end();
689        assert_eq!(cursor.byte_index, 2);
690        assert_eq!(cursor.grapheme(), Rope::from("y").slice(..));
691
692        // On an empty line, `move_until_line_end` stays on the line end.
693        let mut cursor = CursorView::try_from(("\nx\n", 0)).unwrap();
694        cursor.move_until_line_end();
695        assert_eq!(cursor.byte_index, 0);
696    }
697
698    #[test]
699    fn move_to_next_byte_count_skips_previous_matches() {
700        let mut cursor = CursorView::try_from(("hello world\n", 0)).unwrap();
701
702        assert!(cursor.move_to_next_byte(b'l', 1));
703        assert_eq!(cursor.byte_index, 2);
704
705        let mut cursor = CursorView::try_from(("hello world\n", 0)).unwrap();
706        assert!(cursor.move_to_next_byte(b'l', 2));
707        assert_eq!(cursor.byte_index, 3);
708
709        let mut cursor = CursorView::try_from(("hello world\n", 0)).unwrap();
710        assert!(cursor.move_to_next_byte(b'l', 3));
711        assert_eq!(cursor.byte_index, 9);
712
713        let mut cursor = CursorView::try_from(("hello world\n", 0)).unwrap();
714        assert!(!cursor.move_to_next_byte(b'l', 4));
715        assert_eq!(cursor.byte_index, 0);
716
717        let mut cursor = CursorView::try_from(("hello world\n", 11)).unwrap();
718        assert!(!cursor.move_to_prev_byte(b'l', 4));
719        assert_eq!(cursor.byte_index, 11);
720    }
721
722    #[test]
723    fn move_to_next_byte_skips_match_under_cursor() {
724        // Like Kakoune's `f`, the search starts after the grapheme the cursor occupies.
725        let mut cursor = CursorView::try_from(("ll\n", 0)).unwrap();
726        assert!(cursor.move_to_next_byte(b'l', 1));
727        assert_eq!(cursor.byte_index, 1);
728    }
729
730    #[test]
731    fn move_to_next_blank_count_skips_previous_matches() {
732        let mut cursor = CursorView::try_from(("a b\tc\n", 0)).unwrap();
733
734        assert!(cursor.move_to_next_blank(1));
735        assert_eq!(cursor.byte_index, 1);
736
737        let mut cursor = CursorView::try_from(("a b\tc\n", 0)).unwrap();
738        assert!(cursor.move_to_next_blank(2));
739        assert_eq!(cursor.byte_index, 3);
740
741        let mut cursor = CursorView::try_from(("a b\tc\n", 0)).unwrap();
742        assert!(cursor.move_to_next_blank(3));
743        assert_eq!(cursor.byte_index, 5);
744
745        let mut cursor = CursorView::try_from(("a b\tc\n", 0)).unwrap();
746        assert!(!cursor.move_to_next_blank(4));
747        assert_eq!(cursor.byte_index, 0);
748
749        let mut cursor = CursorView::try_from(("a b\tc\n", 4)).unwrap();
750        assert!(!cursor.move_to_prev_blank(3));
751        assert_eq!(cursor.byte_index, 4);
752    }
753
754    #[hegel::test(test_cases = 1_000)]
755    fn fuzz(tc: TestCase) {
756        #[derive(Default)]
757        struct StateMachine {
758            text: Text,
759            state: CursorState,
760        }
761        #[hegel::state_machine]
762        #[expect(clippy::needless_pass_by_value)]
763        impl StateMachine {
764            fn cursor(&mut self) -> CursorEdit<'_> {
765                CursorEdit::new(&mut self.text, &mut self.state).expect("Cursor state kept valid")
766            }
767            #[rule]
768            fn move_to(&mut self, tc: TestCase) {
769                let byte_index = tc.draw(gs::integers::<usize>().max_value(self.text.len()));
770                self.cursor().move_to(byte_index);
771            }
772            #[rule]
773            fn move_left(&mut self, tc: TestCase) {
774                let count = tc.draw(gs::integers::<usize>().min_value(1).max_value(100));
775                self.cursor().move_left(count);
776            }
777            #[rule]
778            fn move_right(&mut self, tc: TestCase) {
779                let count = tc.draw(gs::integers::<usize>().min_value(1).max_value(100));
780                self.cursor().move_right(count);
781            }
782            fn goal_column(cursor: &CursorEdit<'_>, tc: TestCase) -> GoalColumn {
783                match tc.draw(gs::integers::<u8>().max_value(2)) {
784                    0 => GoalColumn::Column(cursor.display_column()),
785                    1 => GoalColumn::UntilLineEnd,
786                    2 => GoalColumn::OntoLineEnd,
787                    _ => unreachable!(),
788                }
789            }
790            #[rule]
791            fn move_up(&mut self, tc: TestCase) {
792                let count = tc.draw(gs::integers::<usize>().min_value(1).max_value(100));
793                let mut cursor = self.cursor();
794                let goal_column = Self::goal_column(&cursor, tc);
795                cursor.move_up(goal_column, count);
796            }
797            #[rule]
798            fn move_down(&mut self, tc: TestCase) {
799                let count = tc.draw(gs::integers::<usize>().min_value(1).max_value(100));
800                let mut cursor = self.cursor();
801                let goal_column = Self::goal_column(&cursor, tc);
802                cursor.move_down(goal_column, count);
803            }
804            #[rule]
805            fn move_to_prev_byte(&mut self, tc: TestCase) {
806                let byte = tc.draw(gs::integers::<u8>());
807                let count = tc.draw(gs::integers::<usize>().min_value(1).max_value(100));
808                self.cursor().move_to_prev_byte(byte, count);
809            }
810            #[rule]
811            fn move_to_next_byte(&mut self, tc: TestCase) {
812                let byte = tc.draw(gs::integers::<u8>());
813                let count = tc.draw(gs::integers::<usize>().min_value(1).max_value(100));
814                self.cursor().move_to_next_byte(byte, count);
815            }
816            #[rule]
817            fn move_to_prev_blank(&mut self, tc: TestCase) {
818                let count = tc.draw(gs::integers::<usize>().min_value(1).max_value(100));
819                self.cursor().move_to_prev_blank(count);
820            }
821            #[rule]
822            fn move_to_next_blank(&mut self, tc: TestCase) {
823                let count = tc.draw(gs::integers::<usize>().min_value(1).max_value(100));
824                self.cursor().move_to_next_blank(count);
825            }
826            #[rule]
827            fn move_to_start(&mut self, _: TestCase) {
828                self.cursor().move_to_start();
829            }
830            #[rule]
831            fn move_to_end(&mut self, _: TestCase) {
832                self.cursor().move_to_end();
833            }
834            #[rule]
835            fn move_to_bottom(&mut self, _: TestCase) {
836                self.cursor().move_to_bottom();
837            }
838            #[rule]
839            fn move_to_line_start(&mut self, _: TestCase) {
840                self.cursor().move_to_line_start();
841            }
842            #[rule]
843            fn move_to_line_non_blank_start(&mut self, _: TestCase) {
844                self.cursor().move_to_line_non_blank_start();
845            }
846            #[rule]
847            fn move_to_line_end(&mut self, _: TestCase) {
848                self.cursor().move_to_line_end();
849            }
850            #[rule]
851            fn move_until_line_end(&mut self, _: TestCase) {
852                self.cursor().move_until_line_end();
853            }
854            #[rule]
855            fn insert_char(&mut self, tc: TestCase) {
856                let text = tc.draw(gs::text().min_size(1));
857                let c = text.chars().next().expect("min_size(1) yields a char");
858                self.cursor().insert_char(c);
859            }
860            #[rule]
861            fn insert(&mut self, tc: TestCase) {
862                let text = tc.draw(gs::text());
863                self.cursor().insert(&text);
864            }
865            #[rule]
866            fn delete_before(&mut self, tc: TestCase) {
867                let count = tc.draw(gs::integers::<usize>().min_value(1).max_value(100));
868                let mut cursor = self.cursor();
869                for _ in 0..count {
870                    cursor.delete_before();
871                }
872            }
873            #[rule]
874            fn delete_after(&mut self, tc: TestCase) {
875                let count = tc.draw(gs::integers::<usize>().min_value(1).max_value(100));
876                let mut cursor = self.cursor();
877                for _ in 0..count {
878                    cursor.delete_after();
879                }
880            }
881            #[invariant]
882            fn invariants(&self, _: TestCase) {
883                let _ = Cursor::new(&self.text, &self.state)
884                    .expect("Cursor remains valid after every operation");
885                let rope = self.text.rope();
886                assert!(
887                    rope.len() > 0 && rope.byte(rope.len() - 1) == b'\n',
888                    "Text keeps its trailing newline"
889                );
890            }
891        }
892        hegel::stateful::machine(StateMachine::default()).run(tc);
893    }
894}