promkit-widgets 0.7.0

Widgets for promkit
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
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
use std::collections::HashSet;

use promkit_core::grapheme::{StyledGrapheme, StyledGraphemes};

/// Edit mode.
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Clone, Default)]
pub enum Mode {
    #[default]
    /// Insert a char at the current position.
    Insert,
    /// Overwrite a char at the current position.
    Overwrite,
}

/// A text editor that supports basic editing operations
/// such as insert, delete, and overwrite.
#[derive(Clone)]
pub struct TextEditor {
    text: StyledGraphemes,
    position: usize,
    preferred_column: Option<usize>,
}

/// A cursor position in newline-delimited text.
///
/// `column` is measured in terminal display cells rather than grapheme indices.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct TextPosition {
    pub row: usize,
    pub column: usize,
}

impl Default for TextEditor {
    fn default() -> Self {
        Self {
            // Keep a trailing grapheme as the visible cursor.
            text: StyledGraphemes::from(" "),
            position: 0,
            preferred_column: None,
        }
    }
}

impl TextEditor {
    pub fn new<S: AsRef<str>>(s: S) -> Self {
        let mut buf = s.as_ref().to_owned();
        buf.push(' ');
        let text = StyledGraphemes::from(buf);
        let position = text.len() - 1;
        Self {
            text,
            position,
            preferred_column: None,
        }
    }

    /// Returns the current text including the cursor.
    pub fn text(&self) -> StyledGraphemes {
        self.text.clone()
    }

    /// Returns the text without the cursor.
    pub fn text_without_cursor(&self) -> StyledGraphemes {
        let mut ret = self.text();
        ret.pop_back();
        ret
    }

    /// Returns the current position of the cursor within the text.
    pub fn position(&self) -> usize {
        self.position
    }

    /// Returns the cursor position in newline-delimited text.
    ///
    /// The row is a logical row separated by an explicit newline. The column is
    /// the terminal display width before the cursor on that row.
    pub fn logical_position(&self) -> TextPosition {
        let ranges = self.line_ranges();
        let (row, (start, _)) = ranges
            .iter()
            .copied()
            .enumerate()
            .find(|(_, (start, end))| self.position >= *start && self.position <= *end)
            .unwrap_or_else(|| {
                let row = ranges.len().saturating_sub(1);
                (row, ranges[row])
            });

        TextPosition {
            row,
            column: self.display_width_between(start, self.position),
        }
    }

    /// Resolves a logical text position to an absolute grapheme cursor index.
    ///
    /// Columns past the end of a row resolve to that row's end. A column inside
    /// a wide grapheme resolves to the position before that grapheme.
    pub fn position_at(&self, position: TextPosition) -> Option<usize> {
        let (start, end) = self.line_ranges().get(position.row).copied()?;
        Some(self.position_for_column(start, end, position.column))
    }

    /// Masks all characters except the cursor with the specified mask character.
    pub fn masking(&self, mask: char) -> StyledGraphemes {
        let cursor = self.text.len() - 1;
        self.text()
            .chars()
            .into_iter()
            .enumerate()
            .map(|(i, c)| StyledGrapheme::from(if i == cursor || c == '\n' { c } else { mask }))
            .collect::<StyledGraphemes>()
    }

    /// Replaces the current text with new text and positions the cursor at the end.
    pub fn replace(&mut self, new: &str) {
        *self = Self::new(new);
    }

    /// Inserts a character at the current cursor position.
    pub fn insert(&mut self, ch: char) {
        self.preferred_column = None;
        let pos = self.position();
        self.text.insert(pos, StyledGrapheme::from(ch));
        self.forward();
    }

    /// Inserts a newline at the current cursor position.
    pub fn insert_newline(&mut self) {
        self.insert('\n');
    }

    pub fn insert_chars(&mut self, vch: &Vec<char>) {
        for ch in vch {
            self.insert(*ch);
        }
    }

    /// Overwrites the character at the current cursor position with the specified character.
    pub fn overwrite(&mut self, ch: char) {
        if self.position == self.text.len() - 1 {
            self.insert(ch)
        } else {
            self.preferred_column = None;
            let pos = self.position();
            self.text.replace_range(pos..pos + 1, ch.to_string());
            self.forward();
        }
    }

    pub fn overwrite_chars(&mut self, vch: &Vec<char>) {
        for ch in vch {
            self.overwrite(*ch);
        }
    }

    /// Erases the character before the cursor position.
    pub fn erase(&mut self) {
        if self.position > 0 {
            self.preferred_column = None;
            self.backward();
            let pos = self.position();
            self.text.drain(pos..pos + 1);
        }
    }

    /// Erases the grapheme at the cursor position.
    ///
    /// Erasing a newline joins its surrounding logical rows. The trailing
    /// cursor grapheme is never removed.
    pub fn erase_forward(&mut self) {
        if self.position < self.text.len() - 1 {
            self.preferred_column = None;
            self.text.drain(self.position..self.position + 1);
        }
    }

    /// Clears all text and resets the editor to its default state.
    pub fn erase_all(&mut self) {
        *self = Self::default();
    }

    /// Erases the text from the current cursor position to the specified position,
    /// considering whether pos is greater or smaller than the current position.
    fn erase_to_position(&mut self, pos: usize) {
        self.preferred_column = None;
        let current_pos = self.position();
        if pos > current_pos {
            self.text.drain(current_pos..pos);
        } else {
            self.text.drain(pos..current_pos);
            self.move_to(pos);
        }
    }

    /// Finds the nearest previous index of any character in `word_break_chars` from the cursor position.
    fn find_previous_nearest_index(&self, word_break_chars: &HashSet<char>) -> usize {
        let current_position = self.position();
        self.text()
            .chars()
            .iter()
            .enumerate()
            .filter(|&(i, _)| i < current_position.saturating_sub(1))
            .rev()
            .find(|&(_, c)| word_break_chars.contains(c))
            .map(|(i, _)| i + 1)
            .unwrap_or(0)
    }

    /// Erases the text from the current cursor position to the nearest previous character in `word_break_chars`.
    pub fn erase_to_previous_nearest(&mut self, word_break_chars: &HashSet<char>) {
        let pos = self.find_previous_nearest_index(word_break_chars);
        self.erase_to_position(pos);
    }

    /// Moves the cursor to the nearest previous character in `word_break_chars`.
    pub fn move_to_previous_nearest(&mut self, word_break_chars: &HashSet<char>) {
        let pos = self.find_previous_nearest_index(word_break_chars);
        self.move_to(pos);
    }

    /// Finds the nearest next index of any character in `word_break_chars` from the cursor position.
    fn find_next_nearest_index(&self, word_break_chars: &HashSet<char>) -> usize {
        let current_position = self.position();
        self.text()
            .chars()
            .iter()
            .enumerate()
            .filter(|&(i, _)| i > current_position)
            .find(|&(_, c)| word_break_chars.contains(c))
            .map(|(i, _)| {
                if i < self.text.len() - 1 {
                    i + 1
                } else {
                    self.text.len() - 1
                }
            })
            .unwrap_or(self.text.len() - 1)
    }

    /// Erases the text from the current cursor position to the nearest next character in `word_break_chars`.
    pub fn erase_to_next_nearest(&mut self, word_break_chars: &HashSet<char>) {
        let pos = self.find_next_nearest_index(word_break_chars);
        self.erase_to_position(pos);
    }

    /// Moves the cursor to the nearest next character in `word_break_chars`.
    pub fn move_to_next_nearest(&mut self, word_break_chars: &HashSet<char>) {
        let pos = self.find_next_nearest_index(word_break_chars);
        self.move_to(pos);
    }

    /// Moves the cursor to the beginning of the text.
    pub fn move_to_head(&mut self) {
        self.position = 0;
        self.preferred_column = None;
    }

    /// Moves the cursor to the end of the text.
    pub fn move_to_tail(&mut self) {
        self.position = self.text.len() - 1;
        self.preferred_column = None;
    }

    /// Moves the cursor to the beginning of its current logical row.
    pub fn move_to_line_head(&mut self) {
        let position = self.logical_position();
        if let Some((start, _)) = self.line_ranges().get(position.row) {
            self.position = *start;
            self.preferred_column = None;
        }
    }

    /// Moves the cursor to the end of its current logical row.
    pub fn move_to_line_tail(&mut self) {
        let position = self.logical_position();
        if let Some((_, end)) = self.line_ranges().get(position.row) {
            self.position = *end;
            self.preferred_column = None;
        }
    }

    /// Moves the cursor to the previous logical row.
    ///
    /// Repeated vertical movement preserves the original display column and
    /// clamps only while passing through shorter rows.
    pub fn move_up(&mut self) -> bool {
        self.move_vertical(-1)
    }

    /// Moves the cursor to the next logical row.
    ///
    /// Repeated vertical movement preserves the original display column and
    /// clamps only while passing through shorter rows.
    pub fn move_down(&mut self) -> bool {
        self.move_vertical(1)
    }

    /// Moves the cursor to a character by index.
    pub fn move_to(&mut self, position: usize) -> bool {
        if position < self.text.len() {
            self.position = position;
            self.preferred_column = None;
            true
        } else {
            false
        }
    }

    pub fn shift(&mut self, backward: usize, forward: usize) -> bool {
        let Some(position) = self
            .position
            .checked_sub(backward)
            .and_then(|position| position.checked_add(forward))
        else {
            return false;
        };

        self.move_to(position)
    }

    /// Moves the cursor one position backward, if possible.
    pub fn backward(&mut self) -> bool {
        self.shift(1, 0)
    }

    /// Moves the cursor one position forward, if possible.
    pub fn forward(&mut self) -> bool {
        self.shift(0, 1)
    }

    fn move_vertical(&mut self, row_delta: isize) -> bool {
        let ranges = self.line_ranges();
        let current = self.logical_position();
        let Some(target_row) = current.row.checked_add_signed(row_delta) else {
            return false;
        };
        let Some((start, end)) = ranges.get(target_row).copied() else {
            return false;
        };

        let column = self.preferred_column.unwrap_or(current.column);
        self.position = self.position_for_column(start, end, column);
        self.preferred_column = Some(column);
        true
    }

    fn line_ranges(&self) -> Vec<(usize, usize)> {
        let content_end = self.text.len().saturating_sub(1);
        let mut ranges = Vec::new();
        let mut start = 0;

        for (index, grapheme) in self.text.iter().take(content_end).enumerate() {
            if grapheme.character() == '\n' {
                ranges.push((start, index));
                start = index + 1;
            }
        }

        ranges.push((start, content_end));
        ranges
    }

    fn display_width_between(&self, start: usize, end: usize) -> usize {
        self.text
            .iter()
            .skip(start)
            .take(end.saturating_sub(start))
            .map(StyledGrapheme::width)
            .sum()
    }

    fn position_for_column(&self, start: usize, end: usize, column: usize) -> usize {
        let mut current_column = 0;

        for (offset, grapheme) in self
            .text
            .iter()
            .skip(start)
            .take(end.saturating_sub(start))
            .enumerate()
        {
            let next_column = current_column + grapheme.width();
            if column < next_column {
                return start + offset;
            }
            current_column = next_column;
        }

        end
    }
}

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

    mod text_editor {
        use super::*;

        fn new_with_position(s: String, p: usize) -> TextEditor {
            let text = StyledGraphemes::from(s);
            TextEditor {
                position: p.min(text.len().saturating_sub(1)),
                text,
                preferred_column: None,
            }
        }

        mod new {
            use super::*;

            #[test]
            fn starts_at_the_trailing_cursor() {
                let texteditor = TextEditor::new("abc");

                assert_eq!(texteditor.position(), 3);
            }
        }

        mod move_to {
            use super::*;

            #[test]
            fn preserves_the_position_when_the_target_is_out_of_bounds() {
                let mut texteditor = TextEditor::new("abc");

                assert!(texteditor.move_to(1));
                assert_eq!(texteditor.position(), 1);
                assert!(!texteditor.move_to(4));
                assert_eq!(texteditor.position(), 1);
            }
        }

        mod shift {
            use super::*;

            #[test]
            fn preserves_the_position_when_the_target_is_out_of_bounds() {
                let mut texteditor = TextEditor::new("abc");
                assert!(texteditor.move_to(1));

                assert!(texteditor.shift(0, 2));
                assert_eq!(texteditor.position(), 3);
                assert!(!texteditor.shift(0, 1));
                assert_eq!(texteditor.position(), 3);
                assert!(!texteditor.shift(4, 0));
                assert_eq!(texteditor.position(), 3);
            }
        }

        mod masking {
            use super::*;

            #[test]
            fn replaces_non_whitespace_characters_with_the_mask() {
                let txt = new_with_position(String::from("abcde "), 0);
                assert_eq!(StyledGraphemes::from("***** "), txt.masking('*'))
            }

            #[test]
            fn preserves_newlines_in_multiline_text() {
                let txt = TextEditor::new("ab\nc");

                assert_eq!(StyledGraphemes::from("**\n* "), txt.masking('*'));
            }
        }

        mod erase {
            use super::*;

            #[test]
            fn empty_editor_is_unchanged() {
                let txt = TextEditor::default();
                assert_eq!(StyledGraphemes::from(" "), txt.text());
                assert_eq!(0, txt.position());
            }

            #[test]
            fn removes_the_character_before_the_cursor() {
                let mut txt = new_with_position(
                    String::from("abc "),
                    1, // indicate `b`.
                );
                let new = new_with_position(
                    String::from("bc "),
                    0, // indicate `b`.
                );
                txt.erase();
                assert_eq!(new.text(), txt.text());
                assert_eq!(new.position(), txt.position());
            }

            #[test]
            fn removes_the_last_character_at_the_tail() {
                let mut txt = new_with_position(
                    String::from("abc "),
                    3, // indicate tail.
                );
                let new = new_with_position(
                    String::from("ab "),
                    2, // indicate tail.
                );
                txt.erase();
                assert_eq!(new.text(), txt.text());
                assert_eq!(new.position(), txt.position());
            }

            #[test]
            fn head_is_unchanged() {
                let txt = new_with_position(
                    String::from("abc "),
                    0, // indicate `a`.
                );
                assert_eq!(StyledGraphemes::from("abc "), txt.text());
                assert_eq!(0, txt.position());
            }
        }

        mod find_previous_nearest_index {
            use super::*;

            use std::collections::HashSet;

            #[test]
            fn finds_the_previous_word_boundary() {
                let mut txt = new_with_position(String::from("koko momo jojo "), 11); // indicate `o`.
                assert_eq!(10, txt.find_previous_nearest_index(&HashSet::from([' '])));
                txt.move_to(10);
                assert_eq!(5, txt.find_previous_nearest_index(&HashSet::from([' '])));
            }

            #[test]
            fn returns_the_head_when_no_boundary_exists() {
                let txt = new_with_position(String::from("koko momo jojo "), 7); // indicate `m`.
                assert_eq!(0, txt.find_previous_nearest_index(&HashSet::from(['z'])));
            }
        }

        mod find_next_nearest_index {
            use super::*;

            use std::collections::HashSet;

            #[test]
            fn finds_the_next_word_boundary() {
                let mut txt = new_with_position(String::from("koko momo jojo "), 7); // indicate `m`.
                assert_eq!(10, txt.find_next_nearest_index(&HashSet::from([' '])));
                txt.move_to(10);
                assert_eq!(14, txt.find_next_nearest_index(&HashSet::from([' '])));
            }

            #[test]
            fn returns_the_tail_when_no_boundary_exists() {
                let txt = new_with_position(String::from("koko momo jojo "), 7); // indicate `m`.
                assert_eq!(14, txt.find_next_nearest_index(&HashSet::from(['z'])));
            }
        }

        mod insert {
            use super::*;

            #[test]
            fn inserts_into_an_empty_editor() {
                let mut txt = TextEditor::default();
                let new = new_with_position(
                    String::from("d "),
                    1, // indicate tail.
                );
                txt.insert('d');
                assert_eq!(new.text(), txt.text());
                assert_eq!(new.position(), txt.position());
            }

            #[test]
            fn inserts_before_the_cursor() {
                let mut txt = new_with_position(
                    String::from("abc "),
                    1, // indicate `b`.
                );
                let new = new_with_position(
                    String::from("adbc "),
                    2, // indicate `b`.
                );
                txt.insert('d');
                assert_eq!(new.text(), txt.text());
                assert_eq!(new.position(), txt.position());
            }

            #[test]
            fn appends_at_the_tail() {
                let mut txt = new_with_position(
                    String::from("abc "),
                    3, // indicate tail.
                );
                let new = new_with_position(
                    String::from("abcd "),
                    4, // indicate tail.
                );
                txt.insert('d');
                assert_eq!(new.text(), txt.text());
                assert_eq!(new.position(), txt.position());
            }

            #[test]
            fn prepends_at_the_head() {
                let mut txt = new_with_position(
                    String::from("abc "),
                    0, // indicate `a`.
                );
                let new = new_with_position(
                    String::from("dabc "),
                    1, // indicate `a`.
                );
                txt.insert('d');
                assert_eq!(new.text(), txt.text());
                assert_eq!(new.position(), txt.position());
            }
        }

        mod logical_position {
            use super::*;

            #[test]
            fn uses_display_columns() {
                let mut txt = TextEditor::new("ab\n界c");

                assert_eq!(TextPosition { row: 1, column: 3 }, txt.logical_position());

                assert!(txt.move_to(3)); // Before `界`.
                assert_eq!(TextPosition { row: 1, column: 0 }, txt.logical_position());
            }

            #[test]
            fn handles_empty_lines_and_a_trailing_newline() {
                let mut txt = TextEditor::new("a\n\n");

                assert_eq!(TextPosition { row: 2, column: 0 }, txt.logical_position());
                assert!(txt.move_up());
                assert_eq!(TextPosition { row: 1, column: 0 }, txt.logical_position());
                assert!(txt.move_up());
                assert_eq!(TextPosition { row: 0, column: 0 }, txt.logical_position());
            }
        }

        mod insert_newline {
            use super::*;

            #[test]
            fn inserts_at_the_cursor() {
                let mut txt = TextEditor::new("abcd");
                assert!(txt.move_to(2));

                txt.insert_newline();

                assert_eq!("ab\ncd", txt.text_without_cursor().to_string());
                assert_eq!(3, txt.position());
                assert_eq!(TextPosition { row: 1, column: 0 }, txt.logical_position());
            }
        }

        mod move_down {
            use super::*;

            #[test]
            fn preserves_the_preferred_display_column() {
                let mut txt = TextEditor::new("abcdef\nxy\n123456");
                assert!(txt.move_to(6)); // End of the first line.

                assert!(txt.move_down());
                assert_eq!(9, txt.position()); // End of the shorter second line.
                assert_eq!(TextPosition { row: 1, column: 2 }, txt.logical_position());

                assert!(txt.move_down());
                assert_eq!(16, txt.position()); // Restore column 6 on the third line.
                assert_eq!(TextPosition { row: 2, column: 6 }, txt.logical_position());

                assert!(txt.move_up());
                assert_eq!(9, txt.position());
                assert!(txt.move_up());
                assert_eq!(6, txt.position());
            }

            #[test]
            fn uses_wide_character_display_widths() {
                let mut txt = TextEditor::new("界a\n123");
                assert!(txt.move_to(1)); // Display column 2 after `界`.

                assert!(txt.move_down());

                assert_eq!(5, txt.position());
                assert_eq!(TextPosition { row: 1, column: 2 }, txt.logical_position());
            }

            #[test]
            fn stops_at_the_document_tail() {
                let mut txt = TextEditor::new("ab\ncd");
                txt.move_to_tail();

                assert!(!txt.move_down());
            }
        }

        mod move_up {
            use super::*;

            #[test]
            fn stops_at_the_document_head() {
                let mut txt = TextEditor::new("ab\ncd");
                txt.move_to_head();

                assert!(!txt.move_up());
                assert_eq!(0, txt.position());

                assert!(txt.move_to(3));
                assert!(txt.move_up());
                assert_eq!(0, txt.position());
                assert!(!txt.move_up());
            }
        }

        mod move_to_line_head {
            use super::*;

            #[test]
            fn moves_to_the_current_line_head() {
                let mut txt = TextEditor::new("ab\ncd");
                assert!(txt.move_to(4)); // Before `d`.

                txt.move_to_line_head();
                assert_eq!(3, txt.position());
            }
        }

        mod move_to_line_tail {
            use super::*;

            #[test]
            fn moves_to_the_current_line_tail() {
                let mut txt = TextEditor::new("ab\ncd");
                assert!(txt.move_to(4)); // Before `d`.

                txt.move_to_line_tail();
                assert_eq!(5, txt.position());
            }
        }

        mod erase_forward {
            use super::*;

            #[test]
            fn erases_a_newline_and_joins_lines() {
                let mut txt = TextEditor::new("ab\ncd");
                assert!(txt.move_to(2)); // Before the newline.

                txt.erase_forward();

                assert_eq!("abcd", txt.text_without_cursor().to_string());
                assert_eq!(2, txt.position());
                assert_eq!(TextPosition { row: 0, column: 2 }, txt.logical_position());
            }
        }

        mod overwrite {
            use super::*;

            #[test]
            fn inserts_into_an_empty_editor() {
                let mut txt = TextEditor::default();
                let new = new_with_position(
                    String::from("d "),
                    1, // indicate tail.
                );
                txt.overwrite('d');
                assert_eq!(new.text(), txt.text());
                assert_eq!(new.position(), txt.position());
            }

            #[test]
            fn replaces_the_character_at_the_cursor() {
                let mut txt = new_with_position(
                    String::from("abc "),
                    1, // indicate `b`.
                );
                let new = new_with_position(
                    String::from("adc "),
                    2, // indicate `c`.
                );
                txt.overwrite('d');
                assert_eq!(new.text(), txt.text());
                assert_eq!(new.position(), txt.position());
            }

            #[test]
            fn appends_at_the_tail() {
                let mut txt = new_with_position(
                    String::from("abc "),
                    3, // indicate tail.
                );
                let new = new_with_position(
                    String::from("abcd "),
                    4, // indicate tail.
                );
                txt.overwrite('d');
                assert_eq!(new.text(), txt.text());
                assert_eq!(new.position(), txt.position());
            }

            #[test]
            fn replaces_the_first_character_at_the_head() {
                let mut txt = new_with_position(
                    String::from("abc "),
                    0, // indicate `a`.
                );
                let new = new_with_position(
                    String::from("dbc "),
                    1, // indicate `b`.
                );
                txt.overwrite('d');
                assert_eq!(new.text(), txt.text());
                assert_eq!(new.position(), txt.position());
            }
        }

        mod backward {
            use super::*;

            #[test]
            fn empty_editor_is_unchanged() {
                let mut txt = TextEditor::default();
                txt.backward();
                assert_eq!(StyledGraphemes::from(" "), txt.text());
                assert_eq!(0, txt.position());
            }

            #[test]
            fn moves_back_one_character() {
                let mut txt = new_with_position(
                    String::from("abc "),
                    1, // indicate `b`.
                );
                let new = new_with_position(
                    String::from("abc "),
                    0, // indicate `a`.
                );
                txt.backward();
                assert_eq!(new.text(), txt.text());
                assert_eq!(new.position(), txt.position());
            }

            #[test]
            fn moves_back_from_the_tail() {
                let mut txt = new_with_position(
                    String::from("abc "),
                    3, // indicate tail.
                );
                let new = new_with_position(
                    String::from("abc "),
                    2, // indicate `c`.
                );
                txt.backward();
                assert_eq!(new.text(), txt.text());
                assert_eq!(new.position(), txt.position());
            }

            #[test]
            fn head_is_unchanged() {
                let mut txt = new_with_position(
                    String::from("abc "),
                    0, // indicate `a`.
                );
                txt.backward();
                assert_eq!(StyledGraphemes::from("abc "), txt.text());
                assert_eq!(0, txt.position());
            }
        }

        mod forward {
            use super::*;

            #[test]
            fn empty_editor_is_unchanged() {
                let mut txt = TextEditor::default();
                txt.forward();
                assert_eq!(StyledGraphemes::from(" "), txt.text());
                assert_eq!(0, txt.position());
            }

            #[test]
            fn moves_forward_one_character() {
                let mut txt = new_with_position(
                    String::from("abc "),
                    1, // indicate `b`.
                );
                let new = new_with_position(
                    String::from("abc "),
                    2, // indicate `c`.
                );
                txt.forward();
                assert_eq!(new.text(), txt.text());
                assert_eq!(new.position(), txt.position());
            }

            #[test]
            fn tail_is_unchanged() {
                let mut txt = new_with_position(
                    String::from("abc "),
                    3, // indicate tail.
                );
                txt.forward();
                assert_eq!(StyledGraphemes::from("abc "), txt.text());
                assert_eq!(3, txt.position());
            }

            #[test]
            fn moves_forward_from_the_head() {
                let mut txt = new_with_position(
                    String::from("abc "),
                    0, // indicate `a`.
                );
                let new = new_with_position(
                    String::from("abc "),
                    1, // indicate `b`.
                );
                txt.forward();
                assert_eq!(new.text(), txt.text());
                assert_eq!(new.position(), txt.position());
            }
        }

        mod move_to_head {
            use super::*;

            #[test]
            fn empty_editor_is_unchanged() {
                let mut txt = TextEditor::default();
                txt.move_to_head();
                assert_eq!(StyledGraphemes::from(" "), txt.text());
                assert_eq!(0, txt.position());
            }

            #[test]
            fn moves_to_the_head() {
                let mut txt = new_with_position(
                    String::from("abc "),
                    1, // indicate `b`.
                );
                let new = new_with_position(
                    String::from("abc "),
                    0, // indicate `a`.
                );
                txt.move_to_head();
                assert_eq!(new.text(), txt.text());
                assert_eq!(new.position(), txt.position());
            }

            #[test]
            fn moves_from_the_tail_to_the_head() {
                let mut txt = new_with_position(
                    String::from("abc "),
                    3, // indicate tail.
                );
                let new = new_with_position(
                    String::from("abc "),
                    0, // indicate `a`.
                );
                txt.move_to_head();
                assert_eq!(new.text(), txt.text());
                assert_eq!(new.position(), txt.position());
            }

            #[test]
            fn head_is_unchanged() {
                let mut txt = new_with_position(
                    String::from("abc "),
                    0, // indicate `a`.
                );
                txt.move_to_head();
                assert_eq!(StyledGraphemes::from("abc "), txt.text());
                assert_eq!(0, txt.position());
            }
        }

        mod move_to_tail {
            use super::*;

            #[test]
            fn empty_editor_is_unchanged() {
                let mut txt = TextEditor::default();
                txt.move_to_tail();
                assert_eq!(StyledGraphemes::from(" "), txt.text());
                assert_eq!(0, txt.position());
            }

            #[test]
            fn moves_to_the_tail() {
                let mut txt = new_with_position(
                    String::from("abc "),
                    1, // indicate `b`.
                );
                let new = new_with_position(
                    String::from("abc "),
                    3, // indicate tail.
                );
                txt.move_to_tail();
                assert_eq!(new.text(), txt.text());
                assert_eq!(new.position(), txt.position());
            }

            #[test]
            fn tail_is_unchanged() {
                let mut txt = new_with_position(
                    String::from("abc "),
                    3, // indicate tail.
                );
                txt.move_to_tail();
                assert_eq!(StyledGraphemes::from("abc "), txt.text());
                assert_eq!(3, txt.position());
            }

            #[test]
            fn moves_from_the_head_to_the_tail() {
                let mut txt = new_with_position(
                    String::from("abc "),
                    0, // indicate `a`.
                );
                let new = new_with_position(
                    String::from("abc "),
                    3, // indicate tail.
                );
                txt.move_to_tail();
                assert_eq!(new.text(), txt.text());
                assert_eq!(new.position(), txt.position());
            }
        }
    }
}