lb-rs 26.11.25

The rust library for interacting with your lockbook.
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
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
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
use super::offset_types::{Byte, Grapheme, Graphemes, RangeExt};
use super::operation_types::{InverseOperation, Operation, Replace};
use super::unicode_segs::UnicodeSegs;
use super::{diff, unicode_segs};
use std::ops::Index;
use std::time::Duration;
use unicode_segmentation::UnicodeSegmentation as _;

/// Long-lived state of the editor's text buffer. Factored into sub-structs for borrow-checking.
/// # Operation algebra
/// Operations are created based on a version of the buffer. This version is called the operation's base and is
/// identified with a sequence number. When the base of an operation is equal to the buffer's current sequence number,
/// the operation can be applied and increments the buffer's sequence number.
///
/// When multiple operations are created based on the same version of the buffer, such as when a user types a few
/// keystrokes in one frame or issues a command like indenting multiple list items, the operations all have the same
/// base. Once the first operation is applied and the buffer's sequence number is incremented, the base of the
/// remaining operations must be incremented by using the first operation to transform them before they can be applied.
/// This corresponds to the reality that the buffer state has changed since the operation was created and the operation
/// must be re-interpreted. For example, if text is typed at the beginning then end of a buffer in one frame, the
/// position of the text typed at the end of the buffer is greater when it is applied than it was when it was typed.
///
/// External changes are merged by transforming the diff from the last external text to the new one past the local
/// replacements applied since, which win where they conflict. The result is queued as one external frame, based on the
/// current version like any local frame, and the local replacements are rebased onto the new external text.
///
/// # Undo
/// Undo reverts local changes only. External frames are never undone, and undo stops at the last one: local changes
/// from before it stay.
///
/// Operations are not invertible i.e. you cannot construct an inverse operation that will perfectly cancel out the
/// effect of another operation regardless of the time of interpretation. For example, with a text replacement, you can
/// construct an inverse text replacement that replaces the new range with the original text, but when operations are
/// undone from the middle of the chain, it may affect the original text. The operation will be re-interpreted based on
/// a new state of the buffer at its time of application. The replaced text has no fixed value by design.
///
/// However, it is possible to undo the specific application of an operation in the context of the state of the buffer
/// when it was applied. We store information necessary to undo applied operations alongside the operations themselves
/// i.e. the text replaced in the application. When the operation is transformed for any reason, this undo information
/// is invalidated.
#[derive(Default)]
pub struct Buffer {
    /// Current contents of the buffer (what should be displayed in the editor). Todo: hide behind a read-only accessor
    pub current: Snapshot,

    /// Snapshot of the buffer at the earliest undoable state. Operations are compacted into this as they overflow the
    /// undo limit.
    base: Snapshot,

    /// Operations received by the buffer. Used for undo/redo and for merging external changes.
    ops: Ops,

    /// State for tracking out-of-editor changes
    external: External,
}

#[derive(Debug, Default)]
pub struct Snapshot {
    pub text: String,
    pub segs: UnicodeSegs,
    pub selection: (Grapheme, Grapheme),
    pub seq: usize,
}

impl Snapshot {
    fn apply_select(&mut self, range: (Grapheme, Grapheme)) -> Response {
        self.selection = range;
        Response { selection_user_moved: true, ..Response::default() }
    }

    fn apply_replace(&mut self, replace: &Replace) -> (Response, Graphemes) {
        let Replace { range, text } = replace;
        let byte_range = self.segs.range_to_byte(*range);

        // Capture pre-apply segs so `Graphemes::measure_replace` can compute
        // the buffer delta. It's the only construction path for an
        // OT-correct grapheme count — bypassing it (e.g.
        // `text.graphemes(true).count()`) would produce a `usize`, not a
        // `Graphemes`, so any caller of this function wouldn't compile.
        let old_segs = self.segs.clone();

        self.text
            .replace_range(byte_range.start().0..byte_range.end().0, text);
        self.segs = unicode_segs::calc(&self.text);

        let actual_len = Graphemes::measure_replace(&old_segs, &self.segs, *range);

        adjust_subsequent_range(*range, actual_len, false, &mut self.selection);

        (Response { text_updated: true, ..Default::default() }, actual_len)
    }

    /// Captures the inverse-relevant state from the buffer *before* an op is
    /// applied. Combined with the text after apply by
    /// `PartialInverse::finalize` to produce the full inverse.
    fn invert_pre(&self, op: &Operation) -> PartialInverse {
        let mut partial = PartialInverse { select: self.selection, replace: None };
        if let Operation::Replace(Replace { range, text }) = op {
            let byte_range = self.segs.range_to_byte(*range);
            let replaced_text = self[byte_range].into();
            partial.replace = Some((byte_range.start(), text.len(), replaced_text));
        }
        partial
    }
}

struct PartialInverse {
    select: (Grapheme, Grapheme),
    /// (start byte, inserted bytes, replaced_text) of the replacement.
    replace: Option<(Byte, usize, String)>,
}

impl PartialInverse {
    /// The inverse against `after`, the text once the op applied. It spans
    /// whole graphemes of `after`: text that fused into a neighbor, like a
    /// combining mark after its letter, comes back out with the neighbor.
    fn finalize(self, after: &Snapshot) -> InverseOperation {
        InverseOperation {
            select: self.select,
            replace: self.replace.map(|(start, inserted, replaced_text)| {
                let end = Byte(start.0 + inserted);
                let range =
                    (after.segs.byte_to_char_floor(start), after.segs.byte_to_char_ceil(end));
                let (lo, hi) = after.segs.range_to_byte(range);
                let text =
                    [&after.text[lo.0..start.0], &replaced_text, &after.text[end.0..hi.0]].concat();
                Replace { range, text }
            }),
        }
    }
}

#[derive(Default)]
struct Ops {
    /// Operations that have been received by the buffer
    all: Vec<Operation>,
    meta: Vec<OpMeta>,

    /// Sequence number of the first unapplied operation. Operations starting with this one are queued for processing.
    processed_seq: usize,

    /// Operations that have been applied to the buffer and already transformed, in order of application. Each of these
    /// operations is based on the previous operation in this list, with the first based on the history base. Derived
    /// from other data and invalidated by some undo/redo flows.
    transformed: Vec<Operation>,

    /// Operations representing the inverse of the operations in `transformed_ops`, in order of application. Useful for
    /// undoing operations. The data model differs because an operation that replaces text containing the cursor needs
    /// two operations to revert the text and cursor. Derived from other data and invalidated by some undo/redo flows.
    transformed_inverted: Vec<InverseOperation>,

    /// Actual graphemes contributed by each `transformed` op once spliced
    /// into the buffer. The `Graphemes` newtype enforces this distinction
    /// at the type level — populating this field requires a value from
    /// `Graphemes::measure_replace`, not `text.graphemes(true).count()`,
    /// which would account for in-isolation counts only and miss seam fusion
    /// (Devanagari spacing marks, ZWJ sequences). Always 0 for
    /// `Operation::Select`.
    transformed_actual_len: Vec<Graphemes>,
}

impl Ops {
    fn len(&self) -> usize {
        self.all.len()
    }

    /// Whether the ops at `a` and `b` came from the same `queue` or `reload` call.
    fn same_frame(&self, a: usize, b: usize) -> bool {
        let (a, b) = (&self.meta[a], &self.meta[b]);
        a.base == b.base && a.external == b.external
    }

    /// Returns the half-open `[start, end)` index range of the frame
    /// containing `idx` (a frame is a contiguous run of ops sharing
    /// the same `base`, set by a single `queue` call).
    fn frame_at(&self, idx: usize) -> (usize, usize) {
        let mut start = idx;
        while start > 0 && self.same_frame(start - 1, idx) {
            start -= 1;
        }
        let mut end = idx + 1;
        while end < self.len() && self.same_frame(end, idx) {
            end += 1;
        }
        (start, end)
    }

    /// A frame is "typing-shaped" if it represents a single keystroke-
    /// scale text edit: exactly one `Replace` whose text is at most one
    /// grapheme (so single-char insertion, backspace from cursor, plain
    /// `\n`), plus at most one trailing `Select`. Adjacent typing-
    /// shaped frames within 500ms group into one undo unit.
    fn frame_is_typing(&self, start: usize, end: usize) -> bool {
        let mut replaces = 0usize;
        let mut text_graphemes = 0usize;
        let mut selects = 0usize;
        for op in &self.all[start..end] {
            match op {
                Operation::Replace(Replace { text, .. }) => {
                    replaces += 1;
                    text_graphemes += text.graphemes(true).count();
                }
                Operation::Select(_) => selects += 1,
            }
        }
        replaces == 1 && text_graphemes <= 1 && selects <= 1
    }

    /// The frame's one replacement, if it has exactly one.
    fn frame_replace(&self, start: usize, end: usize) -> Option<&Replace> {
        let mut replaces = self.all[start..end].iter().filter_map(|op| match op {
            Operation::Replace(replace) => Some(replace),
            Operation::Select(_) => None,
        });
        let replace = replaces.next()?;
        replaces.next().is_none().then_some(replace)
    }

    /// Whether the current frame replaces exactly the text the previous one
    /// inserted, as an input method's composition does with each update and
    /// its commit. Ranges are comparable only if the current frame was based
    /// on the state right after the previous one (selects aside).
    fn frame_revises(&self, (prev_start, prev_end): (usize, usize), curr_start: usize) -> bool {
        let curr_end = self.frame_at(curr_start).1;
        let (Some(prev), Some(curr)) =
            (self.frame_replace(prev_start, prev_end), self.frame_replace(curr_start, curr_end))
        else {
            return false;
        };
        let based_after =
            self.meta[curr_start].base - self.meta[prev_start].base == curr_start - prev_start;
        let inserted = prev.text.graphemes(true).count();
        let start = prev.range.start();
        based_after
            && inserted > 0
            && curr.range.start() == start
            && curr.range.end() == Grapheme(start.0 + inserted)
    }

    fn frame_has_replace(&self, start: usize, end: usize) -> bool {
        self.all[start..end]
            .iter()
            .any(|op| matches!(op, Operation::Replace(_)))
    }

    fn is_undo_checkpoint(&self, idx: usize) -> bool {
        // boundaries
        if idx == 0 || idx == self.len() {
            return true;
        }

        // within a single frame, never a checkpoint
        if self.same_frame(idx - 1, idx) {
            return false;
        }

        // external frames are never undone, so no unit spans one
        if self.meta[idx].external || self.meta[idx - 1].external {
            return true;
        }

        // current-frame analysis
        let (curr_start, curr_end) = self.frame_at(idx);
        if !self.frame_has_replace(curr_start, curr_end) {
            // select-only frame absorbs into the prev unit
            return false;
        }

        // walk back through any select-only frames to find the prev
        // real frame. Selects absorb backward, so an undo of *this*
        // unit doesn't revert the cursor placement (click) that came
        // before it.
        let mut walk = curr_start;
        let prev_real = loop {
            if walk == 0 {
                break None;
            }
            let (s, e) = self.frame_at(walk - 1);
            if self.frame_has_replace(s, e) {
                break Some((s, e));
            }
            walk = s;
        };

        // a composition's updates and commit revise one insertion
        if prev_real.is_some_and(|prev| self.frame_revises(prev, curr_start)) {
            return false;
        }

        // typing-grouping: rapid single-keystroke edits stay in one
        // unit so a burst of typing undoes together
        if let Some((prev_start, prev_end)) = prev_real {
            let curr_typing = self.frame_is_typing(curr_start, curr_end);
            let prev_typing = self.frame_is_typing(prev_start, prev_end);
            if curr_typing && prev_typing {
                let gap = self.meta[curr_start]
                    .timestamp
                    .saturating_sub(self.meta[prev_end - 1].timestamp);
                if gap <= Duration::from_millis(500) {
                    return false;
                }
            }
        }

        true
    }
}

#[derive(Default)]
struct External {
    /// Text last loaded into the editor. Used as a reference point for merging out-of-editor changes with in-editor
    /// changes, similar to a base in a 3-way merge. May be a state that never appears in the buffer's history.
    text: String,

    /// Local replacements a save in flight wrote over `text`, in order, undos as the inverses they applied.
    flushed: Vec<Replace>,

    /// Local replacements applied since, in the same form. Applied to `text` after `flushed`, they give the buffer's
    /// text.
    pending: Vec<Replace>,
}

impl External {
    /// Drops each of `edits`, made in order to `text`, along with the one right after that leaves the text as it was
    /// before it, as an undo or a backspace does, so that edits which cancel out don't win conflicts.
    fn drop_reverted(text: &str, edits: Vec<Replace>) -> Vec<Replace> {
        let mut text =
            Snapshot { text: text.into(), segs: unicode_segs::calc(text), ..Default::default() };
        // each kept edit with the bytes it wrote and the text they replaced
        let mut kept: Vec<(Replace, (Byte, Byte), String)> = vec![];
        for p in edits {
            let range = text.segs.range_to_byte(p.range);
            let reverts = kept.last().is_some_and(|(_, written, replaced)| {
                same_replace(&text.text, (*written, replaced), (range, &p.text))
            });
            let replaced = text[range].to_string();
            text.apply_replace(&p);
            if reverts {
                kept.pop();
            } else {
                let written = (range.0, Byte(range.0.0 + p.text.len()));
                kept.push((p, written, replaced));
            }
        }
        kept.into_iter().map(|(p, _, _)| p).collect()
    }

    /// Splits each of `edits`, made in order to `text`, into what it changes: the pieces a diff of what it replaced and
    /// what it wrote finds, last first so each piece's range is still where the diff put it. Only what changed wins
    /// conflicts: text an edit writes back as it was is no longer its own, and an edit that changes nothing is gone.
    /// Returns the pieces and the text after them.
    fn split(text: &str, edits: Vec<Replace>) -> (Vec<Replace>, String) {
        let mut text =
            Snapshot { text: text.into(), segs: unicode_segs::calc(text), ..Default::default() };
        let mut pieces = vec![];
        for p in edits {
            let start = p.range.start();
            for mut piece in diff(&text[p.range], &p.text).into_iter().rev() {
                piece.range = (start + piece.range.0.0, start + piece.range.1.0);
                text.apply_replace(&piece);
                pieces.push(piece);
            }
        }
        (pieces, text.text)
    }

    /// Rebases the local edits onto `text`, the new external text, and returns the external changes as one frame on
    /// `current`, the buffer's text. Local edits win conflicts: an external change overlapping one is dropped, and the
    /// local edit, rebased, replaces what it wrote. Flushed and pending edits are tidied apart, so a save in flight
    /// still records the edits it wrote; a newer version voids that save, whose write over `text` will be refused.
    fn reload(&mut self, text: String, current: &str) -> Vec<Replace> {
        let mut remote = diff(&self.text, &text);
        if text != self.text {
            let pending = std::mem::take(&mut self.pending);
            self.pending = std::mem::take(&mut self.flushed);
            self.pending.extend(pending);
        }
        let (flushed, after) = Self::split(
            &self.text,
            Self::drop_reverted(&self.text, std::mem::take(&mut self.flushed)),
        );
        let (pending, _) =
            Self::split(&after, Self::drop_reverted(&after, std::mem::take(&mut self.pending)));
        (self.flushed, self.pending) = (flushed, pending);
        let base = std::mem::replace(&mut self.text, text);
        if self.flushed.is_empty() && self.pending.is_empty() {
            return remote;
        }

        // each pending edit is taken from `local`, the text before it, to `theirs`, that text plus the remote edits,
        // which wrote the ranges in `written`
        let segs = unicode_segs::calc(&base);
        let mut local = Snapshot { text: base, segs, ..Default::default() };
        let (mut theirs, mut written) = {
            let applied = applied(&local.text, &remote);
            let written = applied.written();
            (applied.current, written)
        };
        for p in self.flushed.iter_mut().chain(&mut self.pending) {
            *p = whole_graphemes(&local, p);
            let (_, len) = local.apply_replace(p);

            // the region the local edit takes over: its range and the remote edits it drops
            let mut region = (p.range.start(), p.range.end());
            let mut kept = vec![];
            let mut dropped = vec![];
            for r in &remote {
                let mut op = Operation::Replace(r.clone());
                let lost = transform_past(&mut op, p.range, len);
                dropped.push(lost);
                if lost {
                    region = (region.0.min(r.range.start()), region.1.max(r.range.end()));
                } else if let Operation::Replace(r) = op {
                    kept.push(r);
                }
            }
            let mut end = region.1;
            adjust_subsequent_position(p.range, len, true, &mut end);
            let local_region = (region.0, end);

            // a kept remote edit precedes the region if it starts before it, or inserts where a replaced region starts
            let sides: Vec<Option<bool>> = remote
                .iter()
                .zip(&dropped)
                .map(|(r, lost)| {
                    let start = r.range.start();
                    let before = start < region.0
                        || (start == region.0 && r.range.is_empty() && !region.is_empty());
                    (!lost).then_some(before)
                })
                .collect();

            // in the remote text the region also covers what the dropped edits wrote; the kept ones stay outside it
            let chain = || {
                remote
                    .iter()
                    .zip(&written)
                    .map(|(r, w)| ((w.0, w.0 + r.range.len()), w.len()))
            };
            let theirs_region = (
                map(chain(), region.0, |j| sides[j].unwrap_or(false)),
                map(chain(), region.1, |j| sides[j].unwrap_or(true)),
            );
            *p = Replace { range: theirs_region, text: local[local_region].into() };
            let (_, rebased_len) = theirs.apply_replace(p);
            written = written
                .iter()
                .zip(&sides)
                .filter_map(|(w, side)| {
                    let mut w = *w;
                    let before = (*side)?;
                    adjust_subsequent_range(p.range, rebased_len, !before, &mut w);
                    Some(w)
                })
                .collect();
            remote = kept;
            if cfg!(debug_assertions) {
                let merged = applied(&local.text, &remote);
                assert_eq!(
                    theirs.text, merged.current.text,
                    "a rebased edit gives the merged text"
                );
                assert_eq!(written, merged.written(), "the remote edits stay where they wrote");
            }
        }
        debug_assert_eq!(local.text, current, "the pending edits give the buffer's text");
        remote
    }
}

/// Maps a position through `chain`, replacements applied in order with the graphemes each contributed, advancing past
/// the `j`th if `advance(j)`.
fn map(
    chain: impl Iterator<Item = ((Grapheme, Grapheme), Graphemes)>, mut position: Grapheme,
    advance: impl Fn(usize) -> bool,
) -> Grapheme {
    for (j, (range, len)) in chain.enumerate() {
        adjust_subsequent_position(range, len, advance(j), &mut position);
    }
    position
}

/// A buffer of `text` that has applied `frame`, edits of `text` as one frame.
fn applied(text: &str, frame: &[Replace]) -> Buffer {
    let mut buffer = Buffer::from(text);
    let ops = frame.iter().cloned().map(Operation::Replace).collect();
    buffer.push_frame(ops, Duration::ZERO, true);
    buffer.update();
    buffer
}

#[derive(Default)]
pub struct Response {
    pub text_updated: bool,
    /// True iff the selection was set by an explicit `Select` op or by
    /// `undo`/`redo` restoring a historical selection. False when the
    /// selection moved only because a `Replace` op OT-shifted its
    /// offsets — that's a side effect of editing, not a user navigation.
    /// Callers use this to gate scroll-to-cursor: programmatic edits
    /// (e.g. fold-button taps) shouldn't pull the viewport.
    pub selection_user_moved: bool,
    pub open_camera: bool,
    /// Sequence range of operations applied this frame. Use
    /// `buffer.replacements_since(seq_before)` to get the edits.
    pub seq_before: usize,
    pub seq_after: usize,
}

impl std::ops::BitOrAssign for Response {
    fn bitor_assign(&mut self, other: Response) {
        self.text_updated |= other.text_updated;
        self.selection_user_moved |= other.selection_user_moved;
        self.open_camera |= other.open_camera;
        // keep the earliest seq_before and latest seq_after
        if self.seq_before == self.seq_after {
            self.seq_before = other.seq_before;
        }
        self.seq_after = other.seq_after;
    }
}

/// Additional metadata tracked alongside operations internally.
#[derive(Clone, Debug)]
struct OpMeta {
    /// When this operation was queued, on the caller's clock. Affects undo units.
    pub timestamp: Duration,

    /// What version of the buffer was the modifier looking at when they made this operation? Used for operational
    /// transformation, both when applying multiple operations in one frame and when merging out-of-editor changes.
    /// The magic happens here.
    pub base: usize,

    /// Whether this operation came from `reload`. External operations are never undone.
    pub external: bool,
}

impl Buffer {
    /// Push a series of operations onto the buffer's input queue; operations will be undone/redone atomically. Useful
    /// for batches of internal operations produced from a single input event e.g. multi-line list identation. `now`
    /// is the caller's clock, which groups typing into undo units.
    pub fn queue(&mut self, mut ops: Vec<Operation>, now: Duration) {
        let timestamp = now;

        // combine adjacent replacements
        let mut combined_ops = Vec::new();
        ops.sort_by_key(|op| match op {
            Operation::Select(range) | Operation::Replace(Replace { range, .. }) => range.start(),
        });
        for op in ops.into_iter() {
            match &op {
                Operation::Replace(Replace { range: op_range, text: op_text }) => {
                    if let Some(Operation::Replace(Replace {
                        range: last_op_range,
                        text: last_op_text,
                    })) = combined_ops.last_mut()
                    {
                        if last_op_range.end() == op_range.start() {
                            last_op_range.1 = op_range.1;
                            last_op_text.push_str(op_text);
                        } else {
                            combined_ops.push(op);
                        }
                    } else {
                        combined_ops.push(op);
                    }
                }
                Operation::Select(_) => combined_ops.push(op),
            }
        }

        self.push_frame(combined_ops, timestamp, false);
    }

    fn push_frame(&mut self, ops: Vec<Operation>, timestamp: Duration, external: bool) {
        let base = self.current.seq;
        self.ops
            .meta
            .extend(ops.iter().map(|_| OpMeta { timestamp, base, external }));
        self.ops.all.extend(ops);
    }

    /// Loads a new string into the buffer, merging out-of-editor changes made since last load with in-editor changes
    /// made since last load. The merge is queued as an external frame, which undo never reverts. Applies the queue, so
    /// the next reload merges against it.
    pub fn reload(&mut self, text: String) -> Response {
        let mut response = self.update();
        let remote = self.external.reload(text, &self.current.text);
        // an external frame ends undo units, so its time is never compared
        self.push_frame(remote.into_iter().map(Operation::Replace).collect(), Duration::ZERO, true);
        response |= self.update();
        response
    }

    /// Marks the local replacements so far as written by a save; read the text the save writes with it. A flush
    /// before the last one's `saved` adds to it, as a failed save writes nothing.
    pub fn flush(&mut self) {
        let pending = std::mem::take(&mut self.external.pending);
        self.external.flushed.extend(pending);
    }

    /// Indicates to the buffer the text that has been saved outside the editor, which had the local replacements up
    /// to the last `flush`. This will serve as the new base for merging external changes.
    pub fn saved(&mut self, external_text: String) {
        self.external.flushed.clear();
        self.external.text = external_text;
    }

    /// Three-way merge of two versions of the buffer's external text, with `external_text_a` winning conflicts.
    pub fn merge(mut self, external_text_a: String, external_text_b: String) -> String {
        let ops_a = diff(&self.external.text, &external_text_a);
        let ops_b = diff(&self.external.text, &external_text_b);

        let ops = ops_a
            .into_iter()
            .chain(ops_b)
            .map(Operation::Replace)
            .collect();
        self.push_frame(ops, Duration::ZERO, false);

        self.update();
        self.current.text
    }

    /// Applies all operations in the buffer's input queue
    pub fn update(&mut self) -> Response {
        // clear redo stack
        //             v base        v current    v processed
        // ops before: |<- applied ->|<- undone ->|<- queued ->|
        // ops after:  |<- applied ->|<- queued ->|
        let queue_len = self.base.seq + self.ops.len() - self.ops.processed_seq;
        if queue_len > 0 {
            let drain_range = self.current.seq..self.ops.processed_seq;
            self.ops.all.drain(drain_range.clone());
            self.ops.meta.drain(drain_range.clone());
            self.ops.transformed.drain(drain_range.clone());
            self.ops.transformed_inverted.drain(drain_range.clone());
            self.ops.transformed_actual_len.drain(drain_range.clone());
            self.ops.processed_seq = self.current.seq;
        } else {
            return Response::default();
        }

        // transform & apply
        let mut result = Response { seq_before: self.current.seq, ..Default::default() };
        for idx in self.current_idx()..self.current_idx() + queue_len {
            let mut op = self.ops.all[idx].clone();
            let meta = &self.ops.meta[idx];
            self.transform(&mut op, meta);
            // the inverse needs the text before apply and after it
            let partial_inverse = self.current.invert_pre(&op);
            self.ops.transformed.push(op.clone());
            self.ops.transformed_actual_len.push(Graphemes::default());
            self.ops.processed_seq += 1;

            result |= self.redo();

            self.ops
                .transformed_inverted
                .push(partial_inverse.finalize(&self.current));
        }

        result.seq_after = self.current.seq;
        result
    }

    fn transform(&self, op: &mut Operation, meta: &OpMeta) {
        let base_idx = meta.base - self.base.seq;
        for transforming_idx in base_idx..self.ops.processed_seq {
            if let Operation::Replace(Replace { range, .. }) =
                &self.ops.transformed[transforming_idx]
            {
                transform_past(op, *range, self.ops.transformed_actual_len[transforming_idx]);
            }
        }
    }

    /// The ranges the applied replacements wrote, each in the text after all of them, which is so when each applied
    /// one lies after those before it.
    fn written(&self) -> Vec<(Grapheme, Grapheme)> {
        self.ops
            .transformed
            .iter()
            .zip(&self.ops.transformed_actual_len)
            .filter_map(|(op, len)| match op {
                Operation::Replace(Replace { range, .. }) => {
                    Some((range.start(), range.start() + *len))
                }
                Operation::Select(_) => None,
            })
            .collect()
    }

    pub fn can_redo(&self) -> bool {
        self.current.seq < self.ops.processed_seq
    }

    /// Undo stops at the last external frame, so it never reverts an edit made outside the editor. Selection-only frames above it
    /// belong to it, as they belong to the frame below them anywhere else.
    pub fn can_undo(&self) -> bool {
        let mut idx = self.current_idx();
        while idx > 0 {
            let (start, end) = self.ops.frame_at(idx - 1);
            if self.ops.meta[start].external {
                return false;
            }
            if self.ops.frame_has_replace(start, end) {
                return true;
            }
            idx = start;
        }
        self.current_idx() > 0
    }

    pub fn redo(&mut self) -> Response {
        let mut response = Response::default();
        while self.can_redo() {
            let idx = self.current_idx();
            // Clone so we can mutate `self` (storing actual_len) without
            // holding a borrow of `self.ops.transformed`.
            let op = self.ops.transformed[idx].clone();

            self.current.seq += 1;

            let actual_len = match &op {
                Operation::Replace(replace) => {
                    let (resp, len) = self.current.apply_replace(replace);
                    if !self.ops.meta[idx].external {
                        self.external.pending.push(replace.clone());
                    }
                    response |= resp;
                    len
                }
                Operation::Select(range) => {
                    response |= self.current.apply_select(*range);
                    Graphemes::default()
                }
            };
            self.ops.transformed_actual_len[idx] = actual_len;

            if self.ops.is_undo_checkpoint(self.current_idx()) {
                break;
            }
        }
        response
    }

    pub fn undo(&mut self) -> Response {
        let mut response = Response::default();
        while self.can_undo() {
            response |= self.step_back();
            if self.ops.is_undo_checkpoint(self.current_idx()) {
                break;
            }
        }
        response
    }

    /// Reverts the last applied operation.
    fn step_back(&mut self) -> Response {
        let mut response = Response::default();
        self.current.seq -= 1;
        // Clone so we can mutate `self.current` while reading the inverse.
        let op = self.ops.transformed_inverted[self.current_idx()].clone();

        if let Some(replace) = op.replace {
            let (resp, _) = self.current.apply_replace(&replace);
            self.external.pending.push(replace);
            response |= resp;
        }
        response |= self.current.apply_select(op.select);
        response
    }

    fn current_idx(&self) -> usize {
        self.current.seq - self.base.seq
    }

    /// Transforms a range through all replacements applied between
    /// `since_seq` and the current sequence. Returns `false` if the range
    /// intersected a replacement (i.e. the content it referred to was
    /// modified) or an undo took the current sequence below `since_seq`.
    pub fn transform_range(&self, since_seq: usize, range: &mut (Grapheme, Grapheme)) -> bool {
        if since_seq > self.current.seq {
            return false;
        }
        let start = since_seq.saturating_sub(self.base.seq);
        let end = self.current_idx();
        for (i, op) in self.ops.transformed[start..end].iter().enumerate() {
            if let Operation::Replace(replace) = op {
                if range.intersects(&replace.range, true)
                    && !(range.is_empty() && replace.range.is_empty())
                {
                    return false;
                }
                let replacement_len = self.ops.transformed_actual_len[start + i];
                adjust_subsequent_range(replace.range, replacement_len, false, range);
            }
        }
        true
    }

    /// Reports whether the buffer's current text is empty.
    pub fn is_empty(&self) -> bool {
        self.current.text.is_empty()
    }

    pub fn selection_text(&self) -> String {
        self[self.current.selection].to_string()
    }
}

impl From<&str> for Buffer {
    fn from(value: &str) -> Self {
        let mut result = Self::default();
        result.current.text = value.to_string();
        result.current.segs = unicode_segs::calc(value);
        result.external.text = value.to_string();
        result
    }
}

/// Transforms `op` past a replacement of `preceding_replaced_range` already applied, which contributed
/// `preceding_actual_len` graphemes. Returns whether `op` lost a conflict with it and was emptied.
fn transform_past(
    op: &mut Operation, preceding_replaced_range: (Grapheme, Grapheme),
    preceding_actual_len: Graphemes,
) -> bool {
    let mut lost = false;
    if let Operation::Replace(Replace { range: transformed_range, text }) = op {
        if preceding_replaced_range.intersects(transformed_range, false)
            && !(preceding_replaced_range.is_empty() && transformed_range.is_empty())
        {
            // concurrent replacements to intersecting ranges choose the first/local edit as the winner
            // this doesn't create self-conflicts during merge because merge combines adjacent replacements
            // this doesn't create self-conflicts for same-frame editor changes because our final condition
            // is that we don't simultaneously insert text for both operations, which creates un-ideal
            // behavior (see test buffer_merge_insert)
            *text = "".into();
            transformed_range.1 = transformed_range.0;
            lost = true;
        }
    }

    match op {
        // an edit that only touches a replaced range's ends lies outside it
        Operation::Replace(Replace { range, .. }) => {
            let (replaced, len) = (preceding_replaced_range, preceding_actual_len);
            let at_start = !replaced.is_empty() && range.start() == replaced.start();
            let insert = range.is_empty();
            let forward = range.0 <= range.1;
            let (a, b) = (&mut range.0, &mut range.1);
            let (start, end) = if forward { (a, b) } else { (b, a) };
            adjust_subsequent_position(replaced, len, !(insert && at_start), start);
            adjust_subsequent_position(replaced, len, insert && !at_start, end);
        }
        Operation::Select(transformed_range) => {
            adjust_subsequent_range(
                preceding_replaced_range,
                preceding_actual_len,
                true,
                transformed_range,
            );
        }
    }
    lost
}

/// Whether writing `a.1` over the bytes `a.0` of `text` gives the same text as writing `b.1` over `b.0`.
fn same_replace(text: &str, a: ((Byte, Byte), &str), b: ((Byte, Byte), &str)) -> bool {
    let (((a_lo, a_hi), a_text), ((b_lo, b_hi), b_text)) = (a, b);
    let (lo, hi) = (a_lo.min(b_lo).0, a_hi.max(b_hi).0);
    let a = [&text[lo..a_lo.0], a_text, &text[a_hi.0..hi]];
    let b = [&text[lo..b_lo.0], b_text, &text[b_hi.0..hi]];
    a.concat() == b.concat()
}

/// `replace` on `before`, widened to whole graphemes of the text after it: a
/// combining mark it writes fuses into the grapheme before it, which the edit
/// then takes over.
fn whole_graphemes(before: &Snapshot, replace: &Replace) -> Replace {
    let (a, b) = before.segs.range_to_byte(replace.range);
    let mut after = before.text.clone();
    after.replace_range(a.0..b.0, &replace.text);
    let segs = unicode_segs::calc(&after);
    let end = a.0 + replace.text.len();
    let (lo, hi) =
        segs.range_to_byte((segs.byte_to_char_floor(a), segs.byte_to_char_ceil(Byte(end))));
    let range = (
        before.segs.byte_to_char_floor(lo).min(replace.range.0),
        before
            .segs
            .byte_to_char_ceil(Byte(b.0 + hi.0 - end))
            .max(replace.range.1),
    );
    let (lo, hi) = before.segs.range_to_byte(range);
    let text = after[lo.0..hi.0 + end - b.0].to_string();
    Replace { range, text }
}

/// Adjust a range based on a text replacement. Positions before the replacement generally are not adjusted,
/// positions after the replacement generally are, and positions within the replacement are adjusted to the end of
/// the replacement if `prefer_advance` is true or are adjusted to the start of the replacement otherwise.
pub fn adjust_subsequent_range(
    replaced_range: (Grapheme, Grapheme), replacement_len: Graphemes, prefer_advance: bool,
    range: &mut (Grapheme, Grapheme),
) {
    for position in [&mut range.0, &mut range.1] {
        adjust_subsequent_position(replaced_range, replacement_len, prefer_advance, position);
    }
}

/// Adjust a position based on a text replacement. Positions before the replacement generally are not adjusted,
/// positions after the replacement generally are, and positions within the replacement are adjusted to the end of
/// the replacement if `prefer_advance` is true or are adjusted to the start of the replacement otherwise.
fn adjust_subsequent_position(
    replaced_range: (Grapheme, Grapheme), replacement_len: Graphemes, prefer_advance: bool,
    position: &mut Grapheme,
) {
    let replaced_len = replaced_range.len();
    let replacement_start = replaced_range.start();
    let replacement_end = replacement_start + replacement_len;

    enum Mode {
        Insert,
        Replace,
    }
    let mode = if replaced_range.is_empty() { Mode::Insert } else { Mode::Replace };

    let sorted_bounds = {
        let mut bounds = vec![replaced_range.start(), replaced_range.end(), *position];
        bounds.sort();
        bounds
    };
    let bind = |start: &Grapheme, end: &Grapheme, pos: &Grapheme| {
        start == &replaced_range.start() && end == &replaced_range.end() && pos == &*position
    };

    *position = match (mode, &sorted_bounds[..]) {
        // case 1: position at point of text insertion
        //                       text before replacement: * *
        //                        range of replaced text:  |
        //          range of subsequent cursor selection:  |
        //                        text after replacement: * X *
        // advance:
        // adjusted range of subsequent cursor selection:    |
        // don't advance:
        // adjusted range of subsequent cursor selection:  |
        (Mode::Insert, [start, end, pos]) if bind(start, end, pos) && end == pos => {
            if prefer_advance {
                replacement_end
            } else {
                replacement_start
            }
        }

        // case 2: position at start of text replacement
        //                       text before replacement: * * * *
        //                        range of replaced text:  |<->|
        //          range of subsequent cursor selection:  |
        //                        text after replacement: * X *
        // adjusted range of subsequent cursor selection:  |
        (Mode::Replace, [start, pos, end]) if bind(start, end, pos) && start == pos => {
            if prefer_advance {
                replacement_end
            } else {
                replacement_start
            }
        }

        // case 3: position at end of text replacement
        //                       text before replacement: * * * *
        //                        range of replaced text:  |<->|
        //          range of subsequent cursor selection:      |
        //                        text after replacement: * X *
        // adjusted range of subsequent cursor selection:    |
        (Mode::Replace, [start, end, pos]) if bind(start, end, pos) && end == pos => {
            if prefer_advance {
                replacement_end
            } else {
                replacement_start
            }
        }

        // case 4: position before point/start of text insertion/replacement
        //                       text before replacement: * * * * *
        //       (possibly empty) range of replaced text:    |<->|
        //          range of subsequent cursor selection:  |
        //                        text after replacement: * * X *
        // adjusted range of subsequent cursor selection:  |
        (_, [pos, start, end]) if bind(start, end, pos) => *position,

        // case 5: position within text replacement
        //                       text before replacement: * * * *
        //                        range of replaced text:  |<->|
        //          range of subsequent cursor selection:    |
        //                        text after replacement: * X *
        // advance:
        // adjusted range of subsequent cursor selection:    |
        // don't advance:
        // adjusted range of subsequent cursor selection:  |
        (Mode::Replace, [start, pos, end]) if bind(start, end, pos) => {
            if prefer_advance {
                replacement_end
            } else {
                replacement_start
            }
        }

        // case 6: position after point/end of text insertion/replacement
        //                       text before replacement: * * * * *
        //       (possibly empty) range of replaced text:  |<->|
        //          range of subsequent cursor selection:        |
        //                        text after replacement: * X * *
        // adjusted range of subsequent cursor selection:      |
        (_, [start, end, pos]) if bind(start, end, pos) => {
            *position + replacement_len - replaced_len
        }
        _ => unreachable!(),
    }
}

impl Index<(Byte, Byte)> for Snapshot {
    type Output = str;

    fn index(&self, index: (Byte, Byte)) -> &Self::Output {
        &self.text[index.start().0..index.end().0]
    }
}

impl Index<(Grapheme, Grapheme)> for Snapshot {
    type Output = str;

    fn index(&self, index: (Grapheme, Grapheme)) -> &Self::Output {
        let index = self.segs.range_to_byte(index);
        &self.text[index.start().0..index.end().0]
    }
}

impl Index<(Byte, Byte)> for Buffer {
    type Output = str;

    fn index(&self, index: (Byte, Byte)) -> &Self::Output {
        &self.current[index]
    }
}

impl Index<(Grapheme, Grapheme)> for Buffer {
    type Output = str;

    fn index(&self, index: (Grapheme, Grapheme)) -> &Self::Output {
        &self.current[index]
    }
}

#[cfg(test)]
mod test {
    use super::Buffer;
    use crate::model::text::offset_types::{Grapheme, RangeExt as _};
    use crate::model::text::operation_types::{Operation, Replace};
    use std::time::Duration;
    use unicode_segmentation::UnicodeSegmentation;

    fn type_into_selection(buffer: &mut Buffer, text: &str) {
        let range = buffer.current.selection;
        buffer.queue(
            vec![
                Operation::Replace(Replace { range, text: text.into() }),
                Operation::Select((range.start(), range.start())),
            ],
            Duration::ZERO,
        );
        buffer.update();
    }

    #[test]
    fn a_reload_keeps_a_combining_mark_typed_onto_its_neighbor() {
        // the mark fuses into "*", so the edit that wrote it spans no grapheme of its own
        let mut buffer = Buffer::from("*abc\n");
        let mark = Replace { range: (Grapheme(1), Grapheme(4)), text: "\u{94d}".into() };
        buffer.queue(vec![Operation::Replace(mark)], Duration::ZERO);
        buffer.update();
        buffer.reload("Z*abc\n".into());
        buffer.update();
        assert_eq!(buffer.current.text, "Z*\u{94d}\n");
    }

    #[test]
    fn a_reload_keeps_a_word_written_beside_a_wider_local_edit() {
        // a table cell rewrite writes `|-` over `--`: only its first character changed
        let mut buffer = Buffer::from("--\n-");
        let rewrite = Replace { range: (Grapheme(0), Grapheme(2)), text: "|-".into() };
        buffer.queue(vec![Operation::Replace(rewrite)], Duration::ZERO);
        buffer.update();
        for version in ["--\n--", "-bar -\n--"] {
            buffer.reload(version.into());
            buffer.update();
        }
        assert_eq!(buffer.current.text, "|bar -\n--");
    }

    #[test]
    fn undo_takes_back_a_combining_mark_typed_after_its_letter() {
        let mut buffer = Buffer::from("xxxxx doc");
        let mark = Replace { range: (Grapheme(1), Grapheme(1)), text: "\u{948}".into() };
        buffer.queue(vec![Operation::Replace(mark)], Duration::ZERO);
        buffer.update();
        assert_eq!(buffer.current.text, "x\u{948}xxxx doc");

        buffer.undo();
        assert_eq!(buffer.current.text, "xxxxx doc");
        buffer.redo();
        assert_eq!(buffer.current.text, "x\u{948}xxxx doc");
    }

    #[test]
    fn type_into_forward_selection() {
        let mut buffer = Buffer::from("hello");
        buffer.current.selection = (Grapheme(0), Grapheme(5));
        type_into_selection(&mut buffer, "X");
        assert_eq!(buffer.current.text, "X");
        assert_eq!(buffer.current.selection, (Grapheme(1), Grapheme(1)));
    }

    #[test]
    fn type_into_backward_selection() {
        let mut buffer = Buffer::from("hello");
        buffer.current.selection = (Grapheme(5), Grapheme(0));
        type_into_selection(&mut buffer, "X");
        assert_eq!(buffer.current.text, "X");
        assert_eq!(buffer.current.selection, (Grapheme(1), Grapheme(1)));
    }

    #[test]
    fn backward_replace_beside_a_replacement() {
        let mut buffer = Buffer::from("aa bb cc");
        buffer.queue(
            vec![
                Operation::Replace(Replace { range: (Grapheme(0), Grapheme(2)), text: "Q".into() }),
                Operation::Select((Grapheme(2), Grapheme(2))),
                Operation::Replace(Replace { range: (Grapheme(5), Grapheme(2)), text: "".into() }),
            ],
            Duration::ZERO,
        );
        buffer.update();
        assert_eq!(buffer.current.text, "Q cc");
    }

    #[test]
    fn buffer_merge_nonintersecting_replace() {
        let base_content = "base content base";
        let local_content = "local content base";
        let remote_content = "base content remote";

        assert_eq!(
            Buffer::from(base_content).merge(local_content.into(), remote_content.into()),
            "local content remote"
        );
        assert_eq!(
            Buffer::from(base_content).merge(remote_content.into(), local_content.into()),
            "local content remote"
        );
    }

    #[test]
    fn buffer_merge_prefix_replace() {
        let base_content = "base content";
        let local_content = "local content";
        let remote_content = "remote content";

        assert_eq!(
            Buffer::from(base_content).merge(local_content.into(), remote_content.into()),
            "local content"
        );
    }

    #[test]
    fn buffer_merge_infix_replace() {
        let base_content = "con base tent";
        let local_content = "con local tent";
        let remote_content = "con remote tent";

        assert_eq!(
            Buffer::from(base_content).merge(local_content.into(), remote_content.into()),
            "con local tent"
        );
        assert_eq!(
            Buffer::from(base_content).merge(remote_content.into(), local_content.into()),
            "con remote tent"
        );
    }

    #[test]
    fn buffer_merge_postfix_replace() {
        let base_content = "content base";
        let local_content = "content local";
        let remote_content = "content remote";

        assert_eq!(
            Buffer::from(base_content).merge(local_content.into(), remote_content.into()),
            "content local"
        );
        assert_eq!(
            Buffer::from(base_content).merge(remote_content.into(), local_content.into()),
            "content remote"
        );
    }

    #[test]
    fn buffer_merge_insert() {
        let base_content = "content";
        let local_content = "content local";
        let remote_content = "content remote";

        assert_eq!(
            Buffer::from(base_content).merge(local_content.into(), remote_content.into()),
            "content local remote"
        );
        assert_eq!(
            Buffer::from(base_content).merge(remote_content.into(), local_content.into()),
            "content remote local"
        );
    }

    #[test]
    fn buffer_merge_edits_touching_a_replaced_word() {
        // an insert at a replaced word's start, a replace ending at it, a replace starting at it
        for (base, local, remote, merged) in [
            ("bar foo foo\n", "Жbar foo foo\n", "foo bar foo foo\n", "foo Жbar foo foo\n"),
            ("aa bb", "aa Жbb", "aa  bb", "aa  Жbb"),
            ("one two three", "one 2 three", "one and two three", "one and 2 three"),
        ] {
            let merge = |a: &str, b: &str| Buffer::from(base).merge(a.into(), b.into());
            assert_eq!(merge(local, remote), merged);
            assert_eq!(merge(remote, local), merged);
        }
    }

    #[test]
    fn buffer_merge_insert_replace() {
        let base_content = "content";
        let local_content = "content local";
        let remote_content = "remote";

        assert_eq!(
            Buffer::from(base_content).merge(local_content.into(), remote_content.into()),
            "remote local"
        );
        assert_eq!(
            Buffer::from(base_content).merge(remote_content.into(), local_content.into()),
            "remote local"
        );
    }

    #[test]
    // this test case used to crash `merge`
    fn buffer_merge_crash() {
        let base_content = "con tent";
        let local_content = "cont tent locallocal";
        let remote_content = "cont remote tent";

        let _ = Buffer::from(base_content).merge(local_content.into(), remote_content.into());
        let _ = Buffer::from(base_content).merge(remote_content.into(), local_content.into());
    }

    // ── Fuzz ──────────────────────────────────────────────────────────────

    use rand::prelude::*;

    /// Grapheme clusters for fuzz testing. Includes ASCII, multi-byte, multi-codepoint emoji
    /// (ZWJ sequences, skin tones, flags), and combining characters.
    const POOL: &[&str] = &[
        "a",
        "b",
        "z",
        " ",
        "\n",
        "\t",
        "é",
        "ñ",
        "ü",
        "日",
        "本",
        "語",
        "👋",
        "🎉",
        "🔥",
        "❤️",
        "👨‍👩‍👧‍👦",
        "🏳️‍🌈",
        "👍🏽",
        "🇺🇸",
        "🇯🇵",
        "e\u{0301}",
        "a\u{0308}", // combining sequences: é, ä
    ];

    /// Generate a random grapheme-level edit of a document. Picks uniformly from:
    /// - 0: Delete 1-5 consecutive graphemes at a random position
    /// - 1: Insert 1-5 random graphemes from POOL at a random position
    /// - 2: Replace 1-5 consecutive graphemes with 1-3 random graphemes from POOL
    /// - 3: Clear everything
    ///
    /// When the document is empty, cases 0/2/3 fall through to insert (the _ arm).
    fn random_edit(rng: &mut StdRng, doc: &str) -> String {
        let graphemes: Vec<&str> = UnicodeSegmentation::graphemes(doc, true).collect();
        let len = graphemes.len();

        let mut g: Vec<String> = graphemes.iter().map(|s| s.to_string()).collect();

        match rng.gen_range(0..4) {
            0 if len > 0 => {
                let pos = rng.gen_range(0..len);
                let del = rng.gen_range(1..=(len - pos).min(5));
                g.drain(pos..pos + del);
            }
            1 => {
                let pos = rng.gen_range(0..=len);
                let n = rng.gen_range(1..=5);
                for j in 0..n {
                    g.insert(pos + j, POOL[rng.gen_range(0..POOL.len())].into());
                }
            }
            2 if len > 0 => {
                let pos = rng.gen_range(0..len);
                let del = rng.gen_range(1..=(len - pos).min(5));
                let ins: Vec<String> = (0..rng.gen_range(1..=3))
                    .map(|_| POOL[rng.gen_range(0..POOL.len())].into())
                    .collect();
                g.splice(pos..pos + del, ins);
            }
            3 if len > 0 => {
                g.clear();
            }
            _ => {
                let n = rng.gen_range(1..=5);
                for _ in 0..n {
                    g.push(POOL[rng.gen_range(0..POOL.len())].into());
                }
            }
        }
        g.concat()
    }

    #[test]
    fn buffer_merge_fuzz() {
        let mut rng = StdRng::seed_from_u64(42);
        let bases = ["hello world", "👨‍👩‍👧‍👦🇺🇸🔥", "café ñoño 日本語", ""];
        for _ in 0..10_000 {
            let base = bases[rng.gen_range(0..bases.len())];
            let a = random_edit(&mut rng, base);
            let b = random_edit(&mut rng, base);

            // must not panic
            let _ = Buffer::from(base).merge(a.clone(), b.clone());
            let _ = Buffer::from(base).merge(b, a);
        }
    }

    // ── Chain convergence ──

    /// Simulates a sync channel between two adjacent nodes. Holds the last-agreed-upon
    /// document text, which serves as the 3-way merge base. When two nodes sync, their
    /// documents are merged against this base, both nodes adopt the result, and the base
    /// advances. This mirrors how lockbook's sync works: each client keeps a base (last
    /// synced state) and merges local vs remote changes against it.
    struct SyncLink {
        base: String,
    }

    impl SyncLink {
        fn new(base: &str) -> Self {
            Self { base: base.into() }
        }

        fn sync(&mut self, left: &mut String, right: &mut String) {
            let merged = Buffer::from(self.base.as_str()).merge(left.clone(), right.clone());
            *left = merged.clone();
            *right = merged.clone();
            self.base = merged;
        }
    }

    /// Sync all adjacent pairs in both directions until the chain stabilizes.
    /// With N nodes and N-1 links, 2*N passes ensures changes propagate end-to-end.
    fn full_sync(nodes: &mut [String], links: &mut [SyncLink]) {
        for _ in 0..nodes.len() * 2 {
            for i in 0..links.len() {
                let (left, right) = nodes.split_at_mut(i + 1);
                links[i].sync(&mut left[i], &mut right[0]);
            }
            for i in (0..links.len()).rev() {
                let (left, right) = nodes.split_at_mut(i + 1);
                links[i].sync(&mut left[i], &mut right[0]);
            }
        }
    }

    fn partial_sync(nodes: &mut [String], links: &mut [SyncLink], rng: &mut StdRng) {
        for _ in 0..3 {
            for i in 0..links.len() {
                if rng.gen_bool(0.5) {
                    let (left, right) = nodes.split_at_mut(i + 1);
                    links[i].sync(&mut left[i], &mut right[0]);
                }
            }
        }
    }

    fn assert_converged(nodes: &[String]) {
        for (i, node) in nodes.iter().enumerate().skip(1) {
            assert_eq!(
                &nodes[0], node,
                "node 0 and node {} diverged: {:?} vs {:?}",
                i, nodes[0], node
            );
        }
    }

    #[test]
    fn buffer_merge_fuzz_chain_2() {
        let mut rng = StdRng::seed_from_u64(42);
        for _ in 0..10_000 {
            let init = if rng.gen_bool(0.5) { "hello 👋🏽" } else { "" };
            let mut nodes: Vec<String> = (0..2).map(|_| init.into()).collect();
            let mut links: Vec<SyncLink> = (0..1).map(|_| SyncLink::new(init)).collect();

            for _ in 0..rng.gen_range(1..=4) {
                for _ in 0..rng.gen_range(1..=3) {
                    let i = rng.gen_range(0..2);
                    nodes[i] = random_edit(&mut rng, &nodes[i]);
                }
                if rng.gen_bool(0.5) {
                    partial_sync(&mut nodes, &mut links, &mut rng);
                }
            }

            full_sync(&mut nodes, &mut links);
            assert_converged(&nodes);
        }
    }

    #[test]
    fn buffer_merge_fuzz_chain_5() {
        let mut rng = StdRng::seed_from_u64(77);
        for _ in 0..5_000 {
            let init = if rng.gen_bool(0.5) { "café 日本語 🇯🇵" } else { "abc" };
            let mut nodes: Vec<String> = (0..5).map(|_| init.into()).collect();
            let mut links: Vec<SyncLink> = (0..4).map(|_| SyncLink::new(init)).collect();

            for _ in 0..rng.gen_range(1..=3) {
                for _ in 0..rng.gen_range(1..=5) {
                    let i = rng.gen_range(0..5);
                    nodes[i] = random_edit(&mut rng, &nodes[i]);
                }
                if rng.gen_bool(0.5) {
                    partial_sync(&mut nodes, &mut links, &mut rng);
                }
            }

            full_sync(&mut nodes, &mut links);
            assert_converged(&nodes);
        }
    }
}

#[cfg(test)]
mod undo_unit_tests {
    //! Unit-grouping behavior of `undo`. Each `frame` call simulates
    //! one `queue() + update()` (one editor frame). After a sequence
    //! of frames we count how many `undo()` calls it takes to reach a
    //! given state — that count *is* the number of undo units.

    use super::Buffer;
    use crate::model::text::offset_types::{Grapheme, IntoRangeExt as _, RangeExt as _};
    use crate::model::text::operation_types::{Operation, Replace};
    use std::cell::Cell;
    use std::time::Duration;

    thread_local! {
        /// The test's clock, which only `sleep` moves.
        static NOW: Cell<Duration> = const { Cell::new(Duration::ZERO) };
    }

    fn sleep(by: Duration) {
        NOW.with(|now| now.set(now.get() + by));
    }

    fn frame(buf: &mut Buffer, ops: Vec<Operation>) {
        buf.queue(ops, NOW.with(Cell::get));
        buf.update();
    }

    fn type_str(buf: &mut Buffer, s: &str) {
        let cursor = buf.current.selection.start();
        // Select is at the pre-insert cursor; OT advances it to the
        // end of the inserted text via `prefer_advance`.
        frame(
            buf,
            vec![
                Operation::Replace(Replace { range: cursor.into_range(), text: s.into() }),
                Operation::Select(cursor.into_range()),
            ],
        );
    }

    /// Plain Enter at cursor — single `\n` Replace, like the editor
    /// produces when no auto-prefix kicks in.
    fn enter(buf: &mut Buffer) {
        type_str(buf, "\n");
    }

    fn backspace(buf: &mut Buffer) {
        let cursor = buf.current.selection.start();
        if cursor.0 == 0 {
            return;
        }
        let prev = Grapheme(cursor.0 - 1);
        frame(
            buf,
            vec![
                Operation::Replace(Replace { range: (prev, cursor), text: "".into() }),
                Operation::Select(prev.into_range()),
            ],
        );
    }

    fn click(buf: &mut Buffer, pos: usize) {
        frame(buf, vec![Operation::Select(Grapheme(pos).into_range())]);
    }

    /// Multi-Replace frame, the shape produced by tab/shift-tab
    /// cascades — explicitly not typing-shaped.
    fn cmd_indent_lines(buf: &mut Buffer, line_starts: &[usize]) {
        let mut ops: Vec<Operation> = line_starts
            .iter()
            .map(|&s| {
                Operation::Replace(Replace { range: Grapheme(s).into_range(), text: "  ".into() })
            })
            .collect();
        ops.push(Operation::Select(Grapheme(line_starts[0] + 2).into_range()));
        frame(buf, ops);
    }

    fn cmd_deindent_lines(buf: &mut Buffer, line_starts: &[usize]) {
        let mut ops: Vec<Operation> = line_starts
            .iter()
            .map(|&s| {
                Operation::Replace(Replace {
                    range: (Grapheme(s), Grapheme(s + 2)),
                    text: "".into(),
                })
            })
            .collect();
        ops.push(Operation::Select(Grapheme(line_starts[0]).into_range()));
        frame(buf, ops);
    }

    // ─── A: single command undoes in one step ──────────────────────
    #[test]
    fn single_command_one_unit() {
        let mut buf = Buffer::from("ab\ncd\nef\n");
        cmd_indent_lines(&mut buf, &[0, 3, 6]);
        assert_eq!(buf.current.text, "  ab\n  cd\n  ef\n");
        buf.undo();
        assert_eq!(buf.current.text, "ab\ncd\nef\n");
    }

    // ─── B: two commands undo independently ────────────────────────
    #[test]
    fn two_commands_two_units() {
        let mut buf = Buffer::from("ab\ncd\nef\n");
        cmd_indent_lines(&mut buf, &[0, 3, 6]);
        cmd_indent_lines(&mut buf, &[2, 7, 12]);
        let after_two = buf.current.text.clone();
        buf.undo();
        assert_ne!(buf.current.text, after_two);
        let after_one_undo = buf.current.text.clone();
        assert_eq!(after_one_undo, "  ab\n  cd\n  ef\n");
        buf.undo();
        assert_eq!(buf.current.text, "ab\ncd\nef\n");
    }

    // ─── C: click only doesn't form an undoable unit ───────────────
    #[test]
    fn click_only_doesnt_create_unit() {
        let mut buf = Buffer::from("hello");
        click(&mut buf, 3);
        // No real edits ever — undo() can technically undo the
        // selection move, but that's the only thing in history.
        // Important: it doesn't create a checkpoint that would block
        // a subsequent edit's undo from reaching past it.
        type_str(&mut buf, "X");
        assert_eq!(buf.current.text, "helXlo");
        buf.undo();
        assert_eq!(buf.current.text, "hello");
    }

    // ─── D: click between two commands, click absorbs ──────────────
    #[test]
    fn click_between_commands_absorbs() {
        let mut buf = Buffer::from("ab\ncd\nef\n");
        cmd_indent_lines(&mut buf, &[0, 3, 6]);
        click(&mut buf, 0);
        cmd_indent_lines(&mut buf, &[2, 7, 12]);
        buf.undo();
        assert_eq!(buf.current.text, "  ab\n  cd\n  ef\n");
        buf.undo();
        assert_eq!(buf.current.text, "ab\ncd\nef\n");
    }

    // ─── E: rapid typing groups into one unit ──────────────────────
    #[test]
    fn rapid_typing_one_unit() {
        let mut buf = Buffer::from("");
        type_str(&mut buf, "a");
        type_str(&mut buf, "b");
        type_str(&mut buf, "c");
        assert_eq!(buf.current.text, "abc");
        buf.undo();
        assert_eq!(buf.current.text, "");
    }

    // ─── F: typing with a long pause splits at the gap ─────────────
    #[test]
    fn typing_long_pause_splits() {
        let mut buf = Buffer::from("");
        type_str(&mut buf, "a");
        type_str(&mut buf, "b");
        sleep(Duration::from_millis(600));
        type_str(&mut buf, "c");
        type_str(&mut buf, "d");
        assert_eq!(buf.current.text, "abcd");
        buf.undo();
        assert_eq!(buf.current.text, "ab");
        buf.undo();
        assert_eq!(buf.current.text, "");
    }

    // ─── G: type / cmd / type → 3 units ────────────────────────────
    #[test]
    fn type_cmd_type_three_units() {
        let mut buf = Buffer::from("xx\nyy\n");
        // pre-position cursor at end so type_str appends after the doc
        buf.current.selection = (Grapheme(6), Grapheme(6));
        type_str(&mut buf, "a");
        type_str(&mut buf, "b");
        cmd_indent_lines(&mut buf, &[0, 3]);
        type_str(&mut buf, "c");
        type_str(&mut buf, "d");
        let final_text = buf.current.text.clone();
        buf.undo();
        assert_ne!(buf.current.text, final_text); // typing 'cd' undone
        assert_eq!(buf.current.text, "  xx\n  yy\nab");
        buf.undo();
        assert_eq!(buf.current.text, "xx\nyy\nab"); // cmd undone
        buf.undo();
        assert_eq!(buf.current.text, "xx\nyy\n"); // typing 'ab' undone
    }

    // ─── H: type / Enter / type → 1 unit (plain Enter is "\n") ─────
    #[test]
    fn type_enter_type_one_unit() {
        let mut buf = Buffer::from("");
        type_str(&mut buf, "a");
        type_str(&mut buf, "b");
        enter(&mut buf);
        type_str(&mut buf, "c");
        type_str(&mut buf, "d");
        assert_eq!(buf.current.text, "ab\ncd");
        buf.undo();
        assert_eq!(buf.current.text, "");
    }

    // ─── I: backspace counts as typing ─────────────────────────────
    #[test]
    fn backspace_groups_with_typing() {
        let mut buf = Buffer::from("");
        type_str(&mut buf, "a");
        type_str(&mut buf, "b");
        backspace(&mut buf);
        type_str(&mut buf, "c");
        assert_eq!(buf.current.text, "ac");
        buf.undo();
        assert_eq!(buf.current.text, "");
    }

    // ─── J: paste (>1 grapheme insert) is its own unit ─────────────
    #[test]
    fn paste_own_unit() {
        let mut buf = Buffer::from("");
        type_str(&mut buf, "a");
        type_str(&mut buf, "b");
        // paste = single Replace with multi-grapheme text
        type_str(&mut buf, "PASTED");
        type_str(&mut buf, "c");
        type_str(&mut buf, "d");
        assert_eq!(buf.current.text, "abPASTEDcd");
        buf.undo();
        assert_eq!(buf.current.text, "abPASTED"); // 'cd' undone
        buf.undo();
        assert_eq!(buf.current.text, "ab"); // PASTE undone
        buf.undo();
        assert_eq!(buf.current.text, ""); // 'ab' undone
    }

    // ─── K: select-then-overwrite-with-1-char groups with typing ───
    #[test]
    fn select_overwrite_groups() {
        let mut buf = Buffer::from("hello");
        // simulate user selecting "ell" and typing "X" → one frame
        // with one Replace of 3-char range with 1-char text
        buf.current.selection = (Grapheme(1), Grapheme(4));
        frame(
            &mut buf,
            vec![
                Operation::Replace(Replace { range: (Grapheme(1), Grapheme(4)), text: "X".into() }),
                Operation::Select(Grapheme(2).into_range()),
            ],
        );
        type_str(&mut buf, "Y");
        assert_eq!(buf.current.text, "hXYo");
        buf.undo();
        assert_eq!(buf.current.text, "hello");
    }

    // ─── selects absorb backward, not forward — undoing the next
    //     unit doesn't drag the cursor back across the click and
    //     scroll the viewport
    #[test]
    fn click_then_edit_undoes_to_post_click_cursor() {
        let mut buf = Buffer::from("hello world");
        click(&mut buf, 6); // cursor between "hello " and "world"
        type_str(&mut buf, "X");
        assert_eq!(buf.current.text, "hello Xworld");
        buf.undo();
        assert_eq!(buf.current.text, "hello world");
        // Cursor stays at the click position, not at wherever the
        // buffer's initial cursor was before the click.
        assert_eq!(buf.current.selection, (Grapheme(6), Grapheme(6)));
    }

    // ─── round-trip repro: shift-tab then tab undoes as 2 units ────
    #[test]
    fn round_trip_two_units() {
        let mut buf = Buffer::from("  foo\n  bar\n");
        click(&mut buf, 2);
        cmd_deindent_lines(&mut buf, &[0, 6]);
        let mid = buf.current.text.clone();
        assert_eq!(mid, "foo\nbar\n");
        cmd_indent_lines(&mut buf, &[0, 4]);
        assert_eq!(buf.current.text, "  foo\n  bar\n");
        buf.undo();
        assert_eq!(buf.current.text, mid); // tab reverted
        buf.undo();
        assert_eq!(buf.current.text, "  foo\n  bar\n"); // shift-tab reverted
    }
}

#[cfg(test)]
mod reload_tests {
    //! Remote versions arriving through `reload` around local edits and
    //! undo. Undo never reverts an external version and stops at the last one,
    //! and a reload lands where the other device put it.

    use super::Buffer;
    use crate::model::text::offset_types::Grapheme;
    use crate::model::text::operation_types::{Operation, Replace};
    use std::time::Duration;

    fn edit(buf: &mut Buffer, (start, end): (usize, usize), text: &str) {
        let range = (Grapheme(start), Grapheme(end));
        buf.queue(vec![Operation::Replace(Replace { range, text: text.into() })], Duration::ZERO);
        buf.update();
    }

    fn reload(buf: &mut Buffer, text: &str) {
        buf.reload(text.into());
        buf.update();
    }

    #[test]
    fn undo_stops_at_an_external_edit() {
        let mut buf = Buffer::from("aa bb cc");
        edit(&mut buf, (0, 0), "x ");
        reload(&mut buf, "aa bb cc R");
        assert!(!buf.can_undo());
        buf.undo();
        assert_eq!(buf.current.text, "x aa bb cc R");
    }

    #[test]
    fn undo_stops_at_an_external_edit_before_a_click() {
        let mut buf = Buffer::from("aa bb");
        edit(&mut buf, (0, 0), "x ");
        reload(&mut buf, "aa bb R");
        buf.queue(vec![Operation::Select((Grapheme(1), Grapheme(1)))], Duration::ZERO);
        buf.update();
        assert!(!buf.can_undo());
    }

    #[test]
    fn undo_after_typing_and_an_external_edit() {
        let mut buf = Buffer::from("aa bb");
        for (i, c) in ["x", "y", "z"].into_iter().enumerate() {
            edit(&mut buf, (i, i), c);
        }
        reload(&mut buf, "aa bb R");
        buf.undo();
        assert_eq!(buf.current.text, "xyzaa bb R");
    }

    #[test]
    fn a_reload_merges_onto_the_one_before_it() {
        let mut buf = Buffer::from("a");
        buf.reload("aR".into());
        buf.reload("a".into());
        buf.update();
        assert_eq!(buf.current.text, "a");
    }

    #[test]
    fn second_reload_over_unsaved_edits_lands_where_it_was_put() {
        let mut buf = Buffer::from("aa bb cc dd");
        edit(&mut buf, (0, 3), "");
        reload(&mut buf, "aa bb cc dd R");
        reload(&mut buf, "aa bb S cc dd R");
        assert_eq!(buf.current.text, "bb S cc dd R");
    }

    #[test]
    fn a_reload_lands_beside_a_move() {
        let image = "![a](https://x.test/a.png)";
        let disk = format!("{image}\n\nab\n\nfoo\n");
        let mut buf = Buffer::from(disk.as_str());
        let end = Grapheme(image.len() + 9);
        buf.queue(
            vec![
                Operation::Replace(Replace {
                    range: (Grapheme(0), Grapheme(image.len())),
                    text: "".into(),
                }),
                Operation::Replace(Replace { range: (end, end), text: image.into() }),
            ],
            Duration::ZERO,
        );
        buf.update();
        let disk = disk.replace("ab", "a⟦1⟧b");
        reload(&mut buf, &disk);
        assert_eq!(buf.current.text, format!("\n\na⟦1⟧b\n\nfoo{image}\n"));
        reload(&mut buf, &disk.replace("foo", "fo⟦2⟧o"));
        assert_eq!(buf.current.text, format!("\n\na⟦1⟧b\n\nfo⟦2⟧o{image}\n"));
    }

    #[test]
    fn reloads_beside_a_local_delete() {
        let mut buf = Buffer::from("aa bb cc dd");
        edit(&mut buf, (3, 6), "");
        reload(&mut buf, "aa R bb cc dd");
        assert_eq!(buf.current.text, "aa R cc dd");
        reload(&mut buf, "aa R bb cc dd S");
        assert_eq!(buf.current.text, "aa R cc dd S");
    }

    #[test]
    fn a_reload_after_typing_taken_back() {
        let mut buf = Buffer::from("aa bbb cc");
        edit(&mut buf, (4, 4), "x");
        buf.undo();
        reload(&mut buf, "aa BBB cc");
        assert_eq!(buf.current.text, "aa BBB cc");

        let mut buf = Buffer::from("aa bbb cc");
        edit(&mut buf, (4, 4), "x");
        edit(&mut buf, (4, 5), "");
        reload(&mut buf, "aa BBB cc");
        assert_eq!(buf.current.text, "aa BBB cc");
    }

    #[test]
    fn a_reload_after_undoing_a_saved_edit() {
        let mut buf = Buffer::from("aa bb");
        edit(&mut buf, (0, 0), "x ");
        buf.flush();
        buf.saved(buf.current.text.clone());
        edit(&mut buf, (7, 7), " y");
        buf.undo();
        buf.undo();
        reload(&mut buf, "x aa R bb");
        assert_eq!(buf.current.text, "aa R bb");
    }

    #[test]
    fn a_save_records_after_a_reload_lands_during_it() {
        let mut buf = Buffer::from("a c");
        edit(&mut buf, (0, 3), "a X c Y");
        buf.flush();
        let written = buf.current.text.clone();
        edit(&mut buf, (7, 7), " Z");
        reload(&mut buf, "a c");
        buf.saved(written);
        reload(&mut buf, "R a X c Y");
        assert_eq!(buf.current.text, "R a X c Y Z");
    }

    #[test]
    fn a_save_refused_for_a_newer_version_keeps_its_undone_edit_undone() {
        let mut buf = Buffer::from("aa bb cc");
        edit(&mut buf, (3, 5), "XX");
        buf.flush();
        buf.undo();
        reload(&mut buf, "aa RR cc");
        assert_eq!(buf.current.text, "aa RR cc");
    }

    #[test]
    fn a_reload_keeps_another_edit_where_a_mark_typed_over_a_selection_was_undone() {
        let mut buf = Buffer::from("ab cd ef");
        edit(&mut buf, (3, 5), "\u{948}");
        assert_eq!(buf.current.text, "ab \u{948} ef");
        buf.undo();
        assert_eq!(buf.current.text, "ab cd ef");
        reload(&mut buf, "ab cX ef");
        assert_eq!(buf.current.text, "ab cX ef");
    }

    #[test]
    fn reload_after_an_undo_at_a_reload() {
        let mut buf = Buffer::from("aa bb cc");
        reload(&mut buf, "aa bb cc R");
        buf.undo();
        reload(&mut buf, "aa bb cc R S");
        assert_eq!(buf.current.text, "aa bb cc R S");
    }

    #[test]
    fn undo_and_redo_after_an_external_edit_round_trip() {
        let mut buf = Buffer::from("aa bb cc");
        edit(&mut buf, (0, 0), "x ");
        reload(&mut buf, "aa bb R cc");
        edit(&mut buf, (12, 12), " y");
        let edited = buf.current.text.clone();
        assert_eq!(edited, "x aa bb R cc y");

        buf.undo();
        assert_eq!(buf.current.text, "x aa bb R cc");
        assert!(!buf.can_undo());
        buf.redo();
        assert_eq!(buf.current.text, edited);
    }
}