Skip to main content

text_document/
transient.rs

1//! Transient edits: changes to the document that no undo history records.
2//!
3//! An input method's composition (the candidates of a Chinese or Japanese input method, the
4//! Korean syllable being built, the live text of dictation) has to be shown in the text,
5//! where the writer is looking, and has to be replaced at every update. Made as ordinary
6//! edits, every update was recorded, and once the composition was committed an undo
7//! replayed each state it went through. A transient edit changes the document and is
8//! announced as a change of its content is ([`DocumentEvent::ContentsChanged`], and the
9//! block and flow events when they apply), so views lay it out and draw it, but it is not
10//! recorded: the undo and redo histories stay as they were, and so does the coalescing of
11//! typing. Nothing arrives yet, so there is no [`DocumentEvent::TextInserted`].
12//!
13//! The edits are [`TextCursor::insert_text_transient`],
14//! [`TextCursor::insert_text_transient_merged`],
15//! [`TextCursor::insert_formatted_text_transient`] and
16//! [`TextCursor::remove_selected_text_transient`].
17//!
18//! # The layer
19//!
20//! The outstanding transient edits are one **layer** over the document as it is recorded.
21//! The layer belongs to the document, whichever cursor made its edits. It begins with the
22//! first transient edit and ends when it is reverted, which puts the recorded content back
23//! as it was before that first edit: the same text, formats and block identities, which is
24//! what every recorded undo entry refers to. Nothing is recorded and the histories are
25//! untouched.
26//!
27//! The layer ends in one of three ways:
28//!
29//! * [`TextDocument::revert_transient_edits`]: the composition is cancelled.
30//! * [`TextCursor::commit_transient_text`]: the composition is committed. The layer is
31//!   reverted, and the text it changed is replaced with the committed text, recorded as
32//!   **one undo step of its own**, closed on both sides: it does not coalesce with the
33//!   typing before it, and the typing after it starts a step of its own, so an undo takes
34//!   back exactly the committed text and gives back what the composition took the place
35//!   of. Inside an open edit block ([`TextCursor::begin_edit_block`]) the commit joins the
36//!   block, as every recorded edit there does.
37//! * Any recorded write to the document, by any cursor or clone of the document. Every edit,
38//!   undo, redo and load reverts the layer before anything else, its own checks included,
39//!   then acts on the recorded content, so the layer is gone even when the write then fails
40//!   or changes nothing. The streaming appends alone check their lines first, and leave the
41//!   layer when they refuse them.
42//!
43//! So a host never keeps its own record of where its composition is: before each update it
44//! asks [`TextDocument::transient_range`], which is `None` once anything has reverted it.
45//!
46//! The history's operations that change no content do not end the layer:
47//! [`TextDocument::clear_undo_redo`], [`TextDocument::break_undo_merge`] and an edit block
48//! leave it outstanding. Nor does [`TextDocument::set_footnote_markers`]: the markers are
49//! the host's, not content, and a revert keeps them.
50//!
51//! # Positions
52//!
53//! A revert puts every cursor back in the recorded text. One that only the transient edits
54//! moved goes back exactly where it stood, the table cells or the whole text it selected
55//! included. Any other (one that something else moved
56//! meanwhile, one made since) is moved back across each transient edit in turn, from the
57//! last, an edit that touches the text the one before it made counting with it as one (a
58//! syllable taken out and its candidate shown in its place are one replacement): a position
59//! 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
60//! the edit replaced, and one at its start to that text's start, except where the edit only
61//! removed text: there a selection's start, or a caret, goes after the text put back, and
62//! its end before it. So a selection holds the recorded text it held, and one that held
63//! only text a transient edit inserted over nothing comes back empty.
64//!
65//! The recorded writes read a cursor after their revert, so they act where it stands in the
66//! recorded text. The explicit ranges of [`TextCursor::replace`] and
67//! [`TextDocument::replace_ranges`] are read in the document as it was, with the layer, and
68//! moved back the same way, under the lock the write itself takes.
69//!
70//! # Reading
71//!
72//! While the layer is outstanding, the document reads as it shows: the text, the flow, a
73//! search, an export. A host that saves on a timer saves the composition with the rest, and
74//! should revert or commit first when that matters (see
75//! [`TextDocument::has_transient_edits`]).
76//!
77//! A view that is not where the transient edits are made (a read-only preview beside the
78//! editor an input method composes in) shows the recorded document instead:
79//! [`TextDocument::snapshot_recorded_flow_masked`], its `_no_paint` twin and
80//! [`TextDocument::snapshot_recorded_block_at_position_masked`] snapshot it as a revert
81//! would leave it. Its positions are the recorded document's: such a view draws a cursor at
82//! [`TextCursor::recorded_position`] and [`TextCursor::recorded_anchor`], where a revert
83//! puts it, places any other position of the document with
84//! [`TextDocument::recorded_position`], and maps a position read off its own layout into
85//! the document with [`TextDocument::position_from_recorded`]. A view that shows only the
86//! transient edits it made itself tells its layer from another with
87//! [`TextDocument::transient_layer`].
88//!
89//! # Under a host's lock
90//!
91//! An input method that edits under a lock of its own (Windows' Text Services Framework
92//! grants one, and reads back what it wrote under the same lock) must not see application
93//! code write the document while it holds the lock: a recorded write by a change callback
94//! would revert the layer, and the input method would read back text other than the text it
95//! wrote. The host holds the document's events for the lock's duration
96//! ([`TextDocument::hold_events`]). Under the hold, the transient edits, their revert, their
97//! commit and every other edit change the document and move its cursors at once, and every
98//! read ([`TextDocument::transient_range`], the text, a cursor's position) sees them; only
99//! their events wait, and go out in the order they were queued when the hold is dropped,
100//! after the lock. A callback that then writes the document reverts or ends the layer as
101//! any recorded write does, outside the lock.
102//!
103//! # Refusals
104//!
105//! What the layer cannot do is refused with [`DocumentError::TransientEdits`], whose
106//! [`TransientRefusal`](crate::TransientRefusal) says which case it is. Underneath, the
107//! document's store enforces what the layer needs of it, whoever calls it:
108//!
109//! * while a layer is outstanding, it refuses to begin any write that is not a transient
110//!   edit's own (a write transaction, a streaming append), so that no recorded edit lands
111//!   over the layer and is then taken away by the revert. Every write this crate offers
112//!   reverts the layer first, so that refusal reaches a caller only when a transient edit
113//!   is made from another thread between the revert and the write
114//!   ([`TransientRefusal::LayerOutstanding`](crate::TransientRefusal::LayerOutstanding));
115//! * it refuses to begin a transient write while any other write is open, a transient one
116//!   included, since the first one's snapshot is the recorded content
117//!   ([`TransientRefusal::WriteInProgress`](crate::TransientRefusal::WriteInProgress));
118//! * it refuses a revert while a transient write is in progress, which the document's lock
119//!   rules out here.
120
121use std::ops::Range;
122use std::sync::{Arc, Weak};
123
124use parking_lot::Mutex;
125
126use frontend::commands::undo_redo_commands;
127
128use crate::cursor::{Recording, TextCursor};
129use crate::document::TextDocument;
130use crate::events::{DocumentEvent, InsertionOrigin};
131use crate::inner::{CursorData, QueuedEvents, TextDocumentInner, adjust_offset};
132use crate::{DocumentError, ReplaceFormatPolicy, Result, TextFormat};
133
134/// One change a transient edit made to the document's positions: from `at`, `removed`
135/// positions replaced by `added`, in the positions the document had at the time.
136#[derive(Debug, Clone, Copy, PartialEq, Eq)]
137pub(crate) struct Splice {
138    pub at: usize,
139    pub removed: usize,
140    pub added: usize,
141}
142
143impl Splice {
144    /// This change followed by `next`, as one change, when `next` touches what this one
145    /// made (`[at, at + added]`, either edge included). `None` when it is elsewhere.
146    ///
147    /// Across one change, a position inside what it made goes to the end of what it
148    /// replaced, and one at its start to its start. Across two that touch, which is what an
149    /// input method makes when it takes a syllable out and then shows its candidate in its
150    /// place, the edges cross: the candidate's start goes after the syllable (where text
151    /// was only removed) and its end before it, so a range over the candidate held nothing.
152    /// Composed, they are the one replacement the writer sees.
153    fn then(self, next: Splice) -> Option<Splice> {
154        let made_end = self.at + self.added;
155        if next.at > made_end || next.at + next.removed < self.at {
156            return None;
157        }
158        // What `next` removed before what this change made, after it, and inside it.
159        let before = self.at.saturating_sub(next.at);
160        let after = (next.at + next.removed).saturating_sub(made_end);
161        let inside = next.removed.saturating_sub(before + after);
162        Some(Splice {
163            at: self.at.min(next.at),
164            removed: before + self.removed + after,
165            added: self.added.saturating_sub(inside) + next.added,
166        })
167    }
168}
169
170/// The part of the document the outstanding transient edits changed: outside it, the
171/// document is as recorded.
172#[derive(Debug, Clone, Copy, PartialEq, Eq)]
173struct Span {
174    /// Where it starts, the same position in the document as it is and as recorded.
175    start: usize,
176    /// Where it ends in the document as it is.
177    end: usize,
178    /// Where it ends in the document as recorded.
179    recorded_end: usize,
180}
181
182/// Where a cursor stands: what a revert gives back to it.
183#[derive(Debug, Clone, Copy, PartialEq, Eq)]
184struct Stand {
185    position: usize,
186    anchor: usize,
187    anchor_in_table: Option<usize>,
188}
189
190impl Stand {
191    fn of(data: &CursorData) -> Self {
192        Stand {
193            position: data.position,
194            anchor: data.anchor,
195            anchor_in_table: data.anchor_in_table,
196        }
197    }
198
199    /// Moved as an edit moves every cursor (see `TextDocumentInner::adjust_cursors`).
200    fn adjusted(self, at: usize, removed: usize, added: usize) -> Self {
201        Stand {
202            position: adjust_offset(self.position, at, removed, added),
203            anchor: adjust_offset(self.anchor, at, removed, added),
204            anchor_in_table: self
205                .anchor_in_table
206                .map(|origin| adjust_offset(origin, at, removed, added)),
207        }
208    }
209
210    /// Moved back across `splices`: a selection's two ends inwards (see [`RangeEnd`]), so
211    /// it holds the same recorded text, a caret as a range's start.
212    fn mapped_back(self, splices: &[Splice]) -> Self {
213        let (low, high) = if self.position <= self.anchor {
214            (&self.position, &self.anchor)
215        } else {
216            (&self.anchor, &self.position)
217        };
218        let low_back = map_back_through(splices, *low, RangeEnd::Start);
219        let high_back = if high == low {
220            low_back
221        } else {
222            map_back_through(splices, *high, RangeEnd::End)
223        };
224        let (position, anchor) = if self.position <= self.anchor {
225            (low_back, high_back)
226        } else {
227            (high_back, low_back)
228        };
229        Stand {
230            position,
231            anchor,
232            anchor_in_table: self
233                .anchor_in_table
234                .map(|origin| map_back_through(splices, origin, RangeEnd::Start)),
235        }
236    }
237}
238
239/// A cursor alive when the layer began: where it stood then, and where the transient edits
240/// alone have taken it since.
241///
242/// A cursor that is still where they took it was moved by nothing else, and a revert puts
243/// it back exactly where it stood. Only a cursor something else moved meanwhile (the one
244/// making the edits, one the writer clicked elsewhere) has to be mapped back through the
245/// changes, which cannot always tell where text came back: a caret where text was removed
246/// stood before it or inside it, and the two look the same.
247#[derive(Debug)]
248struct Rider {
249    cursor: Weak<Mutex<CursorData>>,
250    stood: Stand,
251    expected: Stand,
252    /// What its selection was besides its ends, which every edit, a transient one included,
253    /// clears on every cursor (see `TextDocumentInner::adjust_cursors`): a revert that puts
254    /// it back where it stood puts these back too, the text being the one they were of.
255    cells: Option<crate::flow::CellRange>,
256    whole_text: bool,
257}
258
259/// Which end of a range a position is, read with transient edits in place. It matters only
260/// where an edit removed text and inserted none: there a revert puts text back at that very
261/// position, and this says which side of it the position goes.
262#[derive(Debug, Clone, Copy, PartialEq, Eq)]
263pub(crate) enum RangeEnd {
264    /// A range's start, or a caret: after the text put back, before what followed it.
265    Start,
266    /// A range's end: before the text put back, after what preceded it.
267    End,
268}
269
270/// `position` moved back across one transient change: the inverse of what it did.
271fn unsplice(position: usize, splice: Splice, end: RangeEnd) -> usize {
272    // The change replaced `removed` positions from `at` with `added`; back across it,
273    // `added` positions from `at` become `removed` again.
274    let Splice { at, removed, added } = splice;
275    if position < at {
276        position
277    } else if position == at {
278        // Text only removed, and put back here: a range starting here starts at what
279        // followed the text, as it did before the removal.
280        if added == 0 && end == RangeEnd::Start {
281            at + removed
282        } else {
283            at
284        }
285    } else if position <= at + added {
286        at + removed
287    } else {
288        position - added + removed
289    }
290}
291
292/// `position` moved back across `splices`, the changes made, in order.
293fn map_back_through(splices: &[Splice], position: usize, end: RangeEnd) -> usize {
294    splices
295        .iter()
296        .rev()
297        .fold(position, |p, splice| unsplice(p, *splice, end))
298}
299
300/// Which layer of transient edits a document holds (see
301/// [`TextDocument::transient_layer`]): the same for as long as they are outstanding, and
302/// another once they have ended and new ones begin, in this document or any other.
303#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
304pub struct TransientLayerId(u64);
305
306impl TransientLayerId {
307    /// A layer no other has been or will be, in this process.
308    fn next() -> Self {
309        static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
310        TransientLayerId(NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed))
311    }
312}
313
314/// The outstanding transient edits (see the module documentation).
315#[derive(Debug)]
316pub(crate) struct TransientLayer {
317    /// Which layer this is, for a view that has to tell its own from another's.
318    id: TransientLayerId,
319    /// Every change of positions the layer made, in order, as each edit made it: what a
320    /// panicking edit announces, and how an edit is seen to have changed anything.
321    steps: Vec<Splice>,
322    /// The same changes, each composed with the one before it when they touch (see
323    /// [`Splice::then`]): what a revert maps the cursors back through, and every mapping
324    /// of a position between the document as it is and as recorded.
325    splices: Vec<Splice>,
326    span: Option<Span>,
327    /// Whether one of the edits changed the document away from the span the earlier ones
328    /// had changed, so that the span holds recorded text between them.
329    scattered: bool,
330    riders: Vec<Rider>,
331}
332
333impl TransientLayer {
334    /// A layer beginning while `cursors` are alive, each of which a revert gives back where
335    /// it stands now unless something other than the transient edits moves it.
336    pub(crate) fn over(cursors: &[Weak<Mutex<CursorData>>]) -> Self {
337        let riders = cursors
338            .iter()
339            .filter_map(|weak| {
340                let cursor = weak.upgrade()?;
341                let data = cursor.lock();
342                let stood = Stand::of(&data);
343                Some(Rider {
344                    cursor: weak.clone(),
345                    stood,
346                    expected: stood,
347                    cells: data.cell_selection_override.clone(),
348                    whole_text: data.whole_text_selected,
349                })
350            })
351            .collect();
352        TransientLayer {
353            id: TransientLayerId::next(),
354            steps: Vec::new(),
355            splices: Vec::new(),
356            span: None,
357            scattered: false,
358            riders,
359        }
360    }
361
362    /// A transient edit replaced `removed` positions from `at` with `added`.
363    ///
364    /// Called from `TextDocumentInner::adjust_cursors`, which every edit goes through to
365    /// move the cursors: while a layer is outstanding, every edit is a transient one.
366    pub(crate) fn record(&mut self, at: usize, removed: usize, added: usize) {
367        if removed == 0 && added == 0 {
368            return;
369        }
370        let splice = Splice { at, removed, added };
371        self.steps.push(splice);
372        match self.splices.last().and_then(|last| last.then(splice)) {
373            Some(composed) => *self.splices.last_mut().expect("there is a last") = composed,
374            None => self.splices.push(splice),
375        }
376        for rider in &mut self.riders {
377            rider.expected = rider.expected.adjusted(at, removed, added);
378        }
379        self.span = Some(match self.span {
380            None => Span {
381                start: at,
382                end: at + added,
383                recorded_end: at + removed,
384            },
385            Some(span) => {
386                if at > span.end || at + removed < span.start {
387                    self.scattered = true;
388                }
389                let start = span.start.min(at);
390                let end_before = span.end.max(at + removed);
391                // The recorded text the span now covers: what it covered, and the unchanged
392                // positions it grew over on either side.
393                let recorded_len = (span.recorded_end - span.start)
394                    + (span.start - start)
395                    + (end_before - span.end);
396                Span {
397                    start,
398                    end: end_before - removed + added,
399                    recorded_end: start + recorded_len,
400                }
401            }
402        });
403    }
404
405    /// Where a revert puts `cursor`, which stands at `now`: where it stood when the layer
406    /// began if only the transient edits moved it, else `now` moved back across them.
407    fn stand_after_revert(&self, cursor: &Weak<Mutex<CursorData>>, now: Stand) -> Stand {
408        match self.carried(cursor, now) {
409            Some(rider) => rider.stood,
410            None => now.mapped_back(&self.splices),
411        }
412    }
413
414    /// `cursor`'s rider, when the cursor stands at `now` and only the transient edits moved
415    /// it there: one a revert puts back exactly as it was.
416    fn carried(&self, cursor: &Weak<Mutex<CursorData>>, now: Stand) -> Option<&Rider> {
417        self.riders
418            .iter()
419            .find(|rider| Weak::ptr_eq(&rider.cursor, cursor) && rider.expected == now)
420    }
421
422    /// The range `[start, end)`, read in the document as it shows, in the recorded document,
423    /// as [`Reverted::map_range`] moves it back once the layer is reverted.
424    pub(crate) fn map_range_back(&self, start: usize, end: usize) -> (usize, usize) {
425        map_range_through(&self.splices, start, end)
426    }
427
428    /// [`map_forward`](Self::map_forward), for a reader of the recorded document that has to
429    /// find where one of its positions shows.
430    pub(crate) fn map_position_forward(&self, recorded: usize) -> usize {
431        self.map_forward(recorded)
432    }
433
434    /// `recorded`, a position in the document as recorded, in the document as it is: moved
435    /// across every change the layer made, as each moved every cursor.
436    fn map_forward(&self, recorded: usize) -> usize {
437        self.splices.iter().fold(recorded, |position, splice| {
438            adjust_offset(position, splice.at, splice.removed, splice.added)
439        })
440    }
441}
442
443/// The transient edits a revert took away: how to map a position read in the document as
444/// it was, with them, into the document as it is now.
445#[derive(Debug, Default)]
446pub(crate) struct Reverted {
447    splices: Vec<Splice>,
448}
449
450impl Reverted {
451    /// The range `[start, end)` (either order), read with the transient edits in place, in
452    /// the recorded document: its start moved back as a start, its end as an end, so that it
453    /// holds the recorded text it held. A range that held only transient text can come back
454    /// empty.
455    pub(crate) fn map_range(&self, start: usize, end: usize) -> (usize, usize) {
456        map_range_through(&self.splices, start, end)
457    }
458}
459
460/// [`Reverted::map_range`] across `splices`.
461fn map_range_through(splices: &[Splice], start: usize, end: usize) -> (usize, usize) {
462    let (low, high) = (start.min(end), start.max(end));
463    if low == high {
464        let at = map_back_through(splices, low, RangeEnd::Start);
465        return (at, at);
466    }
467    let low = map_back_through(splices, low, RangeEnd::Start);
468    let high = map_back_through(splices, high, RangeEnd::End);
469    (low, high.max(low))
470}
471
472/// [`Reverted::map_range`] of an optional revert: the range, ordered, when there was none.
473pub(crate) fn map_range_back(
474    reverted: &Option<Reverted>,
475    start: usize,
476    end: usize,
477) -> (usize, usize) {
478    match reverted {
479        Some(reverted) => reverted.map_range(start, end),
480        None => (start.min(end), start.max(end)),
481    }
482}
483
484/// What [`settle`] did before a recorded write: the transient edits it reverted, if any,
485/// with the events that announce it still queued.
486///
487/// The events go out with the write's own, in order, when the write dispatches them: no
488/// callback runs between the revert and the write. A callback that wrote then, from the
489/// revert's own announcement, would write before the write it made way for: an undo would
490/// have taken back the callback's edit instead of the writer's, and a callback putting a
491/// composition back would have had the write refused. Whatever is still queued when this
492/// is dropped (a write that returned before dispatching anything, or failed) goes out then,
493/// so it is held until the write has run and the document is unlocked.
494#[must_use = "hold it until the write has run: the revert's events go out with the write's"]
495pub(crate) struct Settled {
496    /// The document, when a revert happened and its events are still to go out.
497    doc: Option<Arc<Mutex<TextDocumentInner>>>,
498}
499
500impl Drop for Settled {
501    fn drop(&mut self) {
502        if let Some(doc) = self.doc.take() {
503            let queued = doc.lock().take_queued_events();
504            crate::inner::dispatch_queued_events(queued);
505        }
506    }
507}
508
509impl TextDocumentInner {
510    /// Revert the outstanding transient edits: the store back to the recorded content, every
511    /// cursor mapped back, the change announced. `None` when there were none.
512    ///
513    /// The events are queued, not dispatched: the caller dispatches them with its own.
514    pub(crate) fn revert_transient_edits(&mut self) -> Option<Reverted> {
515        let layer = self.transient.take()?;
516        // The store refuses a revert only inside a transient write or over an open write.
517        // This document's transient writes hold its lock as this does, its recorded writes
518        // end before they let it go, and the one write that outlives a call, a load in
519        // place, is never open with a layer: it cannot happen, and if it did, the layer and
520        // the store are left as they are, in step.
521        let Ok(reverted) = self.ctx.db_context.get_store().revert_transient_edits() else {
522            self.transient = Some(layer);
523            debug_assert!(
524                false,
525                "the store refused a revert under the document's lock"
526            );
527            return None;
528        };
529        debug_assert!(
530            reverted || layer.steps.is_empty(),
531            "the document held transient edits that its store did not"
532        );
533        self.prune_dead_cursors();
534        for weak in &self.cursors {
535            let Some(cursor) = weak.upgrade() else {
536                continue;
537            };
538            let mut data = cursor.lock();
539            let now = Stand::of(&data);
540            let back = layer.stand_after_revert(weak, now);
541            data.position = back.position;
542            data.anchor = back.anchor;
543            data.anchor_in_table = back.anchor_in_table;
544            // A cursor put back as it was gets back the cells or the whole text it selected;
545            // any other selection is a new one, of positions alone.
546            let carried = layer.carried(weak, now);
547            data.cell_selection_override = carried.and_then(|rider| rider.cells.clone());
548            data.whole_text_selected = carried.is_some_and(|rider| rider.whole_text);
549        }
550        self.invalidate_text_cache();
551        if let Some(span) = layer.span {
552            let blocks_affected = self.blocks_between(span.start, span.recorded_end);
553            if blocks_affected > 1 {
554                self.rehighlight_all();
555            } else {
556                self.rehighlight_affected(span.start);
557            }
558            self.queue_event(DocumentEvent::ContentsChanged {
559                position: span.start,
560                chars_removed: span.end - span.start,
561                chars_added: span.recorded_end - span.start,
562                blocks_affected,
563            });
564        }
565        self.check_block_count_changed();
566        self.check_flow_changed();
567        Some(Reverted {
568            splices: layer.splices,
569        })
570    }
571
572    /// How many blocks `[start, end)` touches, at least one.
573    ///
574    /// Its last position is `end - 1`: the block at `end` itself starts after a separator
575    /// the range ends before, which a block lookup counts as that next block's.
576    fn blocks_between(&self, start: usize, end: usize) -> usize {
577        let number = |position: usize| {
578            frontend::commands::document_inspection_commands::get_block_at_position(
579                &self.ctx,
580                &frontend::document_inspection::GetBlockAtPositionDto {
581                    position: position as i64,
582                },
583            )
584            .ok()
585            .map(|info| info.block_number)
586        };
587        match (number(start), number(end.saturating_sub(1).max(start))) {
588            (Some(first), Some(last)) if last > first => (last - first) as usize + 1,
589            _ => 1,
590        }
591    }
592
593    /// After a panic inside a transient edit that had made its change: announce the change,
594    /// unless the edit had already, and what it did to the paragraphs and the flow. A panic
595    /// in a syntax highlighter comes before the edit announces anything, and the document
596    /// would show text no listener had heard of.
597    fn announce_kept_changes(&mut self, changes_before: usize, events_before: usize) {
598        let announced = self
599            .pending_events
600            .get(events_before..)
601            .is_some_and(|events| {
602                events
603                    .iter()
604                    .any(|event| matches!(event, DocumentEvent::ContentsChanged { .. }))
605            });
606        let kept: Vec<Splice> = self
607            .transient
608            .as_ref()
609            .map(|layer| layer.steps[changes_before..].to_vec())
610            .unwrap_or_default();
611        self.invalidate_text_cache();
612        if !announced {
613            for splice in &kept {
614                let blocks_affected = self.blocks_between(splice.at, splice.at + splice.added);
615                self.queue_event(DocumentEvent::ContentsChanged {
616                    position: splice.at,
617                    chars_removed: splice.removed,
618                    chars_added: splice.added,
619                    blocks_affected,
620                });
621            }
622        }
623        if !kept.is_empty() {
624            self.check_block_count_changed();
625            self.check_flow_changed();
626        }
627    }
628
629    /// Run `read` over the document as recorded: as it is when no transient edits are
630    /// outstanding, and otherwise over a store of its own holding the content a revert would
631    /// put back (`RopeStore::recorded_snapshot`), which nothing else sees.
632    ///
633    /// Only the context `read` is handed changes, for as long as it runs: the document's own
634    /// store, which an export running on another thread may be reading, keeps the transient
635    /// edits. `read` must only read through the context, as the snapshot builders do: the
636    /// caches beside it (the plain text, the highlights) were made from the document as it
637    /// is. The one of them a snapshot reads by position, a host's highlight ranges, is moved
638    /// back across the transient edits where it is sliced to a block (see
639    /// [`recorded_reading`](Self::recorded_reading)).
640    pub(crate) fn read_recorded<R>(&mut self, read: impl FnOnce(&TextDocumentInner) -> R) -> R {
641        let recorded = self
642            .transient
643            .as_ref()
644            .and_then(|_| self.ctx.db_context.get_store().recorded_snapshot());
645        let Some(recorded) = recorded else {
646            return read(self);
647        };
648        let mut ctx = self.ctx.clone();
649        ctx.db_context =
650            common::database::db_context::DbContext::new().expect("an empty store is always made");
651        ctx.db_context.get_store().restore(&recorded);
652        let live = std::mem::replace(&mut self.ctx, ctx);
653        self.reading_recorded = true;
654        // Puts the document's own context back however `read` ends, a panic included: left
655        // in place, the recorded one would take the document's next writes.
656        struct Restore<'a> {
657            inner: &'a mut TextDocumentInner,
658            live: Option<frontend::AppContext>,
659        }
660        impl Drop for Restore<'_> {
661            fn drop(&mut self) {
662                if let Some(live) = self.live.take() {
663                    self.inner.ctx = live;
664                }
665                self.inner.reading_recorded = false;
666            }
667        }
668        let restore = Restore {
669            inner: self,
670            live: Some(live),
671        };
672        read(restore.inner)
673    }
674
675    /// The outstanding transient edits, while the document is read as recorded (inside
676    /// [`read_recorded`](Self::read_recorded)): what a position of the document as it shows,
677    /// kept beside the store, is moved back across. `None` otherwise.
678    pub(crate) fn recorded_reading(&self) -> Option<&TransientLayer> {
679        self.transient.as_ref().filter(|_| self.reading_recorded)
680    }
681
682    /// Whether a load in place this document started is still writing its content.
683    fn is_loading_in_place(&self) -> bool {
684        if self.history_resets.is_empty() {
685            return false;
686        }
687        let operations = self.ctx.long_operation_manager.lock();
688        self.history_resets
689            .keys()
690            .any(|id| operations.is_operation_finished(id) == Some(false))
691    }
692}
693
694/// Revert `doc`'s outstanding transient edits, if any, before a recorded write.
695///
696/// What a recorded edit calls first, before it reads a cursor, so that it acts on the
697/// recorded text at the cursor's place in it. Hold what it returns until the write has run
698/// (see [`Settled`]).
699pub(crate) fn settle(doc: &Arc<Mutex<TextDocumentInner>>) -> Settled {
700    let reverted = doc.lock().revert_transient_edits().is_some();
701    Settled {
702        doc: reverted.then(|| Arc::clone(doc)),
703    }
704}
705
706impl TextCursor {
707    /// Revert the document's outstanding transient edits before an edit reads this cursor
708    /// (see [`settle`]).
709    pub(crate) fn settle_transient_edits(&self) -> Settled {
710        settle(&self.doc)
711    }
712
713    /// Run `edit` as a transient edit, written to the store inside a transient write.
714    ///
715    /// The write is kept when the edit changed the document's positions, which it logs into
716    /// the layer as it moves the cursors (see `TransientLayer::record`), and undone when it
717    /// did not: the store then goes back to where the edit found it, and the layer is let go
718    /// when the edit opened it. So the store and the layer stay in step whatever happens:
719    /// an error before the change was made (a refused selection, a failed half of a
720    /// replacement) leaves the document as it was, and so does a panic there; a panic after
721    /// it (in a syntax highlighter, which runs after the cursors move) keeps the change, as
722    /// a transient edit the layer holds and a revert takes away.
723    fn edit_transiently<R>(
724        &self,
725        edit: impl FnOnce(&mut TextDocumentInner) -> Result<(R, QueuedEvents)>,
726    ) -> Result<R> {
727        let (value, queued) = {
728            let mut inner = self.doc.lock();
729            if inner.is_loading_in_place() {
730                return Err(DocumentError::TransientEdits(
731                    crate::TransientRefusal::LoadInPlace,
732                ));
733            }
734            let store = Arc::clone(inner.ctx.db_context.get_store());
735            let write = store
736                .begin_transient_write()
737                .map_err(|refused| DocumentError::TransientEdits(refused.into()))?;
738            let opened = write.opens();
739            if opened {
740                let layer = TransientLayer::over(&inner.cursors);
741                inner.transient = Some(layer);
742            }
743            let changes =
744                |inner: &TextDocumentInner| inner.transient.as_ref().map_or(0, |l| l.steps.len());
745            let changes_before = changes(&inner);
746            let events_before = inner.pending_events.len();
747            let outcome =
748                std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| edit(&mut inner)));
749            if changes(&inner) > changes_before {
750                write.keep();
751                if outcome.is_err() {
752                    inner.announce_kept_changes(changes_before, events_before);
753                }
754            } else {
755                drop(write);
756                if opened {
757                    inner.transient = None;
758                }
759                inner.invalidate_text_cache();
760            }
761            match outcome {
762                Ok(Ok(done)) => done,
763                Ok(Err(error)) => return Err(error),
764                Err(panic) => {
765                    // The change the edit kept goes out now, to the callbacks as well as to
766                    // `poll_events`: the host may catch the panic and edit nothing more. A
767                    // callback's own panic is dropped, so the edit's is the one resumed.
768                    let queued = inner.take_queued_events();
769                    drop(inner);
770                    let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
771                        crate::inner::dispatch_queued_events(queued)
772                    }));
773                    std::panic::resume_unwind(panic);
774                }
775            }
776        };
777        crate::inner::dispatch_queued_events(queued);
778        Ok(value)
779    }
780
781    /// Insert plain text at the cursor, replacing the selection if any, **without recording
782    /// it** in the undo history.
783    ///
784    /// For an input method's composition, shown in the text while it is being made, or any
785    /// tentative text a host shows and then either commits or takes back. The text goes in
786    /// as [`insert_text`](Self::insert_text) puts it, with the format of the text before it,
787    /// and the cursor is left after it. The document announces the change as it does every
788    /// edit ([`DocumentEvent::ContentsChanged`], and the block and flow events when they
789    /// apply), so views lay it out and draw it; it announces no
790    /// [`DocumentEvent::TextInserted`], since nothing has arrived yet, no
791    /// [`DocumentEvent::UndoRedoChanged`], since the history has not moved, and leaves
792    /// [`is_modified`](crate::TextDocument::is_modified) as it was.
793    ///
794    /// Nothing is pushed on the undo stack, the redo stack is kept, and the next recorded
795    /// edit coalesces with the one before the transient edits as it would have without
796    /// them. To replace the text a composition showed with its next state, select it and
797    /// call this again: [`TextDocument::transient_range`] says where it is.
798    ///
799    /// The edit joins the document's outstanding transient edits, which a revert, a commit
800    /// or any recorded write ends (see the [module documentation](crate::transient)).
801    ///
802    /// Refused with [`DocumentError::TransientEdits`], the document left as it was, while a
803    /// load in place ([`set_djot`](crate::TextDocument::set_djot) and its siblings) is still
804    /// writing the document, and when the selection crosses a table's cells or holds part
805    /// of a table and text outside it.
806    pub fn insert_text_transient(&self, text: &str) -> Result<()> {
807        self.edit_transiently(|inner| {
808            let (pos, anchor) = self.read_cursor();
809            let queued = self.insert_text_locked(
810                inner,
811                pos,
812                anchor,
813                text,
814                ReplaceFormatPolicy::default(),
815                InsertionOrigin::Unspecified,
816                Recording::Transient,
817            )?;
818            Ok(((), queued))
819        })
820    }
821
822    /// As [`insert_text_transient`](Self::insert_text_transient), with a character format,
823    /// as [`insert_formatted_text`](Self::insert_formatted_text) inserts it. Refused as
824    /// `insert_text_transient` is.
825    pub fn insert_formatted_text_transient(&self, text: &str, format: &TextFormat) -> Result<()> {
826        self.edit_transiently(|inner| {
827            let (pos, anchor) = self.read_cursor();
828            let queued = self.insert_formatted_text_locked(
829                inner,
830                pos,
831                anchor,
832                text,
833                format,
834                InsertionOrigin::Unspecified,
835                Recording::Transient,
836            )?;
837            Ok(((), queued))
838        })
839    }
840
841    /// As [`insert_text_transient`](Self::insert_text_transient), with `format` merged into
842    /// the inserted text: the text takes the format it inherits, as typed text does, and
843    /// every field `format` sets replaces that field of it, the others staying inherited.
844    /// For a composition shown in the format the writer toggled on the caret before it
845    /// (Bold with nothing selected), where
846    /// [`insert_formatted_text_transient`](Self::insert_formatted_text_transient) would also
847    /// set the fields left unset (the font family and size among them).
848    ///
849    /// One transient edit, refused as `insert_text_transient` is and reverted, committed or
850    /// ended by a recorded write in the same way. The merged format is part of what the
851    /// transient edits show and goes with them: a commit records the text it is given in
852    /// the format it inherits, and a host that wants the format recorded merges it into the
853    /// committed text in the same edit block
854    /// ([`begin_edit_block`](Self::begin_edit_block)).
855    pub fn insert_text_transient_merged(&self, text: &str, format: &TextFormat) -> Result<()> {
856        self.edit_transiently(|inner| {
857            let (pos, anchor) = self.read_cursor();
858            let queued = self.insert_text_merging_locked(
859                inner,
860                pos,
861                anchor,
862                text,
863                ReplaceFormatPolicy::default(),
864                Some(format),
865                InsertionOrigin::Unspecified,
866                Recording::Transient,
867            )?;
868            Ok(((), queued))
869        })
870    }
871
872    /// Remove the selected text **without recording it** in the undo history. Returns the
873    /// removed text; nothing happens without a selection.
874    ///
875    /// As [`remove_selected_text`](Self::remove_selected_text) removes it, announced and
876    /// refused as [`insert_text_transient`](Self::insert_text_transient) is, and recorded no
877    /// more. The removed text may be recorded text: an input method that converts a
878    /// committed syllable (Korean Hanja conversion, a reconversion in Japanese) takes it out
879    /// transiently, shows its candidates in its place, and the commit then records the
880    /// whole replacement as one step, which an undo takes back to the syllable.
881    pub fn remove_selected_text_transient(&self) -> Result<String> {
882        self.edit_transiently(|inner| {
883            let (pos, anchor) = self.read_cursor();
884            if pos == anchor {
885                return Ok((String::new(), inner.take_queued_events()));
886            }
887            self.remove_locked(inner, pos, anchor, Recording::Transient)
888        })
889    }
890
891    /// Commit the outstanding transient edits as `text`, recorded as **one undo step of its
892    /// own**.
893    ///
894    /// The transient edits are reverted, and the text they changed in the recorded document
895    /// (see [`TextDocument::transient_range`]) is replaced with `text`: after a composition
896    /// inserted transiently, `text` goes in where it was shown, over the text the
897    /// composition took the place of; after a transient removal of recorded text (a
898    /// syllable an input method converts), it replaces that text, so an undo gives it back.
899    /// The cursor is left after `text`.
900    ///
901    /// The step is closed on both sides, as
902    /// [`break_undo_merge`](crate::TextDocument::break_undo_merge) closes one: it does not
903    /// coalesce with the typing before the composition, and what is typed after it starts a
904    /// step of its own, so an undo takes back exactly the committed text. Inside an open
905    /// edit block, the commit joins the block instead. A replaced range within one block
906    /// entirely in one format keeps it ([`ReplaceFormatPolicy::PreserveIfFullyCovered`]);
907    /// inserted text, and text replacing a range across blocks, takes the format of the text
908    /// before it, as typed text does.
909    ///
910    /// With no transient edits outstanding, `text` replaces the cursor's selection, or goes
911    /// in at the cursor, as the same one closed step. An empty `text` records the removal
912    /// of the recorded text the transient edits had replaced (or of the selection, with
913    /// none outstanding); when there is none it records nothing and, like a cancel
914    /// ([`TextDocument::revert_transient_edits`]), closes no step.
915    ///
916    /// On an error from the recorded half, the transient edits are reverted all the same and
917    /// nothing is recorded, but the step before them is closed already: the typing on either
918    /// side of the failed commit no longer coalesces.
919    ///
920    /// Reports [`InsertionOrigin::Unspecified`], as
921    /// [`insert_text`](Self::insert_text) does. Use
922    /// [`commit_transient_text_with_origin`](Self::commit_transient_text_with_origin) to say,
923    /// [`InsertionOrigin::Composed`] for an input method.
924    ///
925    /// Refused with [`DocumentError::TransientEdits`], the transient edits left as they
926    /// were, when they changed the document in more than one place: the recorded text
927    /// between them would be replaced too.
928    pub fn commit_transient_text(&self, text: &str) -> Result<()> {
929        self.commit_transient_text_with_origin(text, InsertionOrigin::Unspecified)
930    }
931
932    /// As [`commit_transient_text`](Self::commit_transient_text), saying which channel the
933    /// text came through (see [`insert_text_with_origin`](Self::insert_text_with_origin)).
934    pub fn commit_transient_text_with_origin(
935        &self,
936        text: &str,
937        origin: InsertionOrigin,
938    ) -> Result<()> {
939        let (result, rest) = {
940            let mut inner = self.doc.lock();
941            let range = match inner.transient.as_ref() {
942                Some(layer) if layer.scattered => {
943                    return Err(DocumentError::TransientEdits(
944                        crate::TransientRefusal::CommitInSeveralPlaces,
945                    ));
946                }
947                Some(TransientLayer {
948                    span: Some(span), ..
949                }) => Some((span.start, span.recorded_end)),
950                _ => None,
951            };
952            inner.revert_transient_edits();
953            // Read after the revert, which moved it back into the recorded text.
954            let (start, end) = range.unwrap_or_else(|| self.read_cursor());
955            // Nothing to record is a cancel, which closes no step: the typing on either side
956            // coalesces as it would have.
957            let records = !text.is_empty() || start != end;
958            let stack = Some(inner.stack_id);
959            if records {
960                undo_redo_commands::seal_head(&inner.ctx, stack);
961            }
962            let result = if !text.is_empty() {
963                self.insert_text_locked(
964                    &mut inner,
965                    start,
966                    end,
967                    text,
968                    ReplaceFormatPolicy::PreserveIfFullyCovered,
969                    origin,
970                    Recording::History,
971                )
972            } else if start != end {
973                self.remove_locked(&mut inner, start, end, Recording::History)
974                    .map(|(_, queued)| queued)
975            } else {
976                Ok(Vec::new())
977            };
978            if records {
979                undo_redo_commands::seal_head(&inner.ctx, stack);
980            }
981            // What is still queued: the revert's events when the recorded half did not take
982            // them with its own.
983            (result, inner.take_queued_events())
984        };
985        match result {
986            Ok(mut queued) => {
987                queued.extend(rest);
988                crate::inner::dispatch_queued_events(queued);
989                Ok(())
990            }
991            Err(error) => {
992                crate::inner::dispatch_queued_events(rest);
993                Err(error)
994            }
995        }
996    }
997
998    /// Where the cursor's position is in the document as recorded: where
999    /// [`TextDocument::revert_transient_edits`] would put it. Its
1000    /// [`position`](Self::position) when no transient edits are outstanding.
1001    ///
1002    /// For a view that shows the recorded document
1003    /// ([`TextDocument::snapshot_recorded_flow_masked`]) to draw this cursor on the text it
1004    /// shows. Read with [`recorded_anchor`](Self::recorded_anchor), a selection holds the
1005    /// same recorded text the revert leaves it holding.
1006    pub fn recorded_position(&self) -> usize {
1007        self.recorded_stand().position
1008    }
1009
1010    /// Where the cursor's anchor is in the document as recorded, as
1011    /// [`recorded_position`](Self::recorded_position) says of its position.
1012    pub fn recorded_anchor(&self) -> usize {
1013        self.recorded_stand().anchor
1014    }
1015
1016    fn recorded_stand(&self) -> Stand {
1017        let inner = self.doc.lock();
1018        let now = Stand::of(&self.data.lock());
1019        match inner.transient.as_ref() {
1020            Some(layer) => layer.stand_after_revert(&Arc::downgrade(&self.data), now),
1021            None => now,
1022        }
1023    }
1024}
1025
1026impl TextDocument {
1027    /// Revert the outstanding transient edits before a recorded write (see [`settle`]).
1028    pub(crate) fn settle_transient_edits(&self) -> Settled {
1029        settle(&self.inner)
1030    }
1031
1032    /// Whether transient edits are outstanding (see
1033    /// [`TextCursor::insert_text_transient`]): the document shows text its history does not
1034    /// hold, which a revert takes away.
1035    pub fn has_transient_edits(&self) -> bool {
1036        self.inner.lock().transient.is_some()
1037    }
1038
1039    /// Which layer of transient edits is outstanding, `None` when none is: the same from the
1040    /// first transient edit to the end of the layer, and another for the next one.
1041    ///
1042    /// For a view that shows only the transient edits it made (an input method's
1043    /// composition belongs to the view the writer types in): it notes the layer its edit
1044    /// began or joined, and the layer is its own while this still names it. A recorded
1045    /// write that reverts the composition, and transient edits someone else makes after it,
1046    /// make another layer, which [`has_transient_edits`](Self::has_transient_edits) alone
1047    /// cannot tell from the view's own.
1048    pub fn transient_layer(&self) -> Option<TransientLayerId> {
1049        self.inner.lock().transient.as_ref().map(|layer| layer.id)
1050    }
1051
1052    /// Where the outstanding transient edits are, in the document as it is: the smallest
1053    /// range outside of which the document is as recorded. `None` when there are none.
1054    ///
1055    /// After a composition inserted transiently, the composition's text, which the next
1056    /// update selects to replace. After a transient removal and nothing else, an empty
1057    /// range where the text was. The range is the one
1058    /// [`TextCursor::commit_transient_text`] replaces, read in the document with the
1059    /// transient edits in place.
1060    pub fn transient_range(&self) -> Option<Range<usize>> {
1061        let inner = self.inner.lock();
1062        let span = inner.transient.as_ref()?.span?;
1063        Some(span.start..span.end)
1064    }
1065
1066    /// Revert the outstanding transient edits, recording nothing: the document is back to
1067    /// its recorded content, as it was before the first of them, and the undo and redo
1068    /// histories are as they were. Returns whether there were any.
1069    ///
1070    /// What cancelling a composition calls. Every cursor goes back into the recorded text,
1071    /// as the [module documentation](crate::transient#positions) says: the cursor that showed
1072    /// a composition, left after it, lands after the text the composition took the place of.
1073    /// The change is
1074    /// announced as an edit's is ([`DocumentEvent::ContentsChanged`] over the range that
1075    /// changed, and the block and flow events when they apply), with nothing about the
1076    /// history.
1077    pub fn revert_transient_edits(&self) -> bool {
1078        let queued = {
1079            let mut inner = self.inner.lock();
1080            if inner.revert_transient_edits().is_none() {
1081                return false;
1082            }
1083            inner.take_queued_events()
1084        };
1085        crate::inner::dispatch_queued_events(queued);
1086        true
1087    }
1088
1089    /// Snapshot the main flow as [`snapshot_flow_masked`](Self::snapshot_flow_masked) does,
1090    /// of the document **as recorded**: without the outstanding transient edits, as a revert
1091    /// would leave it. The same snapshot as `snapshot_flow_masked` when none are outstanding,
1092    /// at the same cost.
1093    ///
1094    /// For a view of the document that is not where the transient edits are made: a
1095    /// read-only preview beside the editor an input method composes in shows the text the
1096    /// writer has entered, not the composition. Its positions are those of the recorded
1097    /// document: show a cursor in it at [`TextCursor::recorded_position`] and
1098    /// [`TextCursor::recorded_anchor`], and map a position read off it into the document
1099    /// with [`position_from_recorded`](Self::position_from_recorded).
1100    ///
1101    /// The highlights are the document's own, made for the text as it shows: the ranges a
1102    /// host set ([`set_session_ranges`](Self::set_session_ranges)) and a syntax highlighter's
1103    /// spans. Each is moved back as a revert moves a range, so it lands on the recorded text
1104    /// it marks, and one that marked only transient text marks nothing. Within a paragraph
1105    /// the transient edits changed, the highlighter's spans are still the ones it found in
1106    /// the text with them (a keyword the composition splits stays split) until they end.
1107    pub fn snapshot_recorded_flow_masked(
1108        &self,
1109        mask: &crate::highlight::HighlightMask,
1110    ) -> crate::flow::FlowSnapshot {
1111        self.inner
1112            .lock()
1113            .read_recorded(|inner| crate::document::flow_snapshot_of(inner, mask, false))
1114    }
1115
1116    /// [`snapshot_recorded_flow_masked`](Self::snapshot_recorded_flow_masked) without the
1117    /// paint-only overlay, as [`snapshot_flow_masked_no_paint`](Self::snapshot_flow_masked_no_paint)
1118    /// is to [`snapshot_flow_masked`](Self::snapshot_flow_masked): the accessibility tree of a
1119    /// view that shows the recorded document.
1120    pub fn snapshot_recorded_flow_masked_no_paint(
1121        &self,
1122        mask: &crate::highlight::HighlightMask,
1123    ) -> crate::flow::FlowSnapshot {
1124        self.inner
1125            .lock()
1126            .read_recorded(|inner| crate::document::flow_snapshot_of(inner, mask, true))
1127    }
1128
1129    /// The block at `position` in the document as recorded, snapshot as
1130    /// [`snapshot_block_at_position_masked`](Self::snapshot_block_at_position_masked) does:
1131    /// the incremental relayout of a view that shows the recorded document (see
1132    /// [`snapshot_recorded_flow_masked`](Self::snapshot_recorded_flow_masked)). `position`
1133    /// is one of the recorded document's.
1134    pub fn snapshot_recorded_block_at_position_masked(
1135        &self,
1136        position: usize,
1137        mask: &crate::highlight::HighlightMask,
1138    ) -> Option<crate::flow::BlockSnapshot> {
1139        self.inner
1140            .lock()
1141            .read_recorded(|inner| crate::document::block_snapshot_at(inner, position, mask))
1142    }
1143
1144    /// Where `position`, a position in the document as it is, is in the document as
1145    /// recorded: where a revert would put a caret standing there (see the
1146    /// [module documentation](crate::transient#positions)). Itself when no transient edits
1147    /// are outstanding.
1148    ///
1149    /// For one position a view that shows the recorded document (see
1150    /// [`snapshot_recorded_flow_masked`](Self::snapshot_recorded_flow_masked)) has to place
1151    /// on the text it shows. A cursor's own ends are read with
1152    /// [`TextCursor::recorded_position`] and [`TextCursor::recorded_anchor`] instead: its
1153    /// selection is moved back as a whole, and a cursor that only the transient edits moved
1154    /// goes back where it stood, which at a place where text was only removed is before the
1155    /// text put back, where this puts a caret after it.
1156    pub fn recorded_position(&self, position: usize) -> usize {
1157        match self.inner.lock().transient.as_ref() {
1158            Some(layer) => map_back_through(&layer.splices, position, RangeEnd::Start),
1159            None => position,
1160        }
1161    }
1162
1163    /// Where `recorded`, a position in the document as recorded, is in the document as it
1164    /// is: moved across the outstanding transient edits as they moved every cursor. Itself
1165    /// when none are outstanding.
1166    ///
1167    /// What a view that shows the recorded document (see
1168    /// [`snapshot_recorded_flow_masked`](Self::snapshot_recorded_flow_masked)) puts a cursor
1169    /// at, for a position it reads off its own layout: a click, an assistive technology's
1170    /// selection. Outside the text the transient edits changed, the cursor's
1171    /// [`recorded_position`](TextCursor::recorded_position) is then `recorded` again; at
1172    /// that text's edge or inside it, the cursor lands at its edge.
1173    pub fn position_from_recorded(&self, recorded: usize) -> usize {
1174        match self.inner.lock().transient.as_ref() {
1175            Some(layer) => layer.map_forward(recorded),
1176            None => recorded,
1177        }
1178    }
1179}
1180
1181#[cfg(test)]
1182mod tests {
1183    use super::*;
1184
1185    fn layer(splices: &[(usize, usize, usize)]) -> TransientLayer {
1186        let mut layer = TransientLayer::over(&[]);
1187        for &(at, removed, added) in splices {
1188            layer.record(at, removed, added);
1189        }
1190        layer
1191    }
1192
1193    #[test]
1194    fn a_composition_replaced_at_every_update_is_one_span_over_nothing_recorded() {
1195        // "n" at 3, then "ni", "nih", "nihao" over it.
1196        let layer = layer(&[(3, 0, 1), (3, 1, 2), (3, 2, 3), (3, 3, 5)]);
1197        assert_eq!(
1198            layer.span,
1199            Some(Span {
1200                start: 3,
1201                end: 8,
1202                recorded_end: 3
1203            })
1204        );
1205        assert!(!layer.scattered);
1206    }
1207
1208    #[test]
1209    fn a_removed_syllable_shown_converted_is_one_span_over_the_syllable() {
1210        let layer = layer(&[(7, 1, 0), (7, 0, 1)]);
1211        assert_eq!(
1212            layer.span,
1213            Some(Span {
1214                start: 7,
1215                end: 8,
1216                recorded_end: 8
1217            })
1218        );
1219        assert!(!layer.scattered);
1220    }
1221
1222    #[test]
1223    fn an_edit_touching_the_span_from_before_extends_it() {
1224        // A composition at 5..8, then the two recorded characters before it removed.
1225        let layer = layer(&[(5, 0, 3), (3, 2, 0)]);
1226        assert_eq!(
1227            layer.span,
1228            Some(Span {
1229                start: 3,
1230                end: 6,
1231                recorded_end: 5
1232            })
1233        );
1234        assert!(!layer.scattered);
1235    }
1236
1237    #[test]
1238    fn an_edit_away_from_the_span_scatters_the_layer() {
1239        let layer = layer(&[(3, 0, 2), (10, 0, 1)]);
1240        assert!(layer.scattered);
1241        // The span still bounds both, recorded text between them included.
1242        assert_eq!(
1243            layer.span,
1244            Some(Span {
1245                start: 3,
1246                end: 11,
1247                recorded_end: 8
1248            })
1249        );
1250    }
1251
1252    #[test]
1253    fn a_removal_then_an_insertion_in_its_place_is_one_replacement() {
1254        // "ab한": the syllable taken out, then its candidate shown in its place.
1255        let layer = layer(&[(2, 1, 0), (2, 0, 1)]);
1256        assert_eq!(
1257            layer.splices,
1258            [Splice {
1259                at: 2,
1260                removed: 1,
1261                added: 1
1262            }]
1263        );
1264        assert_eq!(layer.steps.len(), 2);
1265        let reverted = Reverted {
1266            splices: layer.splices.clone(),
1267        };
1268        assert_eq!(
1269            reverted.map_range(2, 3),
1270            (2, 3),
1271            "the candidate is the syllable"
1272        );
1273        assert_eq!(layer.map_forward(3), 3);
1274    }
1275
1276    #[test]
1277    fn changes_that_touch_compose_and_others_do_not() {
1278        let composed = |a: (usize, usize, usize), b: (usize, usize, usize)| {
1279            let splice = |(at, removed, added)| Splice { at, removed, added };
1280            splice(a)
1281                .then(splice(b))
1282                .map(|s| (s.at, s.removed, s.added))
1283        };
1284        // A composition replaced by its next state.
1285        assert_eq!(composed((3, 0, 1), (3, 1, 2)), Some((3, 0, 2)));
1286        // Recorded text before it taken out up to it.
1287        assert_eq!(composed((5, 0, 3), (3, 2, 0)), Some((3, 2, 3)));
1288        // Its last character and two recorded ones after it taken out.
1289        assert_eq!(composed((2, 0, 2), (3, 3, 0)), Some((2, 2, 1)));
1290        // Recorded text right after it taken out.
1291        assert_eq!(composed((2, 0, 2), (4, 2, 0)), Some((2, 2, 2)));
1292        // Elsewhere.
1293        assert_eq!(composed((2, 0, 2), (5, 0, 1)), None);
1294        assert_eq!(composed((5, 0, 2), (1, 2, 0)), None);
1295    }
1296
1297    #[test]
1298    fn a_change_of_nothing_is_not_recorded() {
1299        let layer = layer(&[(4, 0, 0)]);
1300        assert!(layer.splices.is_empty());
1301        assert_eq!(layer.span, None);
1302    }
1303
1304    #[test]
1305    fn mapping_back_undoes_every_change_in_reverse() {
1306        let reverted = Reverted {
1307            splices: vec![
1308                Splice {
1309                    at: 3,
1310                    removed: 0,
1311                    added: 1,
1312                },
1313                Splice {
1314                    at: 3,
1315                    removed: 1,
1316                    added: 5,
1317                },
1318            ],
1319        };
1320        // Before the composition, inside it, at its end, and after it.
1321        for end in [RangeEnd::Start, RangeEnd::End] {
1322            let map = |position| map_back_through(&reverted.splices, position, end);
1323            assert_eq!(map(2), 2);
1324            assert_eq!(map(5), 3);
1325            assert_eq!(map(8), 3);
1326            assert_eq!(map(12), 7);
1327        }
1328    }
1329
1330    #[test]
1331    fn a_range_starting_where_text_was_removed_starts_after_it_again() {
1332        // "hello" with "ll" (2..4) removed: "heo".
1333        let reverted = Reverted {
1334            splices: vec![Splice {
1335                at: 2,
1336                removed: 2,
1337                added: 0,
1338            }],
1339        };
1340        // The "o", live 2..3, is recorded 4..5; "he", live 0..2, is recorded 0..2.
1341        assert_eq!(reverted.map_range(2, 3), (4, 5));
1342        assert_eq!(reverted.map_range(0, 2), (0, 2));
1343        // A range across the removal holds what was removed as well.
1344        assert_eq!(reverted.map_range(1, 3), (1, 5));
1345    }
1346
1347    /// A recorded edit with a selection that finds transient edits made since its revert
1348    /// (another thread's, between the revert and its lock) is refused, and leaves an edit
1349    /// block it is part of whole.
1350    #[test]
1351    fn a_recorded_edit_finding_a_layer_keeps_the_edit_block_whole() {
1352        let doc = TextDocument::new();
1353        doc.set_plain_text("hello world").unwrap();
1354        doc.clear_undo_redo();
1355        let cursor = doc.cursor_at(0);
1356        cursor.begin_edit_block();
1357        cursor.insert_text("A").unwrap();
1358        // The other thread's transient edit, after this edit's revert.
1359        doc.cursor_at(3).insert_text_transient("x").unwrap();
1360        let refused = {
1361            let mut inner = doc.inner.lock();
1362            cursor.insert_text_locked(
1363                &mut inner,
1364                7,
1365                12,
1366                "b",
1367                ReplaceFormatPolicy::default(),
1368                InsertionOrigin::Unspecified,
1369                Recording::History,
1370            )
1371        };
1372        assert!(matches!(
1373            refused,
1374            Err(DocumentError::TransientEdits(
1375                crate::TransientRefusal::LayerOutstanding
1376            ))
1377        ));
1378        cursor.end_edit_block();
1379        doc.revert_transient_edits();
1380        assert_eq!(doc.to_plain_text().unwrap(), "Ahello world");
1381        doc.undo().unwrap();
1382        assert_eq!(doc.to_plain_text().unwrap(), "hello world");
1383        assert!(!doc.can_undo());
1384    }
1385
1386    /// A transient edit while a write is open on the store (the one this crate leaves open
1387    /// across its calls is a load in place, refused earlier) is the store's refusal, with
1388    /// nothing changed, and is made once the write has ended.
1389    #[test]
1390    fn a_transient_edit_over_an_open_write_is_refused_by_the_store() {
1391        let doc = TextDocument::new();
1392        doc.set_plain_text("abc").unwrap();
1393        let db = doc.inner.lock().ctx.db_context.clone();
1394        let transaction =
1395            common::database::transactions::Transaction::begin_write_transaction(&db).unwrap();
1396        let refused = doc.cursor_at(1).insert_text_transient("n");
1397        assert!(matches!(
1398            refused,
1399            Err(DocumentError::TransientEdits(
1400                crate::TransientRefusal::WriteInProgress
1401            ))
1402        ));
1403        assert!(!doc.has_transient_edits());
1404        assert_eq!(doc.to_plain_text().unwrap(), "abc");
1405        drop(transaction);
1406        doc.cursor_at(1).insert_text_transient("n").unwrap();
1407        assert_eq!(doc.to_plain_text().unwrap(), "anbc");
1408    }
1409
1410    #[test]
1411    fn a_range_that_held_only_transient_text_comes_back_empty() {
1412        let reverted = Reverted {
1413            splices: vec![Splice {
1414                at: 5,
1415                removed: 0,
1416                added: 3,
1417            }],
1418        };
1419        assert_eq!(reverted.map_range(5, 8), (5, 5));
1420        assert_eq!(reverted.map_range(6, 7), (5, 5));
1421    }
1422}