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
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
use crate::grapheme::Grapheme;
use crate::{upos_type, Cursor, TextError, TextPosition, TextRange};
use std::borrow::Cow;
use std::ops::Range;

/// Backing store for the TextCore.
pub trait TextStore {
    /// Can store multi-line content?
    fn is_multi_line(&self) -> bool;

    /// Get content as string.
    fn string(&self) -> String;

    /// Set content from string.
    fn set_string(&mut self, t: &str);

    /// Grapheme position to byte position.
    /// This is the (start,end) position of the single grapheme after pos.
    ///
    /// * pos must be a valid position: row <= len_lines, col <= line_width of the row.
    fn byte_range_at(&self, pos: TextPosition) -> Result<Range<usize>, TextError>;

    /// Grapheme range to byte range.
    ///
    /// * range must be a valid range. row <= len_lines, col <= line_width of the row.
    fn byte_range(&self, range: TextRange) -> Result<Range<usize>, TextError>;

    /// Byte position to grapheme position.
    /// Returns the position that contains the given byte index.
    ///
    /// * byte must <= byte-len.
    fn byte_to_pos(&self, byte: usize) -> Result<TextPosition, TextError>;

    /// Byte range to grapheme range.
    ///
    /// * byte must <= byte-len.
    fn bytes_to_range(&self, bytes: Range<usize>) -> Result<TextRange, TextError>;

    /// A range of the text as Cow<str>.
    ///
    /// * range must be a valid range. row <= len_lines, col <= line_width of the row.
    /// * pos must be inside of range.
    fn str_slice(&self, range: TextRange) -> Result<Cow<'_, str>, TextError>;

    /// A range of the text as Cow<str>.
    ///
    /// * range must be valid
    fn str_slice_byte(&self, range: Range<usize>) -> Result<Cow<'_, str>, TextError>;

    /// Return a cursor over the graphemes of the range, start at the given position.
    ///
    /// * range must be a valid range. row <= len_lines, col <= line_width of the row.
    /// * pos must be inside of range.
    fn graphemes(
        &self,
        range: TextRange,
        pos: TextPosition,
    ) -> Result<impl Iterator<Item = Grapheme<'_>> + Cursor, TextError>;

    /// Line as str.
    ///
    /// * row must be <= len_lines
    fn line_at(&self, row: upos_type) -> Result<Cow<'_, str>, TextError>;

    /// Iterate over text-lines, starting at line-offset.
    ///
    /// * row must be <= len_lines
    fn lines_at(&self, row: upos_type) -> Result<impl Iterator<Item = Cow<'_, str>>, TextError>;

    /// Return a line as an iterator over the graphemes.
    /// This contains the '\n' at the end.
    ///
    /// * row must be <= len_lines
    fn line_graphemes(
        &self,
        row: upos_type,
    ) -> Result<impl Iterator<Item = Grapheme<'_>> + Cursor, TextError>;

    /// Line width of row as grapheme count.
    /// Excludes the terminating '\n'.
    ///
    /// * row must be <= len_lines
    fn line_width(&self, row: upos_type) -> Result<upos_type, TextError>;

    /// Number of lines.
    fn len_lines(&self) -> upos_type;

    /// Insert a char at the given position.
    ///
    /// * range must be a valid range. row <= len_lines, col <= line_width of the row.
    fn insert_char(
        &mut self,
        pos: TextPosition,
        c: char,
    ) -> Result<(TextRange, Range<usize>), TextError>;

    /// Insert a text str at the given position.
    ///
    /// * range must be a valid range. row <= len_lines, col <= line_width of the row.
    fn insert_str(
        &mut self,
        pos: TextPosition,
        t: &str,
    ) -> Result<(TextRange, Range<usize>), TextError>;

    /// Remove the given text range.
    ///
    /// * range must be a valid range. row <= len_lines, col <= line_width of the row.
    fn remove(
        &mut self,
        range: TextRange,
    ) -> Result<(String, (TextRange, Range<usize>)), TextError>;

    /// Insert a string at the given byte index.
    /// Call this only for undo.
    ///
    /// byte_pos must be <= len bytes.
    fn insert_b(&mut self, byte_pos: usize, t: &str) -> Result<(), TextError>;

    /// Remove the given byte-range.
    /// Call this only for undo.
    ///
    /// byte_pos must be <= len bytes.
    fn remove_b(&mut self, byte_range: Range<usize>) -> Result<(), TextError>;
}

pub(crate) mod text_rope {
    use crate::grapheme::{Grapheme, RopeGraphemes};
    use crate::text_store::{Cursor, TextStore};
    use crate::{upos_type, TextError, TextPosition, TextRange};
    use ropey::{Rope, RopeSlice};
    use std::borrow::Cow;
    use std::mem;
    use std::ops::Range;
    use unicode_segmentation::UnicodeSegmentation;

    /// Text store with a rope.
    #[derive(Debug, Clone, Default)]
    pub struct TextRope {
        text: Rope,
        // tmp buf
        buf: String,
    }

    /// Length as grapheme count, excluding line breaks.
    #[inline]
    fn rope_line_len(r: RopeSlice<'_>) -> upos_type {
        let it = RopeGraphemes::new(0, r);
        it.filter(|g| !g.is_line_break()).count() as upos_type
    }

    /// Length as grapheme count, excluding line breaks.
    #[inline]
    fn str_line_len(s: &str) -> upos_type {
        let it = s.graphemes(true);
        it.filter(|c| *c != "\n" && *c != "\r\n").count() as upos_type
    }

    impl TextRope {
        /// Returns the first char position for the grapheme position.
        #[inline]
        fn char_at(&self, pos: TextPosition) -> Result<usize, TextError> {
            let byte_range = self.byte_range_at(pos)?;
            Ok(self
                .text
                .try_byte_to_char(byte_range.start)
                .expect("valid_bytes"))
        }

        /// Iterator for the chars of a given line.
        #[inline]
        fn line_chars(&self, row: upos_type) -> Result<impl Iterator<Item = char> + '_, TextError> {
            let Some(line) = self.text.get_line(row as usize) else {
                return Err(TextError::LineIndexOutOfBounds(
                    row,
                    self.text.len_lines() as upos_type,
                ));
            };
            Ok(line.chars())
        }
    }

    impl TextRope {
        /// New empty.
        pub fn new() -> Self {
            Self::default()
        }

        /// New from string.
        pub fn new_text(t: &str) -> Self {
            Self {
                text: Rope::from_str(t),
                buf: Default::default(),
            }
        }

        /// New from rope.
        pub fn new_rope(r: Rope) -> Self {
            Self {
                text: r,
                buf: Default::default(),
            }
        }

        /// Borrow the rope
        pub fn rope(&self) -> &Rope {
            &self.text
        }

        /// A range of the text as RopeSlice.
        #[inline]
        pub fn rope_slice(&self, range: TextRange) -> Result<RopeSlice<'_>, TextError> {
            let s = self.char_at(range.start)?;
            let e = self.char_at(range.end)?;
            Ok(self.text.get_slice(s..e).expect("valid_range"))
        }
    }

    impl TextStore for TextRope {
        /// Can store multi-line content?
        ///
        /// If this returns false it is an error to call any function with
        /// a row other than `0`.
        fn is_multi_line(&self) -> bool {
            true
        }

        /// Content as string.
        fn string(&self) -> String {
            self.text.to_string()
        }

        /// Set content.
        fn set_string(&mut self, t: &str) {
            self.text = Rope::from_str(t);
        }

        /// Grapheme position to byte position.
        /// This is the (start,end) position of the single grapheme after pos.
        ///
        /// * pos must be a valid position: row <= len_lines, col <= line_width of the row.
        fn byte_range_at(&self, pos: TextPosition) -> Result<Range<usize>, TextError> {
            let it_line = self.line_graphemes(pos.y)?;

            let mut col = 0;
            let mut byte_end = it_line.text_offset();
            for grapheme in it_line {
                if col == pos.x {
                    return Ok(grapheme.text_bytes());
                }
                col += 1;
                byte_end = grapheme.text_bytes().end;
            }
            // one past the end is ok.
            if col == pos.x {
                return Ok(byte_end..byte_end);
            } else {
                return Err(TextError::ColumnIndexOutOfBounds(pos.x, col));
            }
        }

        /// Grapheme range to byte range.
        ///
        /// * range must be a valid range. row <= len_lines, col <= line_width of the row.
        fn byte_range(&self, range: TextRange) -> Result<Range<usize>, TextError> {
            if range.start.y == range.end.y {
                let it_line = self.line_graphemes(range.start.y)?;

                let mut range_start = None;
                let mut range_end = None;
                let mut col = 0;
                let mut byte_end = it_line.text_offset();
                for grapheme in it_line {
                    if col == range.start.x {
                        range_start = Some(grapheme.text_bytes().start);
                    }
                    if col == range.end.x {
                        range_end = Some(grapheme.text_bytes().end);
                    }
                    if range_start.is_some() && range_end.is_some() {
                        break;
                    }
                    col += 1;
                    byte_end = grapheme.text_bytes().end;
                }
                // one past the end is ok.
                if col == range.start.x {
                    range_start = Some(byte_end);
                }
                if col == range.end.x {
                    range_end = Some(byte_end);
                }

                let Some(range_start) = range_start else {
                    return Err(TextError::ColumnIndexOutOfBounds(range.start.x, col));
                };
                let Some(range_end) = range_end else {
                    return Err(TextError::ColumnIndexOutOfBounds(range.end.x, col));
                };

                Ok(range_start..range_end)
            } else {
                let range_start = self.byte_range_at(range.start)?;
                let range_end = self.byte_range_at(range.end)?;

                Ok(range_start.start..range_end.start)
            }
        }

        /// Byte position to grapheme position.
        /// Returns the position that contains the given byte index.
        ///
        /// * byte must <= byte-len.
        fn byte_to_pos(&self, byte_pos: usize) -> Result<TextPosition, TextError> {
            let Ok(row) = self.text.try_byte_to_line(byte_pos) else {
                return Err(TextError::ByteIndexOutOfBounds(
                    byte_pos,
                    self.text.len_bytes(),
                ));
            };
            let row = row as upos_type;

            let mut col = 0;
            let it_line = self.line_graphemes(row)?;
            for grapheme in it_line {
                if byte_pos < grapheme.text_bytes().end {
                    break;
                }
                col += 1;
            }

            Ok(TextPosition::new(col, row))
        }

        /// Byte range to grapheme range.
        ///
        /// * byte must <= byte-len.
        fn bytes_to_range(&self, bytes: Range<usize>) -> Result<TextRange, TextError> {
            let Ok(start_row) = self.text.try_byte_to_line(bytes.start) else {
                return Err(TextError::ByteIndexOutOfBounds(
                    bytes.start,
                    self.text.len_bytes(),
                ));
            };
            let start_row = start_row as upos_type;
            let Ok(end_row) = self.text.try_byte_to_line(bytes.end) else {
                return Err(TextError::ByteIndexOutOfBounds(
                    bytes.end,
                    self.text.len_bytes(),
                ));
            };
            let end_row = end_row as upos_type;

            if start_row == end_row {
                let mut col = 0;
                let mut start = None;
                let mut end = None;
                let it_line = self.line_graphemes(start_row)?;
                for grapheme in it_line {
                    if bytes.start < grapheme.text_bytes().end {
                        if start == None {
                            start = Some(col);
                        }
                    }
                    if bytes.end < grapheme.text_bytes().end {
                        if end == None {
                            end = Some(col);
                        }
                    }
                    if start.is_some() && end.is_some() {
                        break;
                    }
                    col += 1;
                }
                if bytes.start == self.text.len_bytes() {
                    start = Some(col);
                }
                if bytes.end == self.text.len_bytes() {
                    end = Some(col);
                }

                let Some(start) = start else {
                    return Err(TextError::ByteIndexOutOfBounds(
                        bytes.start,
                        self.text.len_bytes(),
                    ));
                };
                let Some(end) = end else {
                    return Err(TextError::ByteIndexOutOfBounds(
                        bytes.end,
                        self.text.len_bytes(),
                    ));
                };

                Ok(TextRange::new((start, start_row), (end, end_row)))
            } else {
                let start = self.byte_to_pos(bytes.start)?;
                let end = self.byte_to_pos(bytes.end)?;

                Ok(TextRange::new(start, end))
            }
        }

        /// A range of the text as Cow<str>.
        ///
        /// * range must be a valid range. row <= len_lines, col <= line_width of the row.
        /// * pos must be inside of range.
        fn str_slice(&self, range: TextRange) -> Result<Cow<'_, str>, TextError> {
            let start_char = self.char_at(range.start)?;
            let end_char = self.char_at(range.end)?;
            let v = self
                .text
                .get_slice(start_char..end_char)
                .expect("valid_slice");
            match v.as_str() {
                Some(v) => Ok(Cow::Borrowed(v)),
                None => Ok(Cow::Owned(v.to_string())),
            }
        }

        /// A range of the text as Cow<str>.
        ///
        /// The byte-range must be a valid range.
        fn str_slice_byte(&self, range: Range<usize>) -> Result<Cow<'_, str>, TextError> {
            let Some(v) = self.text.get_byte_slice(range.clone()) else {
                return Err(TextError::ByteRangeOutOfBounds(
                    Some(range.start),
                    Some(range.end),
                    self.text.len_bytes(),
                ));
            };
            match v.as_str() {
                Some(v) => Ok(Cow::Borrowed(v)),
                None => Ok(Cow::Owned(v.to_string())),
            }
        }

        /// Return a cursor over the graphemes of the range, start at the given position.
        ///
        /// * range must be a valid range. row <= len_lines, col <= line_width of the row.
        /// * pos must be inside of range.
        fn graphemes(
            &self,
            range: TextRange,
            pos: TextPosition,
        ) -> Result<impl Iterator<Item = Grapheme<'_>> + Cursor, TextError> {
            if !range.contains_pos(pos) && range.end != pos {
                return Err(TextError::TextPositionOutOfBounds(pos));
            }

            let range_bytes = self.byte_range(range)?;
            let pos_byte = self.byte_range_at(pos)?.start;

            let s = self
                .text
                .get_byte_slice(range_bytes.clone())
                .expect("valid_range");

            Ok(
                RopeGraphemes::new_offset(range_bytes.start, s, pos_byte - range_bytes.start)
                    .expect("valid_bytes"),
            )
        }

        /// Line as str.
        ///
        /// * row must be <= len_lines
        fn line_at(&self, row: upos_type) -> Result<Cow<'_, str>, TextError> {
            let len = self.text.len_lines() as upos_type;
            if row > len {
                Err(TextError::LineIndexOutOfBounds(row, len))
            } else if row == len {
                Ok(Cow::Borrowed(""))
            } else {
                let v = self.text.get_line(row as usize).expect("valid_row");
                match v.as_str() {
                    Some(v) => Ok(Cow::Borrowed(v)),
                    None => Ok(Cow::Owned(v.to_string())),
                }
            }
        }

        /// Iterate over text-lines, starting at line-offset.
        ///
        /// * row must be <= len_lines
        fn lines_at(
            &self,
            row: upos_type,
        ) -> Result<impl Iterator<Item = Cow<'_, str>>, TextError> {
            let len = self.text.len_lines() as upos_type;
            if row > len {
                Err(TextError::LineIndexOutOfBounds(row, len))
            } else {
                let it = self.text.get_lines_at(row as usize).expect("valid_row");
                Ok(it.map(|v| match v.as_str() {
                    Some(v) => Cow::Borrowed(v),
                    None => Cow::Owned(v.to_string()),
                }))
            }
        }

        /// Return a line as an iterator over the graphemes.
        /// This contains the '\n' at the end.
        ///
        /// * row must be <= len_lines
        #[inline]
        fn line_graphemes(
            &self,
            row: upos_type,
        ) -> Result<impl Iterator<Item = Grapheme<'_>> + Cursor, TextError> {
            let line_byte = self.text.try_line_to_byte(row as usize)?;
            // try_line_to_byte and get_line don't have the same boundaries.
            // the former accepts one past the end, the latter doesn't.
            // here we need the first behaviour.
            if let Some(line) = self.text.get_line(row as usize) {
                Ok(RopeGraphemes::new(line_byte, line))
            } else {
                Ok(RopeGraphemes::new(line_byte, RopeSlice::from("")))
            }
        }

        /// Line width as grapheme count.
        /// Excludes the terminating '\n'.
        ///
        /// * row must be <= len_lines
        #[inline]
        fn line_width(&self, row: upos_type) -> Result<upos_type, TextError> {
            let len = self.text.len_lines() as upos_type;
            if row > len {
                return Err(TextError::LineIndexOutOfBounds(row, len));
            } else if row == len {
                Ok(0)
            } else {
                let v = self.text.get_line(row as usize).expect("valid_row");
                Ok(rope_line_len(v))
            }
        }

        fn len_lines(&self) -> upos_type {
            self.text.len_lines() as upos_type
        }

        /// Insert a char at the given position.
        ///
        /// * range must be a valid range. row <= len_lines, col <= line_width of the row.
        fn insert_char(
            &mut self,
            pos: TextPosition,
            ch: char,
        ) -> Result<(TextRange, Range<usize>), TextError> {
            let pos_byte = self.byte_range_at(pos)?;
            let pos_char = self
                .text
                .try_byte_to_char(pos_byte.start)
                .expect("valid_bytes");

            let mut it_gr = RopeGraphemes::new_offset(0, self.text.slice(..), pos_byte.start)
                .expect("valid_bytes");

            let prev = it_gr.prev();
            it_gr.next();
            let next = it_gr.next();

            let insert_range = if ch == '\n' {
                if let Some(prev) = prev {
                    if prev == "\r" {
                        TextRange::new(pos, pos)
                    } else {
                        TextRange::new(pos, (0, pos.y + 1))
                    }
                } else {
                    TextRange::new(pos, (0, pos.y + 1))
                }
            } else if ch == '\r' {
                if let Some(next) = next {
                    if next == "\n" {
                        TextRange::new(pos, pos)
                    } else {
                        TextRange::new(pos, (0, pos.y + 1))
                    }
                } else {
                    TextRange::new(pos, (0, pos.y + 1))
                }
            } else {
                let mut len = 0;
                self.buf.clear();
                if let Some(prev) = prev {
                    len += 1;
                    self.buf.push_str(prev.grapheme());
                }
                len += 1;
                self.buf.push(ch);
                if let Some(next) = next {
                    len += 1;
                    self.buf.push_str(next.grapheme());
                }

                let n = len - self.buf.graphemes(true).count();
                if n == 0 {
                    TextRange::new(pos, (pos.x + 1, pos.y))
                } else if n == 1 {
                    // combined some
                    TextRange::new(pos, pos)
                } else if n == 2 {
                    // combined some
                    TextRange::new(pos, pos)
                } else {
                    unreachable!("insert_char {:?}", self.buf);
                }
            };

            self.text
                .try_insert_char(pos_char, ch)
                .expect("valid_chars");

            Ok((insert_range, pos_byte.start..pos_byte.start + ch.len_utf8()))
        }

        /// Insert a text str at the given position.
        ///
        /// * range must be a valid range. row <= len_lines, col <= line_width of the row.
        fn insert_str(
            &mut self,
            pos: TextPosition,
            txt: &str,
        ) -> Result<(TextRange, Range<usize>), TextError> {
            let pos_byte = self.byte_range_at(pos)?;
            let pos_char = self
                .text
                .try_byte_to_char(pos_byte.start)
                .expect("valid_bytes");

            let mut line_count = 0;
            let mut last_linebreak_idx = 0;
            for (p, c) in txt.char_indices() {
                if c == '\n' {
                    line_count += 1;
                    last_linebreak_idx = p + 1;
                }
            }

            let insert_range = if line_count > 0 {
                let mut buf = mem::take(&mut self.buf);

                // Find the length of line after the insert position.
                let split = self.char_at(pos).expect("valid_pos");
                let line = self.line_chars(pos.y).expect("valid_pos");
                buf.clear();
                for c in line.skip(split) {
                    buf.push(c);
                }
                let old_len = str_line_len(&buf);
                buf.clear();

                // compose the new line and find its length.
                buf.push_str(&txt[last_linebreak_idx..]);
                let line = self.line_chars(pos.y).expect("valid_pos");
                for c in line.skip(split) {
                    buf.push(c);
                }
                let new_len = str_line_len(&buf);
                buf.clear();
                self.buf = buf;

                self.text.try_insert(pos_char, txt).expect("valid_pos");

                TextRange::new(pos, (new_len - old_len, pos.y + line_count))
            } else {
                // no way to know if the insert text combines with a surrounding char.
                // the difference of the graphem len seems safe though.
                let old_len = self.line_width(pos.y).expect("valid_line");

                self.text.try_insert(pos_char, txt).expect("valid_pos");

                let new_len = self.line_width(pos.y).expect("valid_line");

                TextRange::new(pos, (pos.x + new_len - old_len, pos.y))
            };

            Ok((insert_range, pos_byte.start..pos_byte.start + txt.len()))
        }

        /// Remove the given text range.
        ///
        /// * range must be a valid range. row <= len_lines, col <= line_width of the row.
        fn remove(
            &mut self,
            range: TextRange,
        ) -> Result<(String, (TextRange, Range<usize>)), TextError> {
            let start_byte_pos = self.byte_range_at(range.start)?;
            let end_byte_pos = self.byte_range_at(range.end)?;

            let start_pos = self
                .text
                .try_byte_to_char(start_byte_pos.start)
                .expect("valid_bytes");
            let end_pos = self
                .text
                .try_byte_to_char(end_byte_pos.start)
                .expect("valid_bytes");

            let old_text = self
                .text
                .get_slice(start_pos..end_pos)
                .expect("valid_bytes");
            let old_text = old_text.to_string();

            self.text.try_remove(start_pos..end_pos).expect("valid_pos");

            Ok((old_text, (range, start_byte_pos.start..end_byte_pos.start)))
        }

        /// Insert a string at the given byte index.
        /// Call this only for undo.
        ///
        /// byte_pos must be <= len bytes.
        fn insert_b(&mut self, byte_pos: usize, t: &str) -> Result<(), TextError> {
            let pos_char = self.text.try_byte_to_char(byte_pos)?;
            self.text.try_insert(pos_char, t).expect("valid_pos");
            Ok(())
        }

        /// Remove the given byte-range.
        /// Call this only for undo.
        ///
        /// byte_pos must be <= len bytes.
        fn remove_b(&mut self, byte_range: Range<usize>) -> Result<(), TextError> {
            let start_char = self.text.try_byte_to_char(byte_range.start)?;
            let end_char = self.text.try_byte_to_char(byte_range.end)?;
            self.text
                .try_remove(start_char..end_char)
                .expect("valid_range");
            Ok(())
        }
    }

    impl From<ropey::Error> for TextError {
        fn from(err: ropey::Error) -> Self {
            use ropey::Error;
            match err {
                Error::ByteIndexOutOfBounds(i, l) => TextError::ByteIndexOutOfBounds(i, l),
                Error::CharIndexOutOfBounds(i, l) => TextError::CharIndexOutOfBounds(i, l),
                Error::LineIndexOutOfBounds(i, l) => {
                    TextError::LineIndexOutOfBounds(i as upos_type, l as upos_type)
                }
                Error::Utf16IndexOutOfBounds(_, _) => {
                    unreachable!("{:?}", err)
                }
                Error::ByteIndexNotCharBoundary(i) => TextError::ByteIndexNotCharBoundary(i),
                Error::ByteRangeNotCharBoundary(s, e) => TextError::ByteRangeNotCharBoundary(s, e),
                Error::ByteRangeInvalid(s, e) => TextError::ByteRangeInvalid(s, e),
                Error::CharRangeInvalid(s, e) => TextError::CharRangeInvalid(s, e),
                Error::ByteRangeOutOfBounds(s, e, l) => TextError::ByteRangeOutOfBounds(s, e, l),
                Error::CharRangeOutOfBounds(s, e, l) => TextError::CharRangeOutOfBounds(s, e, l),
                _ => {
                    unreachable!("{:?}", err)
                }
            }
        }
    }
}

pub(crate) mod text_string {
    use crate::grapheme::{Grapheme, StrGraphemes};
    use crate::text_store::{Cursor, TextStore};
    use crate::{upos_type, TextError, TextPosition, TextRange};
    use std::borrow::Cow;
    use std::iter::once;
    use std::mem;
    use std::ops::Range;
    use unicode_segmentation::UnicodeSegmentation;

    /// Single line text-store.
    #[derive(Debug, Default, Clone)]
    pub struct TextString {
        // text
        text: String,
        // len as grapheme count
        len: upos_type,
        // tmp buffer
        buf: String,
    }

    /// Length as grapheme count, excluding line breaks.
    #[inline]
    fn str_len(s: &str) -> upos_type {
        s.graphemes(true).count() as upos_type
    }

    impl TextString {
        /// New empty.
        pub fn new() -> Self {
            Self {
                text: Default::default(),
                len: 0,
                buf: Default::default(),
            }
        }

        /// New from string.
        pub fn new_text(t: &str) -> Self {
            Self {
                text: t.into(),
                len: str_len(t),
                buf: Default::default(),
            }
        }

        /// New from string.
        pub fn new_string(t: String) -> Self {
            let len = str_len(&t);
            Self {
                text: t,
                len,
                buf: Default::default(),
            }
        }

        /// str
        pub fn as_str(&self) -> &str {
            self.text.as_str()
        }
    }

    impl TextStore for TextString {
        /// Can store multi-line content?
        ///
        /// todo: allow col=0, row=1
        fn is_multi_line(&self) -> bool {
            false
        }

        /// Get content as string.
        fn string(&self) -> String {
            self.text.to_string()
        }

        /// Set content as string.
        fn set_string(&mut self, t: &str) {
            self.text = t.to_string();
            self.len = str_len(&self.text);
        }

        /// Grapheme position to byte position.
        /// This is the (start,end) position of the single grapheme after pos.
        ///
        /// * pos must be a valid position: row <= len_lines, col <= line_width of the row.
        fn byte_range_at(&self, pos: TextPosition) -> Result<Range<usize>, TextError> {
            if pos.y != 0 && pos != TextPosition::new(0, 1) {
                return Err(TextError::LineIndexOutOfBounds(pos.y, 1));
            };

            if pos == TextPosition::new(0, 1) {
                let len = self.text.len();
                return Ok(len..len);
            }

            let mut byte_range = None;
            for (cidx, (idx, c)) in self
                .text
                .grapheme_indices(true)
                .chain(once((self.text.len(), "")))
                .enumerate()
            {
                if cidx == pos.x as usize {
                    byte_range = Some(idx..idx + c.len());
                    break;
                }
            }

            if let Some(byte_range) = byte_range {
                Ok(byte_range)
            } else {
                Err(TextError::ColumnIndexOutOfBounds(
                    pos.x,
                    str_len(&self.text),
                ))
            }
        }

        /// Grapheme range to byte range.
        ///
        /// * range must be a valid range. row <= len_lines, col <= line_width of the row.
        fn byte_range(&self, range: TextRange) -> Result<Range<usize>, TextError> {
            if range.start.y != 0 && range.start != TextPosition::new(0, 1) {
                return Err(TextError::LineIndexOutOfBounds(range.start.y, 1));
            };
            if range.end.y != 0 && range.end != TextPosition::new(0, 1) {
                return Err(TextError::LineIndexOutOfBounds(range.end.y, 1));
            };

            let mut byte_start = None;
            let mut byte_end = None;

            if range.start == TextPosition::new(0, 1) {
                byte_start = Some(self.text.len());
            }
            if range.end == TextPosition::new(0, 1) {
                byte_end = Some(self.text.len());
            }

            if byte_start.is_none() || byte_end.is_none() {
                for (cidx, (idx, _)) in self
                    .text
                    .grapheme_indices(true)
                    .chain(once((self.text.len(), "")))
                    .enumerate()
                {
                    if TextPosition::new(cidx as upos_type, 0) == range.start {
                        byte_start = Some(idx);
                    }
                    if TextPosition::new(cidx as upos_type, 0) == range.end {
                        byte_end = Some(idx);
                    }
                    if byte_start.is_some() && byte_end.is_some() {
                        break;
                    }
                }
            }

            let Some(byte_start) = byte_start else {
                return Err(TextError::ColumnIndexOutOfBounds(
                    range.start.x,
                    str_len(&self.text),
                ));
            };
            let Some(byte_end) = byte_end else {
                return Err(TextError::ColumnIndexOutOfBounds(
                    range.end.x,
                    str_len(&self.text),
                ));
            };

            Ok(byte_start..byte_end)
        }

        /// Byte position to grapheme position.
        /// Returns the position that contains the given byte index.
        ///
        /// * byte must <= byte-len.
        fn byte_to_pos(&self, byte_pos: usize) -> Result<TextPosition, TextError> {
            let mut pos = None;

            for (cidx, (c_start, c)) in self
                .text
                .grapheme_indices(true)
                .chain(once((self.text.len(), " ")))
                .enumerate()
            {
                if byte_pos < c_start + c.len() {
                    pos = Some(cidx);
                    break;
                }
            }

            if let Some(pos) = pos {
                Ok(TextPosition::new(pos as upos_type, 0))
            } else {
                Err(TextError::ByteIndexOutOfBounds(byte_pos, self.text.len()))
            }
        }

        /// Byte range to grapheme range.
        ///
        /// * byte must <= byte-len.
        fn bytes_to_range(&self, bytes: Range<usize>) -> Result<TextRange, TextError> {
            let mut start = None;
            let mut end = None;
            for (cidx, (c_start, c)) in self
                .text
                .grapheme_indices(true)
                .chain(once((self.text.len(), " ")))
                .enumerate()
            {
                if bytes.start < c_start + c.len() {
                    if start.is_none() {
                        start = Some(cidx as upos_type);
                    }
                }
                if bytes.end < c_start + c.len() {
                    if end.is_none() {
                        end = Some(cidx as upos_type);
                    }
                }
                if start.is_some() && end.is_some() {
                    break;
                }
            }

            let Some(start) = start else {
                return Err(TextError::ByteIndexOutOfBounds(
                    bytes.start,
                    self.text.len(),
                ));
            };
            let Some(end) = end else {
                return Err(TextError::ByteIndexOutOfBounds(bytes.end, self.text.len()));
            };

            Ok(TextRange::new((start, 0), (end, 0)))
        }

        /// A range of the text as Cow<str>.
        ///
        /// * range must be a valid range. row <= len_lines, col <= line_width of the row.
        /// * pos must be inside of range.
        fn str_slice(&self, range: TextRange) -> Result<Cow<'_, str>, TextError> {
            let range = self.byte_range(range)?;
            Ok(Cow::Borrowed(&self.text[range.start..range.end]))
        }

        /// A range of the text as Cow<str>.
        ///
        /// * range must be valid
        fn str_slice_byte(&self, range: Range<usize>) -> Result<Cow<'_, str>, TextError> {
            Ok(Cow::Borrowed(&self.text[range.start..range.end]))
        }

        /// Return a cursor over the graphemes of the range, start at the given position.
        ///
        /// * range must be a valid range. row <= len_lines, col <= line_width of the row.
        /// * pos must be inside of range.
        fn graphemes(
            &self,
            range: TextRange,
            pos: TextPosition,
        ) -> Result<impl Iterator<Item = Grapheme<'_>> + Cursor, TextError> {
            let range_byte = self.byte_range(range)?;
            let pos_byte = self.byte_range_at(pos)?;
            Ok(StrGraphemes::new_offset(
                range_byte.start,
                &self.text[range_byte.clone()],
                pos_byte.start - range_byte.start,
            ))
        }

        /// Line as str.
        ///
        /// * row must be <= len_lines
        fn line_at(&self, row: upos_type) -> Result<Cow<'_, str>, TextError> {
            if row == 0 {
                Ok(Cow::Borrowed(&self.text))
            } else if row == 1 {
                Ok(Cow::Borrowed(""))
            } else {
                Err(TextError::LineIndexOutOfBounds(row, 1))
            }
        }

        /// Iterate over text-lines, starting at line-offset.
        ///
        /// * row must be <= len_lines
        fn lines_at(
            &self,
            row: upos_type,
        ) -> Result<impl Iterator<Item = Cow<'_, str>>, TextError> {
            if row == 0 {
                Ok(once(Cow::Borrowed(self.text.as_str())))
            } else if row == 1 {
                Ok(once(Cow::Borrowed("")))
            } else {
                Err(TextError::LineIndexOutOfBounds(row, 1))
            }
        }

        /// Return a line as an iterator over the graphemes.
        /// This contains the '\n' at the end.
        ///
        /// * row must be <= len_lines
        fn line_graphemes(
            &self,
            row: upos_type,
        ) -> Result<impl Iterator<Item = Grapheme<'_>> + Cursor, TextError> {
            if row == 0 {
                Ok(StrGraphemes::new(0, &self.text))
            } else if row == 1 {
                Ok(StrGraphemes::new(self.text.len(), ""))
            } else {
                Err(TextError::LineIndexOutOfBounds(row, 1))
            }
        }

        /// Line width of row as grapheme count.
        /// Excludes the terminating '\n'.
        ///
        /// * row must be <= len_lines
        fn line_width(&self, row: upos_type) -> Result<upos_type, TextError> {
            if row == 0 {
                Ok(self.len)
            } else if row == 1 {
                Ok(0)
            } else {
                Err(TextError::LineIndexOutOfBounds(row, 1))
            }
        }

        /// Number of lines.
        fn len_lines(&self) -> upos_type {
            1
        }

        /// Insert a char at the given position.
        ///
        /// * range must be a valid range. row <= len_lines, col <= line_width of the row.
        fn insert_char(
            &mut self,
            pos: TextPosition,
            c: char,
        ) -> Result<(TextRange, Range<usize>), TextError> {
            if pos.y != 0 && pos != TextPosition::new(0, 1) {
                return Err(TextError::TextPositionOutOfBounds(pos));
            }

            let byte_pos = self.byte_range_at(pos)?;
            let (before, after) = self.text.split_at(byte_pos.start);

            let old_len = self.len;
            self.buf.clear();
            self.buf.push_str(before);
            self.buf.push(c);
            self.buf.push_str(after);

            let before_bytes = before.len();
            let new_len = str_len(&self.buf);

            mem::swap(&mut self.text, &mut self.buf);
            self.len = new_len;

            Ok((
                TextRange::new((pos.x, 0), (pos.x + (new_len - old_len), 0)),
                before_bytes..before_bytes + c.len_utf8(),
            ))
        }

        /// Insert a str at position.
        fn insert_str(
            &mut self,
            pos: TextPosition,
            t: &str,
        ) -> Result<(TextRange, Range<usize>), TextError> {
            if pos.y != 0 && pos != TextPosition::new(0, 1) {
                return Err(TextError::TextPositionOutOfBounds(pos));
            }

            let byte_pos = self.byte_range_at(pos)?;
            let (before, after) = self.text.split_at(byte_pos.start);

            let old_len = self.len;
            self.buf.clear();
            self.buf.push_str(before);
            self.buf.push_str(t);
            self.buf.push_str(after);

            let before_bytes = before.len();
            let new_len = str_len(&self.buf);

            mem::swap(&mut self.text, &mut self.buf);
            self.len = new_len;

            Ok((
                TextRange::new((pos.x, 0), (pos.x + (new_len - old_len), 0)),
                before_bytes..before_bytes + t.len(),
            ))
        }

        /// Remove a range.
        fn remove(
            &mut self,
            range: TextRange,
        ) -> Result<(String, (TextRange, Range<usize>)), TextError> {
            if range.start.y != 0 && range.start != TextPosition::new(0, 1) {
                return Err(TextError::TextRangeOutOfBounds(range));
            }
            if range.end.y != 0 && range.end != TextPosition::new(0, 1) {
                return Err(TextError::TextRangeOutOfBounds(range));
            }

            let bytes = self.byte_range(range)?;

            let (before, remove, after) = (
                &self.text[..bytes.start],
                &self.text[bytes.start..bytes.end],
                &self.text[bytes.end..],
            );

            self.buf.clear();
            self.buf.push_str(before);
            self.buf.push_str(after);

            let remove_str = remove.to_string();
            let before_bytes = before.len();
            let remove_bytes = remove.len();
            let new_len = str_len(&self.buf);

            mem::swap(&mut self.text, &mut self.buf);
            self.len = new_len;

            Ok((
                remove_str,
                (range, before_bytes..before_bytes + remove_bytes),
            ))
        }

        /// Insert a string at the given byte index.
        fn insert_b(&mut self, byte_pos: usize, t: &str) -> Result<(), TextError> {
            let Some((before, after)) = self.text.split_at_checked(byte_pos) else {
                return Err(TextError::ByteIndexNotCharBoundary(byte_pos));
            };

            self.buf.clear();
            self.buf.push_str(before);
            self.buf.push_str(t);
            self.buf.push_str(after);
            let new_len = str_len(&self.buf);

            mem::swap(&mut self.text, &mut self.buf);
            self.len = new_len;

            Ok(())
        }

        /// Remove the given byte-range.
        fn remove_b(&mut self, byte_range: Range<usize>) -> Result<(), TextError> {
            let Some((before, after)) = self.text.split_at_checked(byte_range.start) else {
                return Err(TextError::ByteIndexNotCharBoundary(byte_range.start));
            };
            let Some((_remove, after)) = after.split_at_checked(byte_range.end - byte_range.start)
            else {
                return Err(TextError::ByteIndexNotCharBoundary(byte_range.end));
            };

            self.buf.clear();
            self.buf.push_str(before);
            self.buf.push_str(after);
            let new_len = str_len(&self.buf);

            mem::swap(&mut self.text, &mut self.buf);
            self.len = new_len;

            Ok(())
        }
    }
}