text-document 1.16.0

Rich text document editing library
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
//! Transient edits: changes to the document that no undo history records.
//!
//! An input method's composition (the candidates of a Chinese or Japanese input method, the
//! Korean syllable being built, the live text of dictation) has to be shown in the text,
//! where the writer is looking, and has to be replaced at every update. Made as ordinary
//! edits, every update was recorded, and once the composition was committed an undo
//! replayed each state it went through. A transient edit changes the document and is
//! announced as a change of its content is ([`DocumentEvent::ContentsChanged`], and the
//! block and flow events when they apply), so views lay it out and draw it, but it is not
//! recorded: the undo and redo histories stay as they were, and so does the coalescing of
//! typing. Nothing arrives yet, so there is no [`DocumentEvent::TextInserted`].
//!
//! The edits are [`TextCursor::insert_text_transient`],
//! [`TextCursor::insert_text_transient_merged`],
//! [`TextCursor::insert_formatted_text_transient`] and
//! [`TextCursor::remove_selected_text_transient`].
//!
//! # The layer
//!
//! The outstanding transient edits are one **layer** over the document as it is recorded.
//! The layer belongs to the document, whichever cursor made its edits. It begins with the
//! first transient edit and ends when it is reverted, which puts the recorded content back
//! as it was before that first edit: the same text, formats and block identities, which is
//! what every recorded undo entry refers to. Nothing is recorded and the histories are
//! untouched.
//!
//! The layer ends in one of three ways:
//!
//! * [`TextDocument::revert_transient_edits`]: the composition is cancelled.
//! * [`TextCursor::commit_transient_text`]: the composition is committed. The layer is
//!   reverted, and the text it changed is replaced with the committed text, recorded as
//!   **one undo step of its own**, closed on both sides: it does not coalesce with the
//!   typing before it, and the typing after it starts a step of its own, so an undo takes
//!   back exactly the committed text and gives back what the composition took the place
//!   of. Inside an open edit block ([`TextCursor::begin_edit_block`]) the commit joins the
//!   block, as every recorded edit there does.
//! * Any recorded write to the document, by any cursor or clone of the document. Every edit,
//!   undo, redo and load reverts the layer before anything else, its own checks included,
//!   then acts on the recorded content, so the layer is gone even when the write then fails
//!   or changes nothing. The streaming appends alone check their lines first, and leave the
//!   layer when they refuse them.
//!
//! So a host never keeps its own record of where its composition is: before each update it
//! asks [`TextDocument::transient_range`], which is `None` once anything has reverted it.
//!
//! The history's operations that change no content do not end the layer:
//! [`TextDocument::clear_undo_redo`], [`TextDocument::break_undo_merge`] and an edit block
//! leave it outstanding. Nor does [`TextDocument::set_footnote_markers`]: the markers are
//! the host's, not content, and a revert keeps them.
//!
//! # Positions
//!
//! A revert puts every cursor back in the recorded text. One that only the transient edits
//! moved goes back exactly where it stood, the table cells or the whole text it selected
//! included. Any other (one that something else moved
//! meanwhile, one made since) is moved back across each transient edit in turn, from the
//! last, an edit that touches the text the one before it made counting with it as one (a
//! syllable taken out and its candidate shown in its place are one replacement): a position
//! before the edit stays, and one after the text it inserted moves by the difference. One inside that text, or at its end, goes to the end of the recorded text
//! the edit replaced, and one at its start to that text's start, except where the edit only
//! removed text: there a selection's start, or a caret, goes after the text put back, and
//! its end before it. So a selection holds the recorded text it held, and one that held
//! only text a transient edit inserted over nothing comes back empty.
//!
//! The recorded writes read a cursor after their revert, so they act where it stands in the
//! recorded text. The explicit ranges of [`TextCursor::replace`] and
//! [`TextDocument::replace_ranges`] are read in the document as it was, with the layer, and
//! moved back the same way, under the lock the write itself takes.
//!
//! # Reading
//!
//! While the layer is outstanding, the document reads as it shows: the text, the flow, a
//! search, an export. A host that saves on a timer saves the composition with the rest, and
//! should revert or commit first when that matters (see
//! [`TextDocument::has_transient_edits`]).
//!
//! A view that is not where the transient edits are made (a read-only preview beside the
//! editor an input method composes in) shows the recorded document instead:
//! [`TextDocument::snapshot_recorded_flow_masked`], its `_no_paint` twin and
//! [`TextDocument::snapshot_recorded_block_at_position_masked`] snapshot it as a revert
//! would leave it. Its positions are the recorded document's: such a view draws a cursor at
//! [`TextCursor::recorded_position`] and [`TextCursor::recorded_anchor`], where a revert
//! puts it, places any other position of the document with
//! [`TextDocument::recorded_position`], and maps a position read off its own layout into
//! the document with [`TextDocument::position_from_recorded`]. A view that shows only the
//! transient edits it made itself tells its layer from another with
//! [`TextDocument::transient_layer`].
//!
//! # Under a host's lock
//!
//! An input method that edits under a lock of its own (Windows' Text Services Framework
//! grants one, and reads back what it wrote under the same lock) must not see application
//! code write the document while it holds the lock: a recorded write by a change callback
//! would revert the layer, and the input method would read back text other than the text it
//! wrote. The host holds the document's events for the lock's duration
//! ([`TextDocument::hold_events`]). Under the hold, the transient edits, their revert, their
//! commit and every other edit change the document and move its cursors at once, and every
//! read ([`TextDocument::transient_range`], the text, a cursor's position) sees them; only
//! their events wait, and go out in the order they were queued when the hold is dropped,
//! after the lock. A callback that then writes the document reverts or ends the layer as
//! any recorded write does, outside the lock.
//!
//! # Refusals
//!
//! What the layer cannot do is refused with [`DocumentError::TransientEdits`], whose
//! [`TransientRefusal`](crate::TransientRefusal) says which case it is. Underneath, the
//! document's store enforces what the layer needs of it, whoever calls it:
//!
//! * while a layer is outstanding, it refuses to begin any write that is not a transient
//!   edit's own (a write transaction, a streaming append), so that no recorded edit lands
//!   over the layer and is then taken away by the revert. Every write this crate offers
//!   reverts the layer first, so that refusal reaches a caller only when a transient edit
//!   is made from another thread between the revert and the write
//!   ([`TransientRefusal::LayerOutstanding`](crate::TransientRefusal::LayerOutstanding));
//! * it refuses to begin a transient write while any other write is open, a transient one
//!   included, since the first one's snapshot is the recorded content
//!   ([`TransientRefusal::WriteInProgress`](crate::TransientRefusal::WriteInProgress));
//! * it refuses a revert while a transient write is in progress, which the document's lock
//!   rules out here.

use std::ops::Range;
use std::sync::{Arc, Weak};

use parking_lot::Mutex;

use frontend::commands::undo_redo_commands;

use crate::cursor::{Recording, TextCursor};
use crate::document::TextDocument;
use crate::events::{DocumentEvent, InsertionOrigin};
use crate::inner::{CursorData, QueuedEvents, TextDocumentInner, adjust_offset};
use crate::{DocumentError, ReplaceFormatPolicy, Result, TextFormat};

/// One change a transient edit made to the document's positions: from `at`, `removed`
/// positions replaced by `added`, in the positions the document had at the time.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct Splice {
    pub at: usize,
    pub removed: usize,
    pub added: usize,
}

impl Splice {
    /// This change followed by `next`, as one change, when `next` touches what this one
    /// made (`[at, at + added]`, either edge included). `None` when it is elsewhere.
    ///
    /// Across one change, a position inside what it made goes to the end of what it
    /// replaced, and one at its start to its start. Across two that touch, which is what an
    /// input method makes when it takes a syllable out and then shows its candidate in its
    /// place, the edges cross: the candidate's start goes after the syllable (where text
    /// was only removed) and its end before it, so a range over the candidate held nothing.
    /// Composed, they are the one replacement the writer sees.
    fn then(self, next: Splice) -> Option<Splice> {
        let made_end = self.at + self.added;
        if next.at > made_end || next.at + next.removed < self.at {
            return None;
        }
        // What `next` removed before what this change made, after it, and inside it.
        let before = self.at.saturating_sub(next.at);
        let after = (next.at + next.removed).saturating_sub(made_end);
        let inside = next.removed.saturating_sub(before + after);
        Some(Splice {
            at: self.at.min(next.at),
            removed: before + self.removed + after,
            added: self.added.saturating_sub(inside) + next.added,
        })
    }
}

/// The part of the document the outstanding transient edits changed: outside it, the
/// document is as recorded.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Span {
    /// Where it starts, the same position in the document as it is and as recorded.
    start: usize,
    /// Where it ends in the document as it is.
    end: usize,
    /// Where it ends in the document as recorded.
    recorded_end: usize,
}

/// Where a cursor stands: what a revert gives back to it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Stand {
    position: usize,
    anchor: usize,
    anchor_in_table: Option<usize>,
}

impl Stand {
    fn of(data: &CursorData) -> Self {
        Stand {
            position: data.position,
            anchor: data.anchor,
            anchor_in_table: data.anchor_in_table,
        }
    }

    /// Moved as an edit moves every cursor (see `TextDocumentInner::adjust_cursors`).
    fn adjusted(self, at: usize, removed: usize, added: usize) -> Self {
        Stand {
            position: adjust_offset(self.position, at, removed, added),
            anchor: adjust_offset(self.anchor, at, removed, added),
            anchor_in_table: self
                .anchor_in_table
                .map(|origin| adjust_offset(origin, at, removed, added)),
        }
    }

    /// Moved back across `splices`: a selection's two ends inwards (see [`RangeEnd`]), so
    /// it holds the same recorded text, a caret as a range's start.
    fn mapped_back(self, splices: &[Splice]) -> Self {
        let (low, high) = if self.position <= self.anchor {
            (&self.position, &self.anchor)
        } else {
            (&self.anchor, &self.position)
        };
        let low_back = map_back_through(splices, *low, RangeEnd::Start);
        let high_back = if high == low {
            low_back
        } else {
            map_back_through(splices, *high, RangeEnd::End)
        };
        let (position, anchor) = if self.position <= self.anchor {
            (low_back, high_back)
        } else {
            (high_back, low_back)
        };
        Stand {
            position,
            anchor,
            anchor_in_table: self
                .anchor_in_table
                .map(|origin| map_back_through(splices, origin, RangeEnd::Start)),
        }
    }
}

/// A cursor alive when the layer began: where it stood then, and where the transient edits
/// alone have taken it since.
///
/// A cursor that is still where they took it was moved by nothing else, and a revert puts
/// it back exactly where it stood. Only a cursor something else moved meanwhile (the one
/// making the edits, one the writer clicked elsewhere) has to be mapped back through the
/// changes, which cannot always tell where text came back: a caret where text was removed
/// stood before it or inside it, and the two look the same.
#[derive(Debug)]
struct Rider {
    cursor: Weak<Mutex<CursorData>>,
    stood: Stand,
    expected: Stand,
    /// What its selection was besides its ends, which every edit, a transient one included,
    /// clears on every cursor (see `TextDocumentInner::adjust_cursors`): a revert that puts
    /// it back where it stood puts these back too, the text being the one they were of.
    cells: Option<crate::flow::CellRange>,
    whole_text: bool,
}

/// Which end of a range a position is, read with transient edits in place. It matters only
/// where an edit removed text and inserted none: there a revert puts text back at that very
/// position, and this says which side of it the position goes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum RangeEnd {
    /// A range's start, or a caret: after the text put back, before what followed it.
    Start,
    /// A range's end: before the text put back, after what preceded it.
    End,
}

/// `position` moved back across one transient change: the inverse of what it did.
fn unsplice(position: usize, splice: Splice, end: RangeEnd) -> usize {
    // The change replaced `removed` positions from `at` with `added`; back across it,
    // `added` positions from `at` become `removed` again.
    let Splice { at, removed, added } = splice;
    if position < at {
        position
    } else if position == at {
        // Text only removed, and put back here: a range starting here starts at what
        // followed the text, as it did before the removal.
        if added == 0 && end == RangeEnd::Start {
            at + removed
        } else {
            at
        }
    } else if position <= at + added {
        at + removed
    } else {
        position - added + removed
    }
}

/// `position` moved back across `splices`, the changes made, in order.
fn map_back_through(splices: &[Splice], position: usize, end: RangeEnd) -> usize {
    splices
        .iter()
        .rev()
        .fold(position, |p, splice| unsplice(p, *splice, end))
}

/// Which layer of transient edits a document holds (see
/// [`TextDocument::transient_layer`]): the same for as long as they are outstanding, and
/// another once they have ended and new ones begin, in this document or any other.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct TransientLayerId(u64);

impl TransientLayerId {
    /// A layer no other has been or will be, in this process.
    fn next() -> Self {
        static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
        TransientLayerId(NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed))
    }
}

/// The outstanding transient edits (see the module documentation).
#[derive(Debug)]
pub(crate) struct TransientLayer {
    /// Which layer this is, for a view that has to tell its own from another's.
    id: TransientLayerId,
    /// Every change of positions the layer made, in order, as each edit made it: what a
    /// panicking edit announces, and how an edit is seen to have changed anything.
    steps: Vec<Splice>,
    /// The same changes, each composed with the one before it when they touch (see
    /// [`Splice::then`]): what a revert maps the cursors back through, and every mapping
    /// of a position between the document as it is and as recorded.
    splices: Vec<Splice>,
    span: Option<Span>,
    /// Whether one of the edits changed the document away from the span the earlier ones
    /// had changed, so that the span holds recorded text between them.
    scattered: bool,
    riders: Vec<Rider>,
}

impl TransientLayer {
    /// A layer beginning while `cursors` are alive, each of which a revert gives back where
    /// it stands now unless something other than the transient edits moves it.
    pub(crate) fn over(cursors: &[Weak<Mutex<CursorData>>]) -> Self {
        let riders = cursors
            .iter()
            .filter_map(|weak| {
                let cursor = weak.upgrade()?;
                let data = cursor.lock();
                let stood = Stand::of(&data);
                Some(Rider {
                    cursor: weak.clone(),
                    stood,
                    expected: stood,
                    cells: data.cell_selection_override.clone(),
                    whole_text: data.whole_text_selected,
                })
            })
            .collect();
        TransientLayer {
            id: TransientLayerId::next(),
            steps: Vec::new(),
            splices: Vec::new(),
            span: None,
            scattered: false,
            riders,
        }
    }

    /// A transient edit replaced `removed` positions from `at` with `added`.
    ///
    /// Called from `TextDocumentInner::adjust_cursors`, which every edit goes through to
    /// move the cursors: while a layer is outstanding, every edit is a transient one.
    pub(crate) fn record(&mut self, at: usize, removed: usize, added: usize) {
        if removed == 0 && added == 0 {
            return;
        }
        let splice = Splice { at, removed, added };
        self.steps.push(splice);
        match self.splices.last().and_then(|last| last.then(splice)) {
            Some(composed) => *self.splices.last_mut().expect("there is a last") = composed,
            None => self.splices.push(splice),
        }
        for rider in &mut self.riders {
            rider.expected = rider.expected.adjusted(at, removed, added);
        }
        self.span = Some(match self.span {
            None => Span {
                start: at,
                end: at + added,
                recorded_end: at + removed,
            },
            Some(span) => {
                if at > span.end || at + removed < span.start {
                    self.scattered = true;
                }
                let start = span.start.min(at);
                let end_before = span.end.max(at + removed);
                // The recorded text the span now covers: what it covered, and the unchanged
                // positions it grew over on either side.
                let recorded_len = (span.recorded_end - span.start)
                    + (span.start - start)
                    + (end_before - span.end);
                Span {
                    start,
                    end: end_before - removed + added,
                    recorded_end: start + recorded_len,
                }
            }
        });
    }

    /// Where a revert puts `cursor`, which stands at `now`: where it stood when the layer
    /// began if only the transient edits moved it, else `now` moved back across them.
    fn stand_after_revert(&self, cursor: &Weak<Mutex<CursorData>>, now: Stand) -> Stand {
        match self.carried(cursor, now) {
            Some(rider) => rider.stood,
            None => now.mapped_back(&self.splices),
        }
    }

    /// `cursor`'s rider, when the cursor stands at `now` and only the transient edits moved
    /// it there: one a revert puts back exactly as it was.
    fn carried(&self, cursor: &Weak<Mutex<CursorData>>, now: Stand) -> Option<&Rider> {
        self.riders
            .iter()
            .find(|rider| Weak::ptr_eq(&rider.cursor, cursor) && rider.expected == now)
    }

    /// The range `[start, end)`, read in the document as it shows, in the recorded document,
    /// as [`Reverted::map_range`] moves it back once the layer is reverted.
    pub(crate) fn map_range_back(&self, start: usize, end: usize) -> (usize, usize) {
        map_range_through(&self.splices, start, end)
    }

    /// [`map_forward`](Self::map_forward), for a reader of the recorded document that has to
    /// find where one of its positions shows.
    pub(crate) fn map_position_forward(&self, recorded: usize) -> usize {
        self.map_forward(recorded)
    }

    /// `recorded`, a position in the document as recorded, in the document as it is: moved
    /// across every change the layer made, as each moved every cursor.
    fn map_forward(&self, recorded: usize) -> usize {
        self.splices.iter().fold(recorded, |position, splice| {
            adjust_offset(position, splice.at, splice.removed, splice.added)
        })
    }
}

/// The transient edits a revert took away: how to map a position read in the document as
/// it was, with them, into the document as it is now.
#[derive(Debug, Default)]
pub(crate) struct Reverted {
    splices: Vec<Splice>,
}

impl Reverted {
    /// The range `[start, end)` (either order), read with the transient edits in place, in
    /// the recorded document: its start moved back as a start, its end as an end, so that it
    /// holds the recorded text it held. A range that held only transient text can come back
    /// empty.
    pub(crate) fn map_range(&self, start: usize, end: usize) -> (usize, usize) {
        map_range_through(&self.splices, start, end)
    }
}

/// [`Reverted::map_range`] across `splices`.
fn map_range_through(splices: &[Splice], start: usize, end: usize) -> (usize, usize) {
    let (low, high) = (start.min(end), start.max(end));
    if low == high {
        let at = map_back_through(splices, low, RangeEnd::Start);
        return (at, at);
    }
    let low = map_back_through(splices, low, RangeEnd::Start);
    let high = map_back_through(splices, high, RangeEnd::End);
    (low, high.max(low))
}

/// [`Reverted::map_range`] of an optional revert: the range, ordered, when there was none.
pub(crate) fn map_range_back(
    reverted: &Option<Reverted>,
    start: usize,
    end: usize,
) -> (usize, usize) {
    match reverted {
        Some(reverted) => reverted.map_range(start, end),
        None => (start.min(end), start.max(end)),
    }
}

/// What [`settle`] did before a recorded write: the transient edits it reverted, if any,
/// with the events that announce it still queued.
///
/// The events go out with the write's own, in order, when the write dispatches them: no
/// callback runs between the revert and the write. A callback that wrote then, from the
/// revert's own announcement, would write before the write it made way for: an undo would
/// have taken back the callback's edit instead of the writer's, and a callback putting a
/// composition back would have had the write refused. Whatever is still queued when this
/// is dropped (a write that returned before dispatching anything, or failed) goes out then,
/// so it is held until the write has run and the document is unlocked.
#[must_use = "hold it until the write has run: the revert's events go out with the write's"]
pub(crate) struct Settled {
    /// The document, when a revert happened and its events are still to go out.
    doc: Option<Arc<Mutex<TextDocumentInner>>>,
}

impl Drop for Settled {
    fn drop(&mut self) {
        if let Some(doc) = self.doc.take() {
            let queued = doc.lock().take_queued_events();
            crate::inner::dispatch_queued_events(queued);
        }
    }
}

impl TextDocumentInner {
    /// Revert the outstanding transient edits: the store back to the recorded content, every
    /// cursor mapped back, the change announced. `None` when there were none.
    ///
    /// The events are queued, not dispatched: the caller dispatches them with its own.
    pub(crate) fn revert_transient_edits(&mut self) -> Option<Reverted> {
        let layer = self.transient.take()?;
        // The store refuses a revert only inside a transient write or over an open write.
        // This document's transient writes hold its lock as this does, its recorded writes
        // end before they let it go, and the one write that outlives a call, a load in
        // place, is never open with a layer: it cannot happen, and if it did, the layer and
        // the store are left as they are, in step.
        let Ok(reverted) = self.ctx.db_context.get_store().revert_transient_edits() else {
            self.transient = Some(layer);
            debug_assert!(
                false,
                "the store refused a revert under the document's lock"
            );
            return None;
        };
        debug_assert!(
            reverted || layer.steps.is_empty(),
            "the document held transient edits that its store did not"
        );
        self.prune_dead_cursors();
        for weak in &self.cursors {
            let Some(cursor) = weak.upgrade() else {
                continue;
            };
            let mut data = cursor.lock();
            let now = Stand::of(&data);
            let back = layer.stand_after_revert(weak, now);
            data.position = back.position;
            data.anchor = back.anchor;
            data.anchor_in_table = back.anchor_in_table;
            // A cursor put back as it was gets back the cells or the whole text it selected;
            // any other selection is a new one, of positions alone.
            let carried = layer.carried(weak, now);
            data.cell_selection_override = carried.and_then(|rider| rider.cells.clone());
            data.whole_text_selected = carried.is_some_and(|rider| rider.whole_text);
        }
        self.invalidate_text_cache();
        if let Some(span) = layer.span {
            let blocks_affected = self.blocks_between(span.start, span.recorded_end);
            if blocks_affected > 1 {
                self.rehighlight_all();
            } else {
                self.rehighlight_affected(span.start);
            }
            self.queue_event(DocumentEvent::ContentsChanged {
                position: span.start,
                chars_removed: span.end - span.start,
                chars_added: span.recorded_end - span.start,
                blocks_affected,
            });
        }
        self.check_block_count_changed();
        self.check_flow_changed();
        Some(Reverted {
            splices: layer.splices,
        })
    }

    /// How many blocks `[start, end)` touches, at least one.
    ///
    /// Its last position is `end - 1`: the block at `end` itself starts after a separator
    /// the range ends before, which a block lookup counts as that next block's.
    fn blocks_between(&self, start: usize, end: usize) -> usize {
        let number = |position: usize| {
            frontend::commands::document_inspection_commands::get_block_at_position(
                &self.ctx,
                &frontend::document_inspection::GetBlockAtPositionDto {
                    position: position as i64,
                },
            )
            .ok()
            .map(|info| info.block_number)
        };
        match (number(start), number(end.saturating_sub(1).max(start))) {
            (Some(first), Some(last)) if last > first => (last - first) as usize + 1,
            _ => 1,
        }
    }

    /// After a panic inside a transient edit that had made its change: announce the change,
    /// unless the edit had already, and what it did to the paragraphs and the flow. A panic
    /// in a syntax highlighter comes before the edit announces anything, and the document
    /// would show text no listener had heard of.
    fn announce_kept_changes(&mut self, changes_before: usize, events_before: usize) {
        let announced = self
            .pending_events
            .get(events_before..)
            .is_some_and(|events| {
                events
                    .iter()
                    .any(|event| matches!(event, DocumentEvent::ContentsChanged { .. }))
            });
        let kept: Vec<Splice> = self
            .transient
            .as_ref()
            .map(|layer| layer.steps[changes_before..].to_vec())
            .unwrap_or_default();
        self.invalidate_text_cache();
        if !announced {
            for splice in &kept {
                let blocks_affected = self.blocks_between(splice.at, splice.at + splice.added);
                self.queue_event(DocumentEvent::ContentsChanged {
                    position: splice.at,
                    chars_removed: splice.removed,
                    chars_added: splice.added,
                    blocks_affected,
                });
            }
        }
        if !kept.is_empty() {
            self.check_block_count_changed();
            self.check_flow_changed();
        }
    }

    /// Run `read` over the document as recorded: as it is when no transient edits are
    /// outstanding, and otherwise over a store of its own holding the content a revert would
    /// put back (`RopeStore::recorded_snapshot`), which nothing else sees.
    ///
    /// Only the context `read` is handed changes, for as long as it runs: the document's own
    /// store, which an export running on another thread may be reading, keeps the transient
    /// edits. `read` must only read through the context, as the snapshot builders do: the
    /// caches beside it (the plain text, the highlights) were made from the document as it
    /// is. The one of them a snapshot reads by position, a host's highlight ranges, is moved
    /// back across the transient edits where it is sliced to a block (see
    /// [`recorded_reading`](Self::recorded_reading)).
    pub(crate) fn read_recorded<R>(&mut self, read: impl FnOnce(&TextDocumentInner) -> R) -> R {
        let recorded = self
            .transient
            .as_ref()
            .and_then(|_| self.ctx.db_context.get_store().recorded_snapshot());
        let Some(recorded) = recorded else {
            return read(self);
        };
        let mut ctx = self.ctx.clone();
        ctx.db_context =
            common::database::db_context::DbContext::new().expect("an empty store is always made");
        ctx.db_context.get_store().restore(&recorded);
        let live = std::mem::replace(&mut self.ctx, ctx);
        self.reading_recorded = true;
        // Puts the document's own context back however `read` ends, a panic included: left
        // in place, the recorded one would take the document's next writes.
        struct Restore<'a> {
            inner: &'a mut TextDocumentInner,
            live: Option<frontend::AppContext>,
        }
        impl Drop for Restore<'_> {
            fn drop(&mut self) {
                if let Some(live) = self.live.take() {
                    self.inner.ctx = live;
                }
                self.inner.reading_recorded = false;
            }
        }
        let restore = Restore {
            inner: self,
            live: Some(live),
        };
        read(restore.inner)
    }

    /// The outstanding transient edits, while the document is read as recorded (inside
    /// [`read_recorded`](Self::read_recorded)): what a position of the document as it shows,
    /// kept beside the store, is moved back across. `None` otherwise.
    pub(crate) fn recorded_reading(&self) -> Option<&TransientLayer> {
        self.transient.as_ref().filter(|_| self.reading_recorded)
    }

    /// Whether a load in place this document started is still writing its content.
    fn is_loading_in_place(&self) -> bool {
        if self.history_resets.is_empty() {
            return false;
        }
        let operations = self.ctx.long_operation_manager.lock();
        self.history_resets
            .keys()
            .any(|id| operations.is_operation_finished(id) == Some(false))
    }
}

/// Revert `doc`'s outstanding transient edits, if any, before a recorded write.
///
/// What a recorded edit calls first, before it reads a cursor, so that it acts on the
/// recorded text at the cursor's place in it. Hold what it returns until the write has run
/// (see [`Settled`]).
pub(crate) fn settle(doc: &Arc<Mutex<TextDocumentInner>>) -> Settled {
    let reverted = doc.lock().revert_transient_edits().is_some();
    Settled {
        doc: reverted.then(|| Arc::clone(doc)),
    }
}

impl TextCursor {
    /// Revert the document's outstanding transient edits before an edit reads this cursor
    /// (see [`settle`]).
    pub(crate) fn settle_transient_edits(&self) -> Settled {
        settle(&self.doc)
    }

    /// Run `edit` as a transient edit, written to the store inside a transient write.
    ///
    /// The write is kept when the edit changed the document's positions, which it logs into
    /// the layer as it moves the cursors (see `TransientLayer::record`), and undone when it
    /// did not: the store then goes back to where the edit found it, and the layer is let go
    /// when the edit opened it. So the store and the layer stay in step whatever happens:
    /// an error before the change was made (a refused selection, a failed half of a
    /// replacement) leaves the document as it was, and so does a panic there; a panic after
    /// it (in a syntax highlighter, which runs after the cursors move) keeps the change, as
    /// a transient edit the layer holds and a revert takes away.
    fn edit_transiently<R>(
        &self,
        edit: impl FnOnce(&mut TextDocumentInner) -> Result<(R, QueuedEvents)>,
    ) -> Result<R> {
        let (value, queued) = {
            let mut inner = self.doc.lock();
            if inner.is_loading_in_place() {
                return Err(DocumentError::TransientEdits(
                    crate::TransientRefusal::LoadInPlace,
                ));
            }
            let store = Arc::clone(inner.ctx.db_context.get_store());
            let write = store
                .begin_transient_write()
                .map_err(|refused| DocumentError::TransientEdits(refused.into()))?;
            let opened = write.opens();
            if opened {
                let layer = TransientLayer::over(&inner.cursors);
                inner.transient = Some(layer);
            }
            let changes =
                |inner: &TextDocumentInner| inner.transient.as_ref().map_or(0, |l| l.steps.len());
            let changes_before = changes(&inner);
            let events_before = inner.pending_events.len();
            let outcome =
                std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| edit(&mut inner)));
            if changes(&inner) > changes_before {
                write.keep();
                if outcome.is_err() {
                    inner.announce_kept_changes(changes_before, events_before);
                }
            } else {
                drop(write);
                if opened {
                    inner.transient = None;
                }
                inner.invalidate_text_cache();
            }
            match outcome {
                Ok(Ok(done)) => done,
                Ok(Err(error)) => return Err(error),
                Err(panic) => {
                    // The change the edit kept goes out now, to the callbacks as well as to
                    // `poll_events`: the host may catch the panic and edit nothing more. A
                    // callback's own panic is dropped, so the edit's is the one resumed.
                    let queued = inner.take_queued_events();
                    drop(inner);
                    let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                        crate::inner::dispatch_queued_events(queued)
                    }));
                    std::panic::resume_unwind(panic);
                }
            }
        };
        crate::inner::dispatch_queued_events(queued);
        Ok(value)
    }

    /// Insert plain text at the cursor, replacing the selection if any, **without recording
    /// it** in the undo history.
    ///
    /// For an input method's composition, shown in the text while it is being made, or any
    /// tentative text a host shows and then either commits or takes back. The text goes in
    /// as [`insert_text`](Self::insert_text) puts it, with the format of the text before it,
    /// and the cursor is left after it. The document announces the change as it does every
    /// edit ([`DocumentEvent::ContentsChanged`], and the block and flow events when they
    /// apply), so views lay it out and draw it; it announces no
    /// [`DocumentEvent::TextInserted`], since nothing has arrived yet, no
    /// [`DocumentEvent::UndoRedoChanged`], since the history has not moved, and leaves
    /// [`is_modified`](crate::TextDocument::is_modified) as it was.
    ///
    /// Nothing is pushed on the undo stack, the redo stack is kept, and the next recorded
    /// edit coalesces with the one before the transient edits as it would have without
    /// them. To replace the text a composition showed with its next state, select it and
    /// call this again: [`TextDocument::transient_range`] says where it is.
    ///
    /// The edit joins the document's outstanding transient edits, which a revert, a commit
    /// or any recorded write ends (see the [module documentation](crate::transient)).
    ///
    /// Refused with [`DocumentError::TransientEdits`], the document left as it was, while a
    /// load in place ([`set_djot`](crate::TextDocument::set_djot) and its siblings) is still
    /// writing the document, and when the selection crosses a table's cells or holds part
    /// of a table and text outside it.
    pub fn insert_text_transient(&self, text: &str) -> Result<()> {
        self.edit_transiently(|inner| {
            let (pos, anchor) = self.read_cursor();
            let queued = self.insert_text_locked(
                inner,
                pos,
                anchor,
                text,
                ReplaceFormatPolicy::default(),
                InsertionOrigin::Unspecified,
                Recording::Transient,
            )?;
            Ok(((), queued))
        })
    }

    /// As [`insert_text_transient`](Self::insert_text_transient), with a character format,
    /// as [`insert_formatted_text`](Self::insert_formatted_text) inserts it. Refused as
    /// `insert_text_transient` is.
    pub fn insert_formatted_text_transient(&self, text: &str, format: &TextFormat) -> Result<()> {
        self.edit_transiently(|inner| {
            let (pos, anchor) = self.read_cursor();
            let queued = self.insert_formatted_text_locked(
                inner,
                pos,
                anchor,
                text,
                format,
                InsertionOrigin::Unspecified,
                Recording::Transient,
            )?;
            Ok(((), queued))
        })
    }

    /// As [`insert_text_transient`](Self::insert_text_transient), with `format` merged into
    /// the inserted text: the text takes the format it inherits, as typed text does, and
    /// every field `format` sets replaces that field of it, the others staying inherited.
    /// For a composition shown in the format the writer toggled on the caret before it
    /// (Bold with nothing selected), where
    /// [`insert_formatted_text_transient`](Self::insert_formatted_text_transient) would also
    /// set the fields left unset (the font family and size among them).
    ///
    /// One transient edit, refused as `insert_text_transient` is and reverted, committed or
    /// ended by a recorded write in the same way. The merged format is part of what the
    /// transient edits show and goes with them: a commit records the text it is given in
    /// the format it inherits, and a host that wants the format recorded merges it into the
    /// committed text in the same edit block
    /// ([`begin_edit_block`](Self::begin_edit_block)).
    pub fn insert_text_transient_merged(&self, text: &str, format: &TextFormat) -> Result<()> {
        self.edit_transiently(|inner| {
            let (pos, anchor) = self.read_cursor();
            let queued = self.insert_text_merging_locked(
                inner,
                pos,
                anchor,
                text,
                ReplaceFormatPolicy::default(),
                Some(format),
                InsertionOrigin::Unspecified,
                Recording::Transient,
            )?;
            Ok(((), queued))
        })
    }

    /// Remove the selected text **without recording it** in the undo history. Returns the
    /// removed text; nothing happens without a selection.
    ///
    /// As [`remove_selected_text`](Self::remove_selected_text) removes it, announced and
    /// refused as [`insert_text_transient`](Self::insert_text_transient) is, and recorded no
    /// more. The removed text may be recorded text: an input method that converts a
    /// committed syllable (Korean Hanja conversion, a reconversion in Japanese) takes it out
    /// transiently, shows its candidates in its place, and the commit then records the
    /// whole replacement as one step, which an undo takes back to the syllable.
    pub fn remove_selected_text_transient(&self) -> Result<String> {
        self.edit_transiently(|inner| {
            let (pos, anchor) = self.read_cursor();
            if pos == anchor {
                return Ok((String::new(), inner.take_queued_events()));
            }
            self.remove_locked(inner, pos, anchor, Recording::Transient)
        })
    }

    /// Commit the outstanding transient edits as `text`, recorded as **one undo step of its
    /// own**.
    ///
    /// The transient edits are reverted, and the text they changed in the recorded document
    /// (see [`TextDocument::transient_range`]) is replaced with `text`: after a composition
    /// inserted transiently, `text` goes in where it was shown, over the text the
    /// composition took the place of; after a transient removal of recorded text (a
    /// syllable an input method converts), it replaces that text, so an undo gives it back.
    /// The cursor is left after `text`.
    ///
    /// The step is closed on both sides, as
    /// [`break_undo_merge`](crate::TextDocument::break_undo_merge) closes one: it does not
    /// coalesce with the typing before the composition, and what is typed after it starts a
    /// step of its own, so an undo takes back exactly the committed text. Inside an open
    /// edit block, the commit joins the block instead. A replaced range within one block
    /// entirely in one format keeps it ([`ReplaceFormatPolicy::PreserveIfFullyCovered`]);
    /// inserted text, and text replacing a range across blocks, takes the format of the text
    /// before it, as typed text does.
    ///
    /// With no transient edits outstanding, `text` replaces the cursor's selection, or goes
    /// in at the cursor, as the same one closed step. An empty `text` records the removal
    /// of the recorded text the transient edits had replaced (or of the selection, with
    /// none outstanding); when there is none it records nothing and, like a cancel
    /// ([`TextDocument::revert_transient_edits`]), closes no step.
    ///
    /// On an error from the recorded half, the transient edits are reverted all the same and
    /// nothing is recorded, but the step before them is closed already: the typing on either
    /// side of the failed commit no longer coalesces.
    ///
    /// Reports [`InsertionOrigin::Unspecified`], as
    /// [`insert_text`](Self::insert_text) does. Use
    /// [`commit_transient_text_with_origin`](Self::commit_transient_text_with_origin) to say,
    /// [`InsertionOrigin::Composed`] for an input method.
    ///
    /// Refused with [`DocumentError::TransientEdits`], the transient edits left as they
    /// were, when they changed the document in more than one place: the recorded text
    /// between them would be replaced too.
    pub fn commit_transient_text(&self, text: &str) -> Result<()> {
        self.commit_transient_text_with_origin(text, InsertionOrigin::Unspecified)
    }

    /// As [`commit_transient_text`](Self::commit_transient_text), saying which channel the
    /// text came through (see [`insert_text_with_origin`](Self::insert_text_with_origin)).
    pub fn commit_transient_text_with_origin(
        &self,
        text: &str,
        origin: InsertionOrigin,
    ) -> Result<()> {
        let (result, rest) = {
            let mut inner = self.doc.lock();
            let range = match inner.transient.as_ref() {
                Some(layer) if layer.scattered => {
                    return Err(DocumentError::TransientEdits(
                        crate::TransientRefusal::CommitInSeveralPlaces,
                    ));
                }
                Some(TransientLayer {
                    span: Some(span), ..
                }) => Some((span.start, span.recorded_end)),
                _ => None,
            };
            inner.revert_transient_edits();
            // Read after the revert, which moved it back into the recorded text.
            let (start, end) = range.unwrap_or_else(|| self.read_cursor());
            // Nothing to record is a cancel, which closes no step: the typing on either side
            // coalesces as it would have.
            let records = !text.is_empty() || start != end;
            let stack = Some(inner.stack_id);
            if records {
                undo_redo_commands::seal_head(&inner.ctx, stack);
            }
            let result = if !text.is_empty() {
                self.insert_text_locked(
                    &mut inner,
                    start,
                    end,
                    text,
                    ReplaceFormatPolicy::PreserveIfFullyCovered,
                    origin,
                    Recording::History,
                )
            } else if start != end {
                self.remove_locked(&mut inner, start, end, Recording::History)
                    .map(|(_, queued)| queued)
            } else {
                Ok(Vec::new())
            };
            if records {
                undo_redo_commands::seal_head(&inner.ctx, stack);
            }
            // What is still queued: the revert's events when the recorded half did not take
            // them with its own.
            (result, inner.take_queued_events())
        };
        match result {
            Ok(mut queued) => {
                queued.extend(rest);
                crate::inner::dispatch_queued_events(queued);
                Ok(())
            }
            Err(error) => {
                crate::inner::dispatch_queued_events(rest);
                Err(error)
            }
        }
    }

    /// Where the cursor's position is in the document as recorded: where
    /// [`TextDocument::revert_transient_edits`] would put it. Its
    /// [`position`](Self::position) when no transient edits are outstanding.
    ///
    /// For a view that shows the recorded document
    /// ([`TextDocument::snapshot_recorded_flow_masked`]) to draw this cursor on the text it
    /// shows. Read with [`recorded_anchor`](Self::recorded_anchor), a selection holds the
    /// same recorded text the revert leaves it holding.
    pub fn recorded_position(&self) -> usize {
        self.recorded_stand().position
    }

    /// Where the cursor's anchor is in the document as recorded, as
    /// [`recorded_position`](Self::recorded_position) says of its position.
    pub fn recorded_anchor(&self) -> usize {
        self.recorded_stand().anchor
    }

    fn recorded_stand(&self) -> Stand {
        let inner = self.doc.lock();
        let now = Stand::of(&self.data.lock());
        match inner.transient.as_ref() {
            Some(layer) => layer.stand_after_revert(&Arc::downgrade(&self.data), now),
            None => now,
        }
    }
}

impl TextDocument {
    /// Revert the outstanding transient edits before a recorded write (see [`settle`]).
    pub(crate) fn settle_transient_edits(&self) -> Settled {
        settle(&self.inner)
    }

    /// Whether transient edits are outstanding (see
    /// [`TextCursor::insert_text_transient`]): the document shows text its history does not
    /// hold, which a revert takes away.
    pub fn has_transient_edits(&self) -> bool {
        self.inner.lock().transient.is_some()
    }

    /// Which layer of transient edits is outstanding, `None` when none is: the same from the
    /// first transient edit to the end of the layer, and another for the next one.
    ///
    /// For a view that shows only the transient edits it made (an input method's
    /// composition belongs to the view the writer types in): it notes the layer its edit
    /// began or joined, and the layer is its own while this still names it. A recorded
    /// write that reverts the composition, and transient edits someone else makes after it,
    /// make another layer, which [`has_transient_edits`](Self::has_transient_edits) alone
    /// cannot tell from the view's own.
    pub fn transient_layer(&self) -> Option<TransientLayerId> {
        self.inner.lock().transient.as_ref().map(|layer| layer.id)
    }

    /// Where the outstanding transient edits are, in the document as it is: the smallest
    /// range outside of which the document is as recorded. `None` when there are none.
    ///
    /// After a composition inserted transiently, the composition's text, which the next
    /// update selects to replace. After a transient removal and nothing else, an empty
    /// range where the text was. The range is the one
    /// [`TextCursor::commit_transient_text`] replaces, read in the document with the
    /// transient edits in place.
    pub fn transient_range(&self) -> Option<Range<usize>> {
        let inner = self.inner.lock();
        let span = inner.transient.as_ref()?.span?;
        Some(span.start..span.end)
    }

    /// Revert the outstanding transient edits, recording nothing: the document is back to
    /// its recorded content, as it was before the first of them, and the undo and redo
    /// histories are as they were. Returns whether there were any.
    ///
    /// What cancelling a composition calls. Every cursor goes back into the recorded text,
    /// as the [module documentation](crate::transient#positions) says: the cursor that showed
    /// a composition, left after it, lands after the text the composition took the place of.
    /// The change is
    /// announced as an edit's is ([`DocumentEvent::ContentsChanged`] over the range that
    /// changed, and the block and flow events when they apply), with nothing about the
    /// history.
    pub fn revert_transient_edits(&self) -> bool {
        let queued = {
            let mut inner = self.inner.lock();
            if inner.revert_transient_edits().is_none() {
                return false;
            }
            inner.take_queued_events()
        };
        crate::inner::dispatch_queued_events(queued);
        true
    }

    /// Snapshot the main flow as [`snapshot_flow_masked`](Self::snapshot_flow_masked) does,
    /// of the document **as recorded**: without the outstanding transient edits, as a revert
    /// would leave it. The same snapshot as `snapshot_flow_masked` when none are outstanding,
    /// at the same cost.
    ///
    /// For a view of the document that is not where the transient edits are made: a
    /// read-only preview beside the editor an input method composes in shows the text the
    /// writer has entered, not the composition. Its positions are those of the recorded
    /// document: show a cursor in it at [`TextCursor::recorded_position`] and
    /// [`TextCursor::recorded_anchor`], and map a position read off it into the document
    /// with [`position_from_recorded`](Self::position_from_recorded).
    ///
    /// The highlights are the document's own, made for the text as it shows: the ranges a
    /// host set ([`set_session_ranges`](Self::set_session_ranges)) and a syntax highlighter's
    /// spans. Each is moved back as a revert moves a range, so it lands on the recorded text
    /// it marks, and one that marked only transient text marks nothing. Within a paragraph
    /// the transient edits changed, the highlighter's spans are still the ones it found in
    /// the text with them (a keyword the composition splits stays split) until they end.
    pub fn snapshot_recorded_flow_masked(
        &self,
        mask: &crate::highlight::HighlightMask,
    ) -> crate::flow::FlowSnapshot {
        self.inner
            .lock()
            .read_recorded(|inner| crate::document::flow_snapshot_of(inner, mask, false))
    }

    /// [`snapshot_recorded_flow_masked`](Self::snapshot_recorded_flow_masked) without the
    /// paint-only overlay, as [`snapshot_flow_masked_no_paint`](Self::snapshot_flow_masked_no_paint)
    /// is to [`snapshot_flow_masked`](Self::snapshot_flow_masked): the accessibility tree of a
    /// view that shows the recorded document.
    pub fn snapshot_recorded_flow_masked_no_paint(
        &self,
        mask: &crate::highlight::HighlightMask,
    ) -> crate::flow::FlowSnapshot {
        self.inner
            .lock()
            .read_recorded(|inner| crate::document::flow_snapshot_of(inner, mask, true))
    }

    /// The block at `position` in the document as recorded, snapshot as
    /// [`snapshot_block_at_position_masked`](Self::snapshot_block_at_position_masked) does:
    /// the incremental relayout of a view that shows the recorded document (see
    /// [`snapshot_recorded_flow_masked`](Self::snapshot_recorded_flow_masked)). `position`
    /// is one of the recorded document's.
    pub fn snapshot_recorded_block_at_position_masked(
        &self,
        position: usize,
        mask: &crate::highlight::HighlightMask,
    ) -> Option<crate::flow::BlockSnapshot> {
        self.inner
            .lock()
            .read_recorded(|inner| crate::document::block_snapshot_at(inner, position, mask))
    }

    /// Where `position`, a position in the document as it is, is in the document as
    /// recorded: where a revert would put a caret standing there (see the
    /// [module documentation](crate::transient#positions)). Itself when no transient edits
    /// are outstanding.
    ///
    /// For one position a view that shows the recorded document (see
    /// [`snapshot_recorded_flow_masked`](Self::snapshot_recorded_flow_masked)) has to place
    /// on the text it shows. A cursor's own ends are read with
    /// [`TextCursor::recorded_position`] and [`TextCursor::recorded_anchor`] instead: its
    /// selection is moved back as a whole, and a cursor that only the transient edits moved
    /// goes back where it stood, which at a place where text was only removed is before the
    /// text put back, where this puts a caret after it.
    pub fn recorded_position(&self, position: usize) -> usize {
        match self.inner.lock().transient.as_ref() {
            Some(layer) => map_back_through(&layer.splices, position, RangeEnd::Start),
            None => position,
        }
    }

    /// Where `recorded`, a position in the document as recorded, is in the document as it
    /// is: moved across the outstanding transient edits as they moved every cursor. Itself
    /// when none are outstanding.
    ///
    /// What a view that shows the recorded document (see
    /// [`snapshot_recorded_flow_masked`](Self::snapshot_recorded_flow_masked)) puts a cursor
    /// at, for a position it reads off its own layout: a click, an assistive technology's
    /// selection. Outside the text the transient edits changed, the cursor's
    /// [`recorded_position`](TextCursor::recorded_position) is then `recorded` again; at
    /// that text's edge or inside it, the cursor lands at its edge.
    pub fn position_from_recorded(&self, recorded: usize) -> usize {
        match self.inner.lock().transient.as_ref() {
            Some(layer) => layer.map_forward(recorded),
            None => recorded,
        }
    }
}

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

    fn layer(splices: &[(usize, usize, usize)]) -> TransientLayer {
        let mut layer = TransientLayer::over(&[]);
        for &(at, removed, added) in splices {
            layer.record(at, removed, added);
        }
        layer
    }

    #[test]
    fn a_composition_replaced_at_every_update_is_one_span_over_nothing_recorded() {
        // "n" at 3, then "ni", "nih", "nihao" over it.
        let layer = layer(&[(3, 0, 1), (3, 1, 2), (3, 2, 3), (3, 3, 5)]);
        assert_eq!(
            layer.span,
            Some(Span {
                start: 3,
                end: 8,
                recorded_end: 3
            })
        );
        assert!(!layer.scattered);
    }

    #[test]
    fn a_removed_syllable_shown_converted_is_one_span_over_the_syllable() {
        let layer = layer(&[(7, 1, 0), (7, 0, 1)]);
        assert_eq!(
            layer.span,
            Some(Span {
                start: 7,
                end: 8,
                recorded_end: 8
            })
        );
        assert!(!layer.scattered);
    }

    #[test]
    fn an_edit_touching_the_span_from_before_extends_it() {
        // A composition at 5..8, then the two recorded characters before it removed.
        let layer = layer(&[(5, 0, 3), (3, 2, 0)]);
        assert_eq!(
            layer.span,
            Some(Span {
                start: 3,
                end: 6,
                recorded_end: 5
            })
        );
        assert!(!layer.scattered);
    }

    #[test]
    fn an_edit_away_from_the_span_scatters_the_layer() {
        let layer = layer(&[(3, 0, 2), (10, 0, 1)]);
        assert!(layer.scattered);
        // The span still bounds both, recorded text between them included.
        assert_eq!(
            layer.span,
            Some(Span {
                start: 3,
                end: 11,
                recorded_end: 8
            })
        );
    }

    #[test]
    fn a_removal_then_an_insertion_in_its_place_is_one_replacement() {
        // "ab한": the syllable taken out, then its candidate shown in its place.
        let layer = layer(&[(2, 1, 0), (2, 0, 1)]);
        assert_eq!(
            layer.splices,
            [Splice {
                at: 2,
                removed: 1,
                added: 1
            }]
        );
        assert_eq!(layer.steps.len(), 2);
        let reverted = Reverted {
            splices: layer.splices.clone(),
        };
        assert_eq!(
            reverted.map_range(2, 3),
            (2, 3),
            "the candidate is the syllable"
        );
        assert_eq!(layer.map_forward(3), 3);
    }

    #[test]
    fn changes_that_touch_compose_and_others_do_not() {
        let composed = |a: (usize, usize, usize), b: (usize, usize, usize)| {
            let splice = |(at, removed, added)| Splice { at, removed, added };
            splice(a)
                .then(splice(b))
                .map(|s| (s.at, s.removed, s.added))
        };
        // A composition replaced by its next state.
        assert_eq!(composed((3, 0, 1), (3, 1, 2)), Some((3, 0, 2)));
        // Recorded text before it taken out up to it.
        assert_eq!(composed((5, 0, 3), (3, 2, 0)), Some((3, 2, 3)));
        // Its last character and two recorded ones after it taken out.
        assert_eq!(composed((2, 0, 2), (3, 3, 0)), Some((2, 2, 1)));
        // Recorded text right after it taken out.
        assert_eq!(composed((2, 0, 2), (4, 2, 0)), Some((2, 2, 2)));
        // Elsewhere.
        assert_eq!(composed((2, 0, 2), (5, 0, 1)), None);
        assert_eq!(composed((5, 0, 2), (1, 2, 0)), None);
    }

    #[test]
    fn a_change_of_nothing_is_not_recorded() {
        let layer = layer(&[(4, 0, 0)]);
        assert!(layer.splices.is_empty());
        assert_eq!(layer.span, None);
    }

    #[test]
    fn mapping_back_undoes_every_change_in_reverse() {
        let reverted = Reverted {
            splices: vec![
                Splice {
                    at: 3,
                    removed: 0,
                    added: 1,
                },
                Splice {
                    at: 3,
                    removed: 1,
                    added: 5,
                },
            ],
        };
        // Before the composition, inside it, at its end, and after it.
        for end in [RangeEnd::Start, RangeEnd::End] {
            let map = |position| map_back_through(&reverted.splices, position, end);
            assert_eq!(map(2), 2);
            assert_eq!(map(5), 3);
            assert_eq!(map(8), 3);
            assert_eq!(map(12), 7);
        }
    }

    #[test]
    fn a_range_starting_where_text_was_removed_starts_after_it_again() {
        // "hello" with "ll" (2..4) removed: "heo".
        let reverted = Reverted {
            splices: vec![Splice {
                at: 2,
                removed: 2,
                added: 0,
            }],
        };
        // The "o", live 2..3, is recorded 4..5; "he", live 0..2, is recorded 0..2.
        assert_eq!(reverted.map_range(2, 3), (4, 5));
        assert_eq!(reverted.map_range(0, 2), (0, 2));
        // A range across the removal holds what was removed as well.
        assert_eq!(reverted.map_range(1, 3), (1, 5));
    }

    /// A recorded edit with a selection that finds transient edits made since its revert
    /// (another thread's, between the revert and its lock) is refused, and leaves an edit
    /// block it is part of whole.
    #[test]
    fn a_recorded_edit_finding_a_layer_keeps_the_edit_block_whole() {
        let doc = TextDocument::new();
        doc.set_plain_text("hello world").unwrap();
        doc.clear_undo_redo();
        let cursor = doc.cursor_at(0);
        cursor.begin_edit_block();
        cursor.insert_text("A").unwrap();
        // The other thread's transient edit, after this edit's revert.
        doc.cursor_at(3).insert_text_transient("x").unwrap();
        let refused = {
            let mut inner = doc.inner.lock();
            cursor.insert_text_locked(
                &mut inner,
                7,
                12,
                "b",
                ReplaceFormatPolicy::default(),
                InsertionOrigin::Unspecified,
                Recording::History,
            )
        };
        assert!(matches!(
            refused,
            Err(DocumentError::TransientEdits(
                crate::TransientRefusal::LayerOutstanding
            ))
        ));
        cursor.end_edit_block();
        doc.revert_transient_edits();
        assert_eq!(doc.to_plain_text().unwrap(), "Ahello world");
        doc.undo().unwrap();
        assert_eq!(doc.to_plain_text().unwrap(), "hello world");
        assert!(!doc.can_undo());
    }

    /// A transient edit while a write is open on the store (the one this crate leaves open
    /// across its calls is a load in place, refused earlier) is the store's refusal, with
    /// nothing changed, and is made once the write has ended.
    #[test]
    fn a_transient_edit_over_an_open_write_is_refused_by_the_store() {
        let doc = TextDocument::new();
        doc.set_plain_text("abc").unwrap();
        let db = doc.inner.lock().ctx.db_context.clone();
        let transaction =
            common::database::transactions::Transaction::begin_write_transaction(&db).unwrap();
        let refused = doc.cursor_at(1).insert_text_transient("n");
        assert!(matches!(
            refused,
            Err(DocumentError::TransientEdits(
                crate::TransientRefusal::WriteInProgress
            ))
        ));
        assert!(!doc.has_transient_edits());
        assert_eq!(doc.to_plain_text().unwrap(), "abc");
        drop(transaction);
        doc.cursor_at(1).insert_text_transient("n").unwrap();
        assert_eq!(doc.to_plain_text().unwrap(), "anbc");
    }

    #[test]
    fn a_range_that_held_only_transient_text_comes_back_empty() {
        let reverted = Reverted {
            splices: vec![Splice {
                at: 5,
                removed: 0,
                added: 3,
            }],
        };
        assert_eq!(reverted.map_range(5, 8), (5, 5));
        assert_eq!(reverted.map_range(6, 7), (5, 5));
    }
}