Skip to main content

text_document/
cursor.rs

1//! TextCursor implementation — Qt-style multi-cursor with automatic position adjustment.
2
3use std::sync::Arc;
4
5use parking_lot::Mutex;
6
7use crate::{DocumentError, Result};
8
9use crate::ListStyle;
10use frontend::commands::{
11    document_editing_commands, document_formatting_commands, document_inspection_commands,
12    undo_redo_commands,
13};
14
15use unicode_segmentation::UnicodeSegmentation;
16
17use crate::convert::{to_i64, to_usize};
18use crate::events::{DocumentEvent, InsertionOrigin};
19use crate::flow::{CellRange, FlowElement, FrameRef, SelectionKind, TableCellRef};
20use crate::fragment::DocumentFragment;
21use crate::inner::{CursorData, QueuedEvents, TextDocumentInner};
22use crate::link_extent::LinkExtent;
23use crate::text_block::TextBlock;
24use crate::text_table::TextTable;
25use crate::{BlockFormat, FrameFormat, MoveMode, MoveOperation, SelectionType, TextFormat};
26
27use crate::document::get_main_frame_id;
28
29/// Whether an edit goes into the document's undo history or is a transient edit, which
30/// nothing records (see [`TextCursor::insert_text_transient`]).
31#[derive(Debug, Clone, Copy, PartialEq, Eq)]
32pub(crate) enum Recording {
33    History,
34    Transient,
35}
36
37impl Recording {
38    /// The undo stack the edit's commands go to: the document's own, or none at all.
39    fn stack(self, inner: &TextDocumentInner) -> Option<u64> {
40        match self {
41            Recording::History => Some(inner.stack_id),
42            Recording::Transient => Some(common::undo_redo::UNTRACKED_STACK_ID),
43        }
44    }
45}
46
47/// A transient edit must change exactly the positions it was asked to: `[pos, anchor)`
48/// replaced by what it inserted, which is what a revert maps the cursors back through and
49/// what a commit replaces. A range across a table's cells empties them instead, and one
50/// holding part of a table and text outside it takes the whole table: both are refused
51/// (the store goes back as it was, see `TextCursor::edit_transiently`).
52fn check_transient_change(
53    recording: Recording,
54    pos: usize,
55    anchor: usize,
56    removed: usize,
57) -> Result<()> {
58    if recording == Recording::Transient && removed != pos.max(anchor) - pos.min(anchor) {
59        return Err(DocumentError::TransientEdits(
60            crate::TransientRefusal::CrossesTableCells,
61        ));
62    }
63    Ok(())
64}
65
66/// Whether the main text holds nothing but one empty paragraph, whatever the bodies of the
67/// footnotes after it hold.
68fn main_text_is_empty(inner: &TextDocumentInner) -> bool {
69    let store = inner.ctx.db_context.get_store();
70    match common::database::rope_helpers::main_text_end(store) {
71        Some(end) => end == 0,
72        None => max_cursor_position_of(inner) == Some(0),
73    }
74}
75
76/// The maximum valid cursor position.
77///
78/// Cursor positions are rope positions whenever the rope is the document's position
79/// space (see `rope_helpers::rope_positions_match_flow`), and the rope's length is then
80/// the end. It holds every block separator and, around a table, the anchor sentinel and
81/// the separator after it — two positions the two counts the `Document` entity carries
82/// never see. An end computed from those counts stopped two short of the last characters
83/// after a table: no caret could reach them, and a selection to End left them behind.
84///
85/// Where the rope is not the position space the counts still serve: positions include
86/// block separators (one between each pair of adjacent blocks) but `character_count` does
87/// not, so the max position is `character_count + (block_count - 1)`.
88///
89/// It used to take a `DocumentStatsDto`, which meant every clamp on this path —
90/// and it is reached by every move, every insert and every delete — ran
91/// `get_document_stats`, whose other fields cost a walk over every block of the
92/// document, materialising each one's text out of the rope to whitespace-split a
93/// word count nothing here reads. See [`crate::inner::document_counts`].
94///
95/// `None` only when the document entity cannot be read, so each caller keeps the
96/// fallback position it already chose for that case rather than being handed a
97/// zero that reads as an empty document.
98pub(crate) fn max_cursor_position_of(inner: &TextDocumentInner) -> Option<usize> {
99    let store = inner.ctx.db_context.get_store();
100    if common::database::rope_helpers::rope_positions_match_flow(store) {
101        return Some(store.rope.read().len_chars());
102    }
103    let (chars, blocks) = crate::inner::document_counts(inner)?;
104    Some(if blocks > 1 {
105        chars + blocks - 1
106    } else {
107        chars
108    })
109}
110
111/// Delete `[pos, anchor)` (either order) and say how many positions went: the
112/// document's length before the deletion less its length after.
113///
114/// That is not always the selection's length. Backspace or Delete across the
115/// boundary of a table joins nothing and removes nothing, and a range across
116/// cells empties the cells it touches rather than taking out the positions
117/// between its ends. Reporting the selection's length for those moved every
118/// other cursor on the document back by characters that were still there, and
119/// told listeners about a change that never happened.
120///
121/// A `selection` is removed as it is copied: with one end in a table and the
122/// other outside it, it takes the whole table (see [`whole_tables_selected`]).
123/// Backspace and Delete of one character are not selections: at a table's edge
124/// they take nothing.
125fn measured_delete(
126    inner: &TextDocumentInner,
127    pos: usize,
128    anchor: usize,
129    selection: bool,
130    recording: Recording,
131) -> Result<(frontend::document_editing::DeleteTextResultDto, usize)> {
132    let (pos, anchor) = if selection {
133        whole_tables_selected(inner, pos, anchor)
134    } else {
135        (pos, anchor)
136    };
137    let before = max_cursor_position_of(inner);
138    let dto = frontend::document_editing::DeleteTextDto {
139        position: to_i64(pos),
140        anchor: to_i64(anchor),
141    };
142    let result =
143        match document_editing_commands::delete_text(&inner.ctx, recording.stack(inner), &dto) {
144            Ok(result) => result,
145            // Refused because it would remove nothing, so that no undo entry
146            // records it: an edit that removed nothing, the caret where the use
147            // case put it.
148            Err(error) => match error.downcast_ref::<frontend::document_editing::NothingToDelete>()
149            {
150                Some(nothing) => {
151                    return Ok((
152                        frontend::document_editing::DeleteTextResultDto {
153                            new_position: nothing.new_position,
154                            deleted_text: String::new(),
155                        },
156                        0,
157                    ));
158                }
159                None => return Err(error.into()),
160            },
161        };
162    let removed = match (before, max_cursor_position_of(inner)) {
163        (Some(before), Some(after)) => before.saturating_sub(after),
164        // The counts could not be read: the selection's length, as before.
165        _ => pos.max(anchor) - pos.min(anchor),
166    };
167    Ok((result, removed))
168}
169
170/// `[pos, anchor)` (either order), from its start to its end, as a copy or a removal of a
171/// selection takes it: holding whole every table it has one end in and the other end
172/// outside of (see `rope_helpers::take_whole_tables`). The table trap of
173/// [`TextCursor::set_position`] leaves every selection a writer drags or extends so already;
174/// one another cursor's edit moved into a table, or a range a caller hands to
175/// [`TextCursor::replace`], is read the same way.
176fn whole_tables_selected(inner: &TextDocumentInner, pos: usize, anchor: usize) -> (usize, usize) {
177    let (start, end) = common::database::rope_helpers::take_whole_tables(
178        inner.ctx.db_context.get_store(),
179        to_i64(pos.min(anchor)),
180        to_i64(pos.max(anchor)),
181    );
182    (to_usize(start), to_usize(end))
183}
184
185/// Delete `[pos, anchor)` (either order), then run `insert` where the
186/// deletion left the caret, as one undo entry. Returns what `insert` returned,
187/// how many positions the deletion took (see [`measured_delete`]) and where
188/// the deletion left the caret, which is not always where the range started:
189/// a range that empties a table cell takes the cell's text from its start and
190/// leaves the caret there.
191///
192/// When either half fails, the composite is cancelled, which undoes the half
193/// that ran, and the error is returned with the document as it was. The
194/// composite used to be left open on an error: every later edit of the
195/// document joined it and none reached the undo stack, while the deletion
196/// stayed applied behind a cached text that still showed the selection.
197fn delete_then<R>(
198    inner: &TextDocumentInner,
199    pos: usize,
200    anchor: usize,
201    insert: impl FnOnce(usize) -> Result<R>,
202) -> Result<(R, usize, usize)> {
203    delete_then_as(inner, pos, anchor, Recording::History, insert)
204}
205
206/// [`delete_then`], recorded as `recording` says. A transient edit opens no composite:
207/// nothing records its two halves, and when one fails the transient write it runs in puts
208/// the store back as it found it.
209///
210/// A recorded edit that finds transient edits outstanding is refused before it opens one.
211/// It reverted them before it took the lock, so they were made since, from another thread,
212/// and the store would refuse every write of the composite: opened, it would only be
213/// cancelled again, announcing a group that never held anything.
214fn delete_then_as<R>(
215    inner: &TextDocumentInner,
216    pos: usize,
217    anchor: usize,
218    recording: Recording,
219    insert: impl FnOnce(usize) -> Result<R>,
220) -> Result<(R, usize, usize)> {
221    let grouped = recording == Recording::History;
222    if grouped && inner.transient.is_some() {
223        return Err(DocumentError::TransientEdits(
224            crate::TransientRefusal::LayerOutstanding,
225        ));
226    }
227    if grouped {
228        undo_redo_commands::begin_composite(&inner.ctx, Some(inner.stack_id));
229    }
230    let outcome =
231        measured_delete(inner, pos, anchor, true, recording).and_then(|(deleted, removed)| {
232            let at = to_usize(deleted.new_position);
233            insert(at).map(|value| (value, removed, at))
234        });
235    match outcome {
236        Ok(done) => {
237            if grouped {
238                undo_redo_commands::end_composite(&inner.ctx);
239            }
240            Ok(done)
241        }
242        Err(error) => {
243            if grouped {
244                undo_redo_commands::cancel_composite(&inner.ctx);
245            }
246            Err(error)
247        }
248    }
249}
250
251/// How many positions an edit took away when it put in `added` of them: the
252/// document's length before it (`before`) and `added`, less its length now.
253/// `selection`, the length of the range the edit replaced, when a length
254/// cannot be read.
255///
256/// The selection's length is what it takes only when nothing in the range is
257/// a table: a range that starts on a table's anchor starts in the first cell,
258/// a range across a table empties the cells it touches, and one that holds
259/// a whole table takes it, anchor and all.
260fn removed_since(
261    inner: &TextDocumentInner,
262    before: Option<usize>,
263    added: usize,
264    selection: usize,
265) -> usize {
266    match (before, max_cursor_position_of(inner)) {
267        (Some(before), Some(after)) => (before + added).saturating_sub(after),
268        _ => selection,
269    }
270}
271
272/// What an insertion did to the document's positions: from `at`, `removed`
273/// of them replaced by `added`. Only a paste into a table's cells replaces
274/// anything; every other insertion only adds.
275#[derive(Debug, Clone, Copy)]
276struct Insertion {
277    at: usize,
278    removed: usize,
279    added: usize,
280}
281
282impl Insertion {
283    /// `added` positions put in right before `new_pos`, where the caret was
284    /// left. Where they went in is where the use case resolved the caret,
285    /// which is not always where it was asked to: a caret on a table's
286    /// anchor types in the table's first cell.
287    fn ending_at(new_pos: usize, added: usize) -> Self {
288        Insertion {
289            at: new_pos.saturating_sub(added),
290            removed: 0,
291            added,
292        }
293    }
294}
295
296/// A cursor into a [`TextDocument`](crate::TextDocument).
297///
298/// Multiple cursors can coexist on the same document (like Qt's `QTextCursor`).
299/// When any cursor edits text, all other cursors' positions are automatically
300/// adjusted by the document.
301///
302/// Cloning a cursor creates an **independent** cursor at the same position.
303pub struct TextCursor {
304    pub(crate) doc: Arc<Mutex<TextDocumentInner>>,
305    pub(crate) data: Arc<Mutex<CursorData>>,
306}
307
308impl Clone for TextCursor {
309    fn clone(&self) -> Self {
310        let (position, anchor, content_locale, anchor_in_table) = {
311            let d = self.data.lock();
312            (
313                d.position,
314                d.anchor,
315                d.content_locale.clone(),
316                d.anchor_in_table,
317            )
318        };
319        let data = {
320            let mut inner = self.doc.lock();
321            let data = Arc::new(Mutex::new(CursorData {
322                position,
323                anchor,
324                cell_selection_override: None,
325                // A clone reads the same text as its original, so it inherits the language.
326                content_locale,
327                whole_text_selected: false,
328                // The same selection, started where the original's was.
329                anchor_in_table,
330            }));
331            inner.cursors.push(Arc::downgrade(&data));
332            data
333        };
334        TextCursor {
335            doc: self.doc.clone(),
336            data,
337        }
338    }
339}
340
341impl TextCursor {
342    // ── Helpers (called while doc lock is NOT held) ──────────
343
344    pub(crate) fn read_cursor(&self) -> (usize, usize) {
345        let d = self.data.lock();
346        (d.position, d.anchor)
347    }
348
349    /// Common post-edit bookkeeping: adjust all cursors, set this cursor to
350    /// `new_pos`, mark modified, invalidate text cache, queue a
351    /// `ContentsChanged` event, and return the queued events for dispatch.
352    fn finish_edit(
353        &self,
354        inner: &mut TextDocumentInner,
355        edit_pos: usize,
356        removed: usize,
357        inserted: Insertion,
358        new_pos: usize,
359        blocks_affected: usize,
360    ) -> QueuedEvents {
361        self.finish_edit_ext(
362            inner,
363            edit_pos,
364            removed,
365            inserted,
366            new_pos,
367            blocks_affected,
368            true,
369        )
370    }
371
372    #[allow(clippy::too_many_arguments)]
373    fn finish_edit_ext(
374        &self,
375        inner: &mut TextDocumentInner,
376        edit_pos: usize,
377        removed: usize,
378        inserted: Insertion,
379        new_pos: usize,
380        blocks_affected: usize,
381        flow_may_change: bool,
382    ) -> QueuedEvents {
383        self.finish_edit_from(
384            inner,
385            edit_pos,
386            removed,
387            inserted,
388            new_pos,
389            blocks_affected,
390            flow_may_change,
391            InsertionOrigin::Unspecified,
392        )
393    }
394
395    /// As [`finish_edit_ext`](Self::finish_edit_ext), and additionally reports
396    /// which channel the text arrived through.
397    ///
398    /// ⚠ **The one place an origin is turned into an event.** Every insertion
399    /// method reaches this, so the origin travels through one path rather than
400    /// through each method's own idea of what it did — which is what keeps
401    /// `TextInserted` and `ContentsChanged` describing the same edit instead of
402    /// two edits that happen to coincide.
403    ///
404    /// `removed` positions went from `edit_pos` on, then `inserted` changed
405    /// the document, and this cursor goes to `new_pos`. What was added does
406    /// not always start at `edit_pos` (a deletion that empties a table cell
407    /// puts the caret at the cell's start, see [`delete_then`]), and the caret
408    /// does not always follow it (a pasted table leaves the caret in front of
409    /// it): counting what was added from `edit_pos` to the caret moved every
410    /// other cursor by the difference.
411    #[allow(clippy::too_many_arguments)]
412    fn finish_edit_from(
413        &self,
414        inner: &mut TextDocumentInner,
415        edit_pos: usize,
416        removed: usize,
417        inserted: Insertion,
418        new_pos: usize,
419        blocks_affected: usize,
420        flow_may_change: bool,
421        origin: InsertionOrigin,
422    ) -> QueuedEvents {
423        self.finish_edit_as(
424            inner,
425            edit_pos,
426            removed,
427            inserted,
428            new_pos,
429            blocks_affected,
430            flow_may_change,
431            origin,
432            Recording::History,
433        )
434    }
435
436    /// As [`finish_edit_from`](Self::finish_edit_from), for an edit recorded as
437    /// `recording` says. A transient edit moves the cursors and announces the change as
438    /// any edit does, and leaves alone what only a recorded edit changes: the modified
439    /// flag, [`DocumentEvent::TextInserted`] (nothing has arrived: the text is shown, not
440    /// entered) and [`DocumentEvent::UndoRedoChanged`] (the history has not moved).
441    #[allow(clippy::too_many_arguments)]
442    fn finish_edit_as(
443        &self,
444        inner: &mut TextDocumentInner,
445        edit_pos: usize,
446        removed: usize,
447        inserted: Insertion,
448        new_pos: usize,
449        blocks_affected: usize,
450        flow_may_change: bool,
451        origin: InsertionOrigin,
452        recording: Recording,
453    ) -> QueuedEvents {
454        let recorded = recording == Recording::History;
455        // Defensive: a use case can return new_position < edit_pos when
456        // invoked through a stale or out-of-range cursor (e.g. after an
457        // undo restores a state where the previously-saved cursor position
458        // is no longer valid — fuzz finds this). Treat the edit as adding
459        // 0 chars rather than overflowing; the cursor still moves to
460        // `new_pos` below.
461        let Insertion {
462            at: inserted_at,
463            removed: replaced,
464            added,
465        } = inserted;
466        if inserted_at > edit_pos || replaced > 0 {
467            // The text went in past where the deletion was (a table pasted
468            // into a paragraph goes in after it), or it replaced text of its
469            // own (a table pasted into cells): the cursors between stay in
470            // front of it.
471            inner.adjust_cursors(edit_pos, removed, 0);
472            inner.adjust_cursors(inserted_at, replaced, added);
473        } else {
474            inner.adjust_cursors(inserted_at, removed, added);
475        }
476        let removed = removed + replaced;
477        let edit_pos = edit_pos.min(inserted_at);
478        {
479            let mut d = self.data.lock();
480            d.position = new_pos;
481            d.anchor = new_pos;
482            d.whole_text_selected = false;
483            d.anchor_in_table = None;
484        }
485        if recorded {
486            inner.modified = true;
487        }
488        inner.invalidate_text_cache();
489        inner.rehighlight_affected(edit_pos);
490        inner.queue_event(DocumentEvent::ContentsChanged {
491            position: edit_pos,
492            chars_removed: removed,
493            chars_added: added,
494            blocks_affected,
495        });
496        // Only when something was actually inserted. An edit that only deletes
497        // has no origin to report, and emitting one with `chars_inserted: 0`
498        // would put a channel's name on text that never arrived.
499        if added > 0 && recorded {
500            inner.queue_event(DocumentEvent::TextInserted {
501                position: inserted_at,
502                chars_inserted: added,
503                origin,
504            });
505        }
506        inner.check_block_count_changed();
507        if flow_may_change {
508            inner.check_flow_changed();
509        }
510        if recorded {
511            self.queue_undo_redo_event(inner)
512        } else {
513            inner.take_queued_events()
514        }
515    }
516
517    // ── Position & selection ─────────────────────────────────
518
519    /// Current cursor position (between characters).
520    pub fn position(&self) -> usize {
521        self.data.lock().position
522    }
523
524    /// Anchor position. Equal to `position()` when no selection.
525    pub fn anchor(&self) -> usize {
526        self.data.lock().anchor
527    }
528
529    /// Returns true if there is a selection.
530    pub fn has_selection(&self) -> bool {
531        let d = self.data.lock();
532        d.position != d.anchor
533    }
534
535    /// Start of the selection (min of position and anchor).
536    pub fn selection_start(&self) -> usize {
537        let d = self.data.lock();
538        d.position.min(d.anchor)
539    }
540
541    /// End of the selection (max of position and anchor).
542    pub fn selection_end(&self) -> usize {
543        let d = self.data.lock();
544        d.position.max(d.anchor)
545    }
546
547    /// Get the selected text. Returns empty string if no selection.
548    pub fn selected_text(&self) -> Result<String> {
549        let (pos, anchor) = self.read_cursor();
550        if pos == anchor {
551            return Ok(String::new());
552        }
553        let start = pos.min(anchor);
554        let len = pos.max(anchor) - start;
555        let inner = self.doc.lock();
556        let dto = frontend::document_inspection::GetTextAtPositionDto {
557            position: to_i64(start),
558            length: to_i64(len),
559        };
560        let result = document_inspection_commands::get_text_at_position(&inner.ctx, &dto)?;
561        Ok(result.text)
562    }
563
564    /// Up to `max_len` characters of plain text immediately preceding the cursor position,
565    /// bounded and read directly from the store — the same fast block lookup
566    /// [`char_format`](Self::char_format) uses, never materializing the whole document the
567    /// way [`selected_text`](Self::selected_text)'s
568    /// `document_inspection_commands::get_text_at_position` does internally. Block
569    /// boundaries appear as `'\n'`. Returns fewer than `max_len` characters near the start of
570    /// the document.
571    ///
572    /// Falls back to the (correct, but O(document size)) slow path for documents containing
573    /// tables or unmirrored sub-frames, where the fast rope-index lookup doesn't apply — see
574    /// [`common::database::rope_helpers::find_block_at_char_position`]'s own doc comment for
575    /// exactly which documents that is.
576    pub fn text_before(&self, max_len: usize) -> Result<String> {
577        if max_len == 0 {
578            return Ok(String::new());
579        }
580        let pos = self.position();
581        let inner = self.doc.lock();
582        let store = inner.ctx.db_context.get_store();
583
584        // One O(log n) probe decides whether the fast path even applies to this document —
585        // same gate `find_block_at_char_position` itself uses (tables / unmirrored
586        // sub-frames disqualify it). Cheaper to check once up front than to discover it mid
587        // walk.
588        if pos > 0
589            && common::database::rope_helpers::find_block_at_char_position(store, 0).is_none()
590        {
591            let dto = frontend::document_inspection::GetTextAtPositionDto {
592                position: 0,
593                length: to_i64(pos),
594            };
595            let result = document_inspection_commands::get_text_at_position(&inner.ctx, &dto)?;
596            let full = result.text;
597            let total = full.chars().count();
598            let skip = total.saturating_sub(max_len);
599            return Ok(full.chars().skip(skip).collect());
600        }
601
602        let mut pieces: Vec<String> = Vec::new();
603        let mut remaining = max_len;
604        let mut end_pos = pos;
605
606        while remaining > 0 && end_pos > 0 {
607            let query = (end_pos - 1) as i64;
608            // `find_block_at_char_position` returns the *previous*-block answer at a
609            // boundary (char_in_block == the block's own length), which is exactly the
610            // convention this backward walk needs — unlike `get_block_at_position`'s command,
611            // which deliberately advances to the *next* block at a boundary for its own
612            // (forward/click-mapping) callers.
613            let Some((block_id, char_in_block, block_char_start)) =
614                common::database::rope_helpers::find_block_at_char_position(store, query)
615            else {
616                // A table or sub-frame appeared partway through the walk (shouldn't happen
617                // given the up-front check above, but the primitive's contract only promises
618                // this per-call, not for the whole document) — stop rather than guess.
619                break;
620            };
621            let block_dto = frontend::commands::block_commands::get_block(&inner.ctx, &block_id)?
622                .ok_or_else(|| DocumentError::NotFound("block not found".into()))?;
623            let entity: common::entities::Block = block_dto.into();
624            let block_text =
625                common::database::rope_helpers::block_content_via_store(&entity, store);
626            let block_len = block_text.chars().count() as i64;
627            let block_char_start = block_char_start as usize;
628
629            if char_in_block == block_len {
630                // `query` landed exactly on this (non-empty) block's own trailing separator.
631                pieces.push("\n".to_string());
632                remaining -= 1;
633                if remaining == 0 {
634                    break;
635                }
636                let take = remaining.min(block_len as usize);
637                let local_start = block_len as usize - take;
638                let slice: String = block_text.chars().skip(local_start).take(take).collect();
639                pieces.push(slice);
640                remaining -= take;
641                end_pos = block_char_start + local_start;
642            } else {
643                // `query` is a real character at local index `char_in_block`.
644                let available = char_in_block as usize + 1;
645                let take = remaining.min(available);
646                let local_start = available - take;
647                let slice: String = block_text.chars().skip(local_start).take(take).collect();
648                pieces.push(slice);
649                remaining -= take;
650                end_pos = block_char_start + local_start;
651            }
652        }
653
654        pieces.reverse();
655        Ok(pieces.concat())
656    }
657
658    /// Collapse the selection by moving anchor to position.
659    pub fn clear_selection(&self) {
660        let mut d = self.data.lock();
661        d.anchor = d.position;
662        d.whole_text_selected = false;
663        d.anchor_in_table = None;
664    }
665
666    // ── Boundary queries ─────────────────────────────────────
667    //
668    // Each reads the caret's block (see `caret_block`): at the end of a paragraph, the
669    // paragraph the caret ends, as `current_list` and `TextDocument::block_at_caret` read it.
670
671    /// The block the caret at `position` is in (see `block_at_caret_dto`). At the end of a
672    /// paragraph, the character index is the separator after it, which belongs to the next
673    /// paragraph: the queries of the caret's block that read the block at the character index
674    /// put a caret ending a quoted paragraph out of its quotation, and one ending the
675    /// paragraph before a quotation in it.
676    fn caret_block(
677        inner: &TextDocumentInner,
678        position: usize,
679    ) -> Option<frontend::document_inspection::BlockInfoDto> {
680        crate::inner::block_at_caret_dto(&inner.ctx, position).ok()
681    }
682
683    /// True if the cursor is at the start of a block.
684    pub fn at_block_start(&self) -> bool {
685        let pos = self.position();
686        let inner = self.doc.lock();
687        Self::caret_block(&inner, pos).is_some_and(|info| pos == to_usize(info.block_start))
688    }
689
690    /// True if the cursor is at the end of a block: at the end of every paragraph, not only
691    /// the last one.
692    pub fn at_block_end(&self) -> bool {
693        let pos = self.position();
694        let inner = self.doc.lock();
695        Self::caret_block(&inner, pos)
696            .is_some_and(|info| pos == to_usize(info.block_start) + to_usize(info.block_length))
697    }
698
699    /// True if the cursor is at position 0.
700    pub fn at_start(&self) -> bool {
701        self.data.lock().position == 0
702    }
703
704    /// True if the cursor is at the very end of the document.
705    pub fn at_end(&self) -> bool {
706        let pos = self.position();
707        let inner = self.doc.lock();
708        pos >= max_cursor_position_of(&inner).unwrap_or(0)
709    }
710
711    /// The block number (0-indexed) containing the cursor.
712    pub fn block_number(&self) -> usize {
713        let pos = self.position();
714        let inner = self.doc.lock();
715        Self::caret_block(&inner, pos).map_or(0, |info| to_usize(info.block_number))
716    }
717
718    /// The cursor's column within the current block (0-indexed): at the end of a paragraph,
719    /// the paragraph's length.
720    pub fn position_in_block(&self) -> usize {
721        let pos = self.position();
722        let inner = self.doc.lock();
723        Self::caret_block(&inner, pos)
724            .map_or(0, |info| pos.saturating_sub(to_usize(info.block_start)))
725    }
726
727    // ── Movement ─────────────────────────────────────────────
728
729    /// Set the cursor to an absolute position.
730    ///
731    /// When extending a selection (`KeepAnchor`) across a table's edge, the
732    /// selection takes the whole table, as LibreOffice and Word take a table a
733    /// selection runs into or out of: partial table selections from outside a
734    /// table are not allowed.
735    ///
736    /// - Moved into a table from outside it, the position goes to the table's
737    ///   edge on the far side: moving forward, to the end of the table's last
738    ///   cell; moving back, to the table's anchor, its start. The selection then
739    ///   spans exactly what its removal takes. It ended at the start of the
740    ///   paragraph after the table, one position more than the removal takes,
741    ///   since the two paragraphs are not joined: an editor moving the selection
742    ///   by its two ends put the text one character before the drop point.
743    /// - Moved out of the table the selection started in, the anchor goes to
744    ///   the table's edge on the far side, so the selection holds the table
745    ///   whole, from its anchor or to the end of its last cell. The cell it
746    ///   started in is remembered: moved back into that table, the selection
747    ///   starts there again.
748    ///
749    /// The selection this leaves is what [`selection`](Self::selection)
750    /// copies and what [`remove_selected_text`](Self::remove_selected_text),
751    /// typing and pasting over it remove: the anchor stayed in the cell, so an
752    /// editor showed the table's cells up to it selected while the copy held
753    /// the whole table, the removal emptied the cells it met, and a cut pasted
754    /// back put the table in twice. The position was moved instead, to the
755    /// other side of the table: a selection from a cell to the end of the
756    /// text removed the table and kept the paragraphs after it.
757    ///
758    /// Nothing snaps when `mode` is `MoveAnchor` (a plain click or move).
759    pub fn set_position(&self, position: usize, mode: MoveMode) {
760        // Clamp to max document position (includes block separators)
761        let end = {
762            let inner = self.doc.lock();
763            max_cursor_position_of(&inner).unwrap_or(0)
764        };
765        let mut pos = position.min(end);
766
767        let mut kept_anchor: Option<(usize, Option<usize>)> = None;
768        if mode == MoveMode::KeepAnchor {
769            // The end the selection was started at, before any table it started in moved
770            // the anchor out to its edge.
771            let fixed = {
772                let d = self.data.lock();
773                d.anchor_in_table.unwrap_or(d.anchor)
774            };
775            let pos_cell = self.table_cell_at(pos);
776            let fixed_cell = self.selection_anchor_cell(fixed, pos_cell.as_ref());
777            let same_table = |one: &TableCellRef, other: &Option<TableCellRef>| {
778                other
779                    .as_ref()
780                    .is_some_and(|other| other.table.id() == one.table.id())
781            };
782            // The position in a table the selection did not start in: at the table's edge,
783            // on the side away from where it started. Going forward, to the end of its last
784            // cell; going back, to the table's anchor, so the selection holds the table and
785            // none of the paragraph before it, which a removal would then join to what is
786            // left of the one it started in.
787            if let Some(moving) = &pos_cell
788                && !same_table(moving, &fixed_cell)
789            {
790                let forward = fixed < pos;
791                pos = self.table_edge(moving.table.id(), forward).unwrap_or(pos);
792            }
793            // The selection started in a table the position is not in: the anchor at the
794            // table's edge, on the side away from the position.
795            let anchor = match &fixed_cell {
796                Some(started_in) if !same_table(started_in, &pos_cell) => {
797                    let table_id = started_in.table.id();
798                    match self.table_edge(table_id, pos < fixed) {
799                        Some(edge) => (edge, Some(fixed)),
800                        None => (fixed, None),
801                    }
802                }
803                _ => (fixed, None),
804            };
805            kept_anchor = Some(anchor);
806        }
807
808        {
809            let mut d = self.data.lock();
810            d.position = pos;
811            match kept_anchor {
812                Some((anchor, anchor_in_table)) => {
813                    d.anchor = anchor;
814                    d.anchor_in_table = anchor_in_table;
815                }
816                None => {
817                    d.anchor = pos;
818                    d.anchor_in_table = None;
819                }
820            }
821            d.cell_selection_override = None;
822            d.whole_text_selected = false;
823        }
824        // Snap forward to the nearest grapheme cluster boundary so
825        // a caller passing an arbitrary scalar index (e.g. computed
826        // from a hit-test or a plain-text search) never leaves the
827        // cursor inside a multi-scalar grapheme cluster.
828        self.snap_position_to_grapheme_boundary();
829    }
830
831    /// Where the table `table_id` ends, `at_end`, or starts, with its anchor, when the rope
832    /// is the document's position space: the edges a selection holding the table whole runs
833    /// from or to.
834    fn table_edge(&self, table_id: usize, at_end: bool) -> Option<usize> {
835        let inner = self.doc.lock();
836        let extent = common::database::rope_helpers::table_extent(
837            inner.ctx.db_context.get_store(),
838            table_id as common::types::EntityId,
839        )?;
840        Some(to_usize(if at_end { extent.end } else { extent.anchor }))
841    }
842
843    /// Move the cursor by a semantic operation.
844    ///
845    /// `n` is used as a repeat count for character-level movements
846    /// (`NextCharacter`, `PreviousCharacter`, `Left`, `Right`).
847    /// For all other operations it is ignored. Returns `true` if the cursor moved.
848    ///
849    /// A move starting in the main text stops at its end: the bodies of the footnote
850    /// definitions a document holds come after it, and no view shows them. A cursor placed
851    /// in a body with [`set_position`](Self::set_position) moves in the bodies freely.
852    ///
853    /// A selection holding a table whole, its moving end at the table's edge (see
854    /// [`set_position`](Self::set_position)), gives the table back when that end steps back
855    /// into it toward where the selection started: the end goes to the table's other side.
856    pub fn move_position(&self, operation: MoveOperation, mode: MoveMode, n: usize) -> bool {
857        let old_pos = self.position();
858        let mut target = self.kept_in_main_text(old_pos, self.resolve_move(operation, n));
859        if mode == MoveMode::KeepAnchor {
860            target = self.past_a_table_given_back(old_pos, target);
861        }
862        self.set_position(target, mode);
863        self.position() != old_pos
864    }
865
866    /// `target`, the moving end of the selection going there from `from`, taken to the side
867    /// of a table nearer where the selection started when the step goes back into a table
868    /// the selection holds whole: `from` stands at the table's edge on the far side, where
869    /// the table trap put it, and the step goes toward the fixed end. The trap moves any
870    /// position in such a table to that far edge, so every step back landed there again,
871    /// and the selection could only grow: the Left or the Up arrow could not give back a
872    /// table the Right or the Down arrow had taken.
873    fn past_a_table_given_back(&self, from: usize, target: usize) -> usize {
874        let fixed = {
875            let d = self.data.lock();
876            d.anchor_in_table.unwrap_or(d.anchor)
877        };
878        let back = (fixed < from && target < from) || (fixed > from && target > from);
879        let no_table = {
880            let inner = self.doc.lock();
881            inner.ctx.db_context.get_store().tables.read().is_empty()
882        };
883        if !back || no_table {
884            return target;
885        }
886        let Some(cell) = self.table_cell_at(target) else {
887            return target;
888        };
889        let started_in_it = self
890            .selection_anchor_cell(fixed, Some(&cell))
891            .is_some_and(|started_in| started_in.table.id() == cell.table.id());
892        if started_in_it {
893            return target;
894        }
895        let (Some(start), Some(end)) = (
896            self.table_edge(cell.table.id(), false),
897            self.table_edge(cell.table.id(), true),
898        ) else {
899            return target;
900        };
901        if fixed < start && from == end {
902            // The end of what comes before the table.
903            start.saturating_sub(1)
904        } else if fixed > end && from == start {
905            // The start of what comes after it.
906            end + 1
907        } else {
908            target
909        }
910    }
911
912    /// `target`, stopped at the end of the main text when a move from `from` in the main
913    /// text would carry the caret past it. No view shows a footnote's body, and the rope
914    /// holds the bodies after the main text: the Right arrow, End or Down from the end of
915    /// the text went into the first note, and typing there edited it unseen. A move
916    /// starting in a body is left alone.
917    fn kept_in_main_text(&self, from: usize, target: usize) -> usize {
918        if target <= from {
919            return target;
920        }
921        let inner = self.doc.lock();
922        let store = inner.ctx.db_context.get_store();
923        match common::database::rope_helpers::main_text_end(store) {
924            Some(end) if from <= to_usize(end) && target > to_usize(end) => to_usize(end),
925            _ => target,
926        }
927    }
928
929    /// Select a region relative to the cursor position.
930    pub fn select(&self, selection: SelectionType) {
931        match selection {
932            SelectionType::Document => {
933                let end = {
934                    let inner = self.doc.lock();
935                    max_cursor_position_of(&inner).unwrap_or(0)
936                };
937                let mut d = self.data.lock();
938                d.anchor = 0;
939                d.position = end;
940                d.cell_selection_override = None;
941                d.whole_text_selected = true;
942                d.anchor_in_table = None;
943            }
944            SelectionType::BlockUnderCursor | SelectionType::LineUnderCursor => {
945                let pos = self.position();
946                let inner = self.doc.lock();
947                // The caret's block: at the end of a paragraph, that paragraph.
948                if let Some(info) = Self::caret_block(&inner, pos) {
949                    let start = to_usize(info.block_start);
950                    let end = start + to_usize(info.block_length);
951                    drop(inner);
952                    let mut d = self.data.lock();
953                    d.anchor = start;
954                    d.position = end;
955                    d.cell_selection_override = None;
956                    d.whole_text_selected = false;
957                    d.anchor_in_table = None;
958                }
959            }
960            SelectionType::WordUnderCursor => {
961                let pos = self.position();
962                let (word_start, word_end) = self.find_word_boundaries(pos);
963                let mut d = self.data.lock();
964                d.anchor = word_start;
965                d.position = word_end;
966                d.cell_selection_override = None;
967                d.whole_text_selected = false;
968                d.anchor_in_table = None;
969            }
970            SelectionType::SentenceUnderCursor => {
971                let pos = self.position();
972                // A block with nothing to point at leaves the cursor where it was, the same way
973                // `WordUnderCursor` collapses to `(pos, pos)` off a word.
974                if let Some((start, end)) = self.find_sentence_boundaries(pos) {
975                    let mut d = self.data.lock();
976                    d.anchor = start;
977                    d.position = end;
978                    d.cell_selection_override = None;
979                    d.whole_text_selected = false;
980                    d.anchor_in_table = None;
981                }
982            }
983        }
984    }
985
986    /// The language this cursor reads its text as, for the sentence operations. A BCP-47-ish
987    /// tag (`"en"`, `"fr-FR"`); `None` — the default — means untailored UAX #29.
988    ///
989    /// Transient, per-cursor and non-persisted: it never reaches an entity, an undo command or
990    /// an export. The enum-driven [`select`](Self::select) / [`move_position`](Self::move_position)
991    /// have nowhere to take a locale argument, so it is set once on the cursor instead —
992    /// [`TextDocument::sentence_at`](crate::TextDocument::sentence_at) takes the same value per
993    /// call for callers that would rather not hold a cursor at all.
994    pub fn set_content_locale(&self, locale: Option<&str>) {
995        self.data.lock().content_locale = locale.map(str::to_string);
996    }
997
998    /// The language set by [`set_content_locale`](Self::set_content_locale).
999    pub fn content_locale(&self) -> Option<String> {
1000        self.data.lock().content_locale.clone()
1001    }
1002
1003    // ── Text editing ─────────────────────────────────────────
1004
1005    /// Insert plain text at the cursor. Replaces selection if any.
1006    ///
1007    /// Reports [`InsertionOrigin::Unspecified`] — the caller did not say. Use
1008    /// [`insert_text_with_origin`](Self::insert_text_with_origin) to say.
1009    pub fn insert_text(&self, text: &str) -> Result<()> {
1010        self.insert_text_with_origin(text, InsertionOrigin::Unspecified)
1011    }
1012
1013    /// Insert plain text at the cursor, saying which channel it came through.
1014    ///
1015    /// The origin reaches consumers as [`DocumentEvent::TextInserted`]. It is a
1016    /// fact about the channel and never about who was at the other end of it.
1017    pub fn insert_text_with_origin(&self, text: &str, origin: InsertionOrigin) -> Result<()> {
1018        let _settled = self.settle_transient_edits();
1019        let (pos, anchor) = self.read_cursor();
1020        let queued = {
1021            let mut inner = self.doc.lock();
1022            self.insert_text_locked(
1023                &mut inner,
1024                pos,
1025                anchor,
1026                text,
1027                Default::default(),
1028                origin,
1029                Recording::History,
1030            )?
1031        };
1032        crate::inner::dispatch_queued_events(queued);
1033        Ok(())
1034    }
1035
1036    /// Insert `text` over `[pos, anchor)` (either order), the document locked, recorded as
1037    /// `recording` says, and leave this cursor after it. `policy` is what the text wears
1038    /// where it replaces formatted text within one block. Returns the events to dispatch.
1039    #[allow(clippy::too_many_arguments)]
1040    pub(crate) fn insert_text_locked(
1041        &self,
1042        inner: &mut TextDocumentInner,
1043        pos: usize,
1044        anchor: usize,
1045        text: &str,
1046        policy: crate::ReplaceFormatPolicy,
1047        origin: InsertionOrigin,
1048        recording: Recording,
1049    ) -> Result<QueuedEvents> {
1050        self.insert_text_merging_locked(inner, pos, anchor, text, policy, None, origin, recording)
1051    }
1052
1053    /// [`insert_text_locked`](Self::insert_text_locked), then `merge` (when given) merged
1054    /// into the inserted text, as part of the same edit: done before the edit is noted, so
1055    /// a refused merge leaves a transient edit undone with the rest of it. Recorded, the
1056    /// merge would be an undo entry of its own: the transient insert is its one caller.
1057    #[allow(clippy::too_many_arguments)]
1058    pub(crate) fn insert_text_merging_locked(
1059        &self,
1060        inner: &mut TextDocumentInner,
1061        pos: usize,
1062        anchor: usize,
1063        text: &str,
1064        policy: crate::ReplaceFormatPolicy,
1065        merge: Option<&TextFormat>,
1066        origin: InsertionOrigin,
1067        recording: Recording,
1068    ) -> Result<QueuedEvents> {
1069        // Try direct insert first (handles same-block selection and no-selection cases)
1070        let dto = frontend::document_editing::InsertTextDto {
1071            format_policy: policy,
1072            position: to_i64(pos),
1073            anchor: to_i64(anchor),
1074            text: text.into(),
1075        };
1076        let stack = recording.stack(inner);
1077        let edit_pos = pos.min(anchor);
1078        let before = max_cursor_position_of(inner);
1079        let result = match document_editing_commands::insert_text(&inner.ctx, stack, &dto) {
1080            Ok(r) => r,
1081            // Cross-block selection: compose delete + insert as a single
1082            // undo unit.
1083            Err(_) if pos != anchor => {
1084                delete_then_as(inner, pos, anchor, recording, |at| {
1085                    let ins_dto = frontend::document_editing::InsertTextDto {
1086                        format_policy: Default::default(),
1087                        position: to_i64(at),
1088                        anchor: to_i64(at),
1089                        text: text.into(),
1090                    };
1091                    Ok(document_editing_commands::insert_text(
1092                        &inner.ctx, stack, &ins_dto,
1093                    )?)
1094                })?
1095                .0
1096            }
1097            Err(e) => return Err(e.into()),
1098        };
1099
1100        let new_pos = to_usize(result.new_position);
1101        let added = text.chars().count();
1102        let removed = removed_since(inner, before, added, pos.max(anchor) - edit_pos);
1103        check_transient_change(recording, pos, anchor, removed)?;
1104        if let Some(format) = merge
1105            && added > 0
1106        {
1107            let dto = format.to_merge_dto(new_pos - added, new_pos);
1108            document_formatting_commands::merge_text_format(&inner.ctx, stack, &dto)?;
1109        }
1110        Ok(self.finish_edit_as(
1111            inner,
1112            edit_pos,
1113            removed,
1114            Insertion::ending_at(new_pos, added),
1115            new_pos,
1116            to_usize(result.blocks_affected),
1117            false,
1118            origin,
1119            recording,
1120        ))
1121    }
1122
1123    /// Replace `[start, end)` with `text`, choosing what the replacement wears where it
1124    /// overwrites formatted text — see [`crate::ReplaceFormatPolicy`]. Lands as one atomic
1125    /// edit (one undo entry), with the cursor left at the end of the inserted text.
1126    ///
1127    /// The counterpart to [`insert_text`](Self::insert_text) for callers that must *choose*
1128    /// the replacement's formatting rather than inherit whatever precedes the range — a
1129    /// spell-check correction picked from a context menu, an autocorrect, a
1130    /// replace-this-occurrence action. `start`/`end` may be given in either order.
1131    ///
1132    /// A range crossing a block boundary falls back to composing delete + insert as a single
1133    /// undo unit, exactly like [`insert_text`](Self::insert_text)'s existing cross-block
1134    /// fallback — `format_policy` only has meaning within one block, since
1135    /// [`crate::ReplaceFormatPolicy`] operates on a single block's format runs.
1136    ///
1137    /// With [transient edits](crate::transient) outstanding, they are reverted first, and
1138    /// `start` and `end`, read in the document as it was with them, are moved back so that
1139    /// the range holds the recorded text it held (see the
1140    /// [module documentation](crate::transient#positions)). A non-empty range that comes
1141    /// back empty held only transient text and names nothing left: nothing is replaced, and
1142    /// the call returns [`DocumentError::TransientEdits`] so the caller can tell (the
1143    /// transient edits are reverted all the same).
1144    pub fn replace(
1145        &self,
1146        start: usize,
1147        end: usize,
1148        text: &str,
1149        policy: crate::ReplaceFormatPolicy,
1150    ) -> Result<()> {
1151        let (result, rest) = {
1152            let mut inner = self.doc.lock();
1153            // Reverted under the lock the replacement takes, so that no other write lands
1154            // between the revert and the replacement and the mapped range stays true.
1155            let reverted = inner.revert_transient_edits();
1156            let (pos, anchor) = crate::transient::map_range_back(&reverted, start, end);
1157            let result = if start != end && pos == anchor {
1158                Err(DocumentError::TransientEdits(
1159                    crate::TransientRefusal::RangeOfTransientTextOnly,
1160                ))
1161            } else {
1162                self.insert_text_locked(
1163                    &mut inner,
1164                    pos,
1165                    anchor,
1166                    text,
1167                    policy,
1168                    InsertionOrigin::Unspecified,
1169                    Recording::History,
1170                )
1171            };
1172            // What is still queued: the revert's events when the replacement did not take
1173            // them with its own.
1174            (result, inner.take_queued_events())
1175        };
1176        match result {
1177            Ok(mut queued) => {
1178                queued.extend(rest);
1179                crate::inner::dispatch_queued_events(queued);
1180                Ok(())
1181            }
1182            Err(error) => {
1183                crate::inner::dispatch_queued_events(rest);
1184                Err(error)
1185            }
1186        }
1187    }
1188
1189    /// Insert text with a specific character format. Replaces selection if any.
1190    /// Reports [`InsertionOrigin::Unspecified`] — the caller did not say.
1191    pub fn insert_formatted_text(&self, text: &str, format: &TextFormat) -> Result<()> {
1192        self.insert_formatted_text_with_origin(text, format, InsertionOrigin::Unspecified)
1193    }
1194
1195    /// As [`insert_formatted_text`](Self::insert_formatted_text), saying which
1196    /// channel the text came through.
1197    pub fn insert_formatted_text_with_origin(
1198        &self,
1199        text: &str,
1200        format: &TextFormat,
1201        origin: InsertionOrigin,
1202    ) -> Result<()> {
1203        let _settled = self.settle_transient_edits();
1204        let (pos, anchor) = self.read_cursor();
1205        let queued = {
1206            let mut inner = self.doc.lock();
1207            self.insert_formatted_text_locked(
1208                &mut inner,
1209                pos,
1210                anchor,
1211                text,
1212                format,
1213                origin,
1214                Recording::History,
1215            )?
1216        };
1217        crate::inner::dispatch_queued_events(queued);
1218        Ok(())
1219    }
1220
1221    /// [`insert_text_locked`](Self::insert_text_locked) for formatted text.
1222    #[allow(clippy::too_many_arguments)]
1223    pub(crate) fn insert_formatted_text_locked(
1224        &self,
1225        inner: &mut TextDocumentInner,
1226        pos: usize,
1227        anchor: usize,
1228        text: &str,
1229        format: &TextFormat,
1230        origin: InsertionOrigin,
1231        recording: Recording,
1232    ) -> Result<QueuedEvents> {
1233        let make_dto = |p: usize, a: usize| frontend::document_editing::InsertFormattedTextDto {
1234            position: to_i64(p),
1235            anchor: to_i64(a),
1236            text: text.into(),
1237            font_family: format.font_family.clone().unwrap_or_default(),
1238            font_point_size: format.font_point_size.map(|v| v as i64).unwrap_or(0),
1239            font_bold: format.font_bold.unwrap_or(false),
1240            font_italic: format.font_italic.unwrap_or(false),
1241            font_underline: format.font_underline.unwrap_or(false),
1242            font_strikeout: format.font_strikeout.unwrap_or(false),
1243        };
1244        let stack = recording.stack(inner);
1245        let edit_pos = pos.min(anchor);
1246        let before = max_cursor_position_of(inner);
1247        let result = match document_editing_commands::insert_formatted_text(
1248            &inner.ctx,
1249            stack,
1250            &make_dto(pos, anchor),
1251        ) {
1252            Ok(r) => r,
1253            // Cross-block selection: compose delete + insert as a single undo unit
1254            Err(_) if pos != anchor => {
1255                delete_then_as(inner, pos, anchor, recording, |at| {
1256                    Ok(document_editing_commands::insert_formatted_text(
1257                        &inner.ctx,
1258                        stack,
1259                        &make_dto(at, at),
1260                    )?)
1261                })?
1262                .0
1263            }
1264            Err(e) => return Err(e.into()),
1265        };
1266
1267        let new_pos = to_usize(result.new_position);
1268        let added = text.chars().count();
1269        let removed = removed_since(inner, before, added, pos.max(anchor) - edit_pos);
1270        check_transient_change(recording, pos, anchor, removed)?;
1271        Ok(self.finish_edit_as(
1272            inner,
1273            edit_pos,
1274            removed,
1275            Insertion::ending_at(new_pos, added),
1276            new_pos,
1277            1,
1278            false,
1279            origin,
1280            recording,
1281        ))
1282    }
1283
1284    /// Insert a line break inside the block, the one Shift+Enter makes in a word
1285    /// processor. Replaces selection if any.
1286    ///
1287    /// The next line is more of the same paragraph, list item, quotation or heading,
1288    /// where [`insert_block`](Self::insert_block) starts a new one. The block's text
1289    /// holds it as one [`LINE_SEPARATOR`](crate::LINE_SEPARATOR), which every writer
1290    /// puts out as its format's own line break.
1291    ///
1292    /// Reports [`InsertionOrigin::Unspecified`], as [`insert_text`](Self::insert_text)
1293    /// does. Use [`insert_line_break_with_origin`](Self::insert_line_break_with_origin)
1294    /// to say.
1295    pub fn insert_line_break(&self) -> Result<()> {
1296        self.insert_line_break_with_origin(InsertionOrigin::Unspecified)
1297    }
1298
1299    /// [`insert_line_break`](Self::insert_line_break), saying which channel it came
1300    /// through (see [`insert_text_with_origin`](Self::insert_text_with_origin)).
1301    pub fn insert_line_break_with_origin(&self, origin: InsertionOrigin) -> Result<()> {
1302        let mut buffer = [0; 4];
1303        self.insert_text_with_origin(crate::LINE_SEPARATOR.encode_utf8(&mut buffer), origin)
1304    }
1305
1306    /// Insert a block break (new paragraph). Replaces selection if any.
1307    pub fn insert_block(&self) -> Result<()> {
1308        let _settled = self.settle_transient_edits();
1309        let (pos, anchor) = self.read_cursor();
1310        let queued = {
1311            let mut inner = self.doc.lock();
1312
1313            let split_at = |at: usize| -> Result<_> {
1314                let dto = frontend::document_editing::InsertBlockDto {
1315                    position: to_i64(at),
1316                    anchor: to_i64(at),
1317                };
1318                Ok(document_editing_commands::insert_block(
1319                    &inner.ctx,
1320                    Some(inner.stack_id),
1321                    &dto,
1322                )?)
1323            };
1324            let before = max_cursor_position_of(&inner);
1325            let result = if pos != anchor {
1326                // Selection active: delete first, then split (Word convention)
1327                delete_then(&inner, pos, anchor, split_at)?.0
1328            } else {
1329                split_at(pos)?
1330            };
1331
1332            let edit_pos = pos.min(anchor);
1333            let new_pos = to_usize(result.new_position);
1334            // One position: the boundary between the two halves.
1335            let removed = removed_since(&inner, before, 1, pos.max(anchor) - edit_pos);
1336            self.finish_edit(
1337                &mut inner,
1338                edit_pos,
1339                removed,
1340                Insertion::ending_at(new_pos, 1),
1341                new_pos,
1342                2,
1343            )
1344        };
1345        crate::inner::dispatch_queued_events(queued);
1346        Ok(())
1347    }
1348
1349    /// Insert an HTML fragment at the cursor position. Replaces selection if any.
1350    /// As [`insert_html`](Self::insert_html), saying which channel the text came
1351    /// through.
1352    pub fn insert_html_with_origin(&self, html: &str, origin: InsertionOrigin) -> Result<()> {
1353        let frag = DocumentFragment::from_html(html);
1354        self.insert_fragment_with_origin(&frag, origin)
1355    }
1356
1357    /// Insert an HTML fragment at the cursor position. Replaces selection if any.
1358    ///
1359    /// A `<pre>` goes in as paragraphs, one for each of its lines (see
1360    /// [`DocumentFragment::from_html`]).
1361    pub fn insert_html(&self, html: &str) -> Result<()> {
1362        // Delegate to insert_fragment so table structure is preserved.
1363        let frag = DocumentFragment::from_html(html);
1364        self.insert_fragment(&frag)
1365    }
1366
1367    /// Insert a Markdown fragment at the cursor position. Replaces selection if any.
1368    /// As [`insert_markdown`](Self::insert_markdown), saying which channel the text came
1369    /// through.
1370    pub fn insert_markdown_with_origin(
1371        &self,
1372        markdown: &str,
1373        origin: InsertionOrigin,
1374    ) -> Result<()> {
1375        let frag = DocumentFragment::from_markdown(markdown);
1376        self.insert_fragment_with_origin(&frag, origin)
1377    }
1378
1379    pub fn insert_markdown(&self, markdown: &str) -> Result<()> {
1380        let frag = DocumentFragment::from_markdown(markdown);
1381        self.insert_fragment(&frag)
1382    }
1383
1384    /// Insert a djot fragment at the cursor position. Replaces selection if any.
1385    /// As [`insert_djot`](Self::insert_djot), saying which channel the text came
1386    /// through.
1387    pub fn insert_djot_with_origin(&self, djot: &str, origin: InsertionOrigin) -> Result<()> {
1388        let frag = DocumentFragment::from_djot(djot);
1389        self.insert_fragment_with_origin(&frag, origin)
1390    }
1391
1392    pub fn insert_djot(&self, djot: &str) -> Result<()> {
1393        let frag = DocumentFragment::from_djot(djot);
1394        self.insert_fragment(&frag)
1395    }
1396
1397    /// Insert a footnote reference naming `label` at the cursor.
1398    ///
1399    /// Goes through Djot rather than a dedicated editing use case, and
1400    /// deliberately: `[^label]` is what `Content` stores and what a reload
1401    /// parses, so the reference on screen and the reference that survives a save
1402    /// are produced by the same code path. An insertion route of its own would
1403    /// work right up until the document was closed and reopened.
1404    ///
1405    /// The label is the note's durable identity, minted by the caller. It is
1406    /// never the number — that is derived at render time from document order,
1407    /// so inserting a note above this one renumbers it without touching a
1408    /// character of the prose.
1409    ///
1410    /// Refused, with the text left as it was, in a code block: a code block is
1411    /// verbatim text, which the save writes without a reference.
1412    pub fn insert_footnote_reference(&self, label: &str) -> Result<()> {
1413        self.insert_djot(&format!("[^{label}]"))
1414    }
1415
1416    /// Insert a document fragment at the cursor. Replaces selection if any.
1417    /// Reports [`InsertionOrigin::Unspecified`] — the caller did not say.
1418    ///
1419    /// A list the fragment carries goes in with every item, in its order, at
1420    /// most 16 levels deep, where an editor's own nesting gestures stop: an
1421    /// item nested deeper lands at the 16th level, beside the items there. This
1422    /// holds for [`insert_djot`](Self::insert_djot),
1423    /// [`insert_html`](Self::insert_html) and
1424    /// [`insert_markdown`](Self::insert_markdown) as well, which insert a
1425    /// fragment. Loading a document keeps its lists as they are.
1426    ///
1427    /// A quotation, a code block and a paragraph's alignment go in as they stood,
1428    /// so selecting all of a text and inserting another's Djot gives the text a
1429    /// load of that Djot gives. A quotation goes in as deep as it stood, never
1430    /// less deep than the caret already is (one pasted into a quotation is not
1431    /// quoted twice); in a table cell or a footnote's body, which hold paragraphs,
1432    /// it goes in as its paragraphs, and in a table cell a code block goes in as a
1433    /// paragraph (a table cell is written as one line of text).
1434    ///
1435    /// Inserted over a selection holding the whole text (from its start to its end, or
1436    /// [`select(SelectionType::Document)`](Self::select), even of an empty text), or into
1437    /// the empty paragraph a removal of such a selection left, a whole text (a fragment
1438    /// [`from_djot`](DocumentFragment::from_djot),
1439    /// [`from_markdown`](DocumentFragment::from_markdown) or
1440    /// [`from_document`](DocumentFragment::from_document), and so what
1441    /// [`insert_djot`](Self::insert_djot) and [`insert_markdown`](Self::insert_markdown)
1442    /// insert) keeps its own formatting rather than taking that of the empty paragraph the
1443    /// removal leaves, which is the first removed paragraph's: the text reads as the
1444    /// fragment loaded. So does any other fragment with a structure of its own: several
1445    /// paragraphs, a table, a quotation, or a paragraph of its own format. That empty
1446    /// paragraph is replaced whichever cursor removed the text, and after an undo or a
1447    /// redo back to it, as long as it looks as the removal left it. A phrase, one plain
1448    /// paragraph copied from a text or pasted as HTML, goes into it as typed text does and
1449    /// keeps its formatting: its direction, alignment, heading level and quotation. An
1450    /// empty paragraph the writer formatted (a heading line, a list item, a quotation),
1451    /// in an empty text as anywhere else, is the paragraph a paste goes into, as typed text
1452    /// does: a heading line stays a heading, and a quotation made for an epigraph holds
1453    /// what is pasted into it. The bodies of footnote definitions
1454    /// the document holds stay where they are, as
1455    /// [`remove_selected_text`](Self::remove_selected_text) says. A paste that
1456    /// would put an image or a footnote reference into a code block is refused, the
1457    /// text left as it was: a code block is verbatim text, which the save writes
1458    /// without them.
1459    pub fn insert_fragment(&self, fragment: &DocumentFragment) -> Result<()> {
1460        self.insert_fragment_with_origin(fragment, InsertionOrigin::Unspecified)
1461    }
1462
1463    /// As [`insert_fragment`](Self::insert_fragment), saying which channel the
1464    /// text came through. This is the path a paste, a drop and an import all
1465    /// take, so it is the one that most needs to be able to say so.
1466    pub fn insert_fragment_with_origin(
1467        &self,
1468        fragment: &DocumentFragment,
1469        origin: InsertionOrigin,
1470    ) -> Result<()> {
1471        let _settled = self.settle_transient_edits();
1472        let (pos, anchor) = self.read_cursor();
1473        let queued = {
1474            let mut inner = self.doc.lock();
1475            // All of an empty text selected: nothing to remove, and still the whole text to
1476            // replace (see `CursorData::whole_text_selected`). Read under the document's
1477            // lock, which every edit ending that selection holds.
1478            let replacing_an_empty_text = pos == anchor && self.data.lock().whole_text_selected;
1479            // Otherwise, the empty paragraph a removal of all of the text left, as it left
1480            // it, whichever cursor removed the text and after whatever undo or redo brought
1481            // the text back to it (see `EmptiedText`): a text of its own structure pasted
1482            // there keeps its formatting. A line the writer formatted since is pasted into.
1483            let into_an_emptied_text =
1484                pos == anchor && !replacing_an_empty_text && inner.is_the_emptied_text();
1485
1486            // Where the paste went in and what it added are measured, as a
1487            // deletion's removal is: the caret after a paste does not always
1488            // follow what it added. A table pasted into a paragraph goes in
1489            // after the paragraph and leaves the caret in front of it, and the
1490            // tail of a paragraph pasted into stays after the caret.
1491            // After a selection is removed, the fragment goes in marked as replacing it:
1492            // when the selection held the whole text, the empty paragraph it leaves takes
1493            // the fragment's formatting, unless the fragment is a phrase (see
1494            // `replacing_the_text`).
1495            let paste_at = |at: usize, replacing: bool| -> Result<_> {
1496                let store = inner.ctx.db_context.get_store();
1497                let rope_before = store.rope.read().clone();
1498                let before = max_cursor_position_of(&inner);
1499                let fragment_data = if replacing {
1500                    frontend::common::parser_tools::fragment_schema::replacing_the_text(
1501                        fragment.raw_data(),
1502                    )
1503                } else if into_an_emptied_text {
1504                    frontend::common::parser_tools::fragment_schema::into_an_emptied_text(
1505                        fragment.raw_data(),
1506                    )
1507                } else {
1508                    fragment.raw_data().into()
1509                };
1510                let dto = frontend::document_editing::InsertFragmentDto {
1511                    position: to_i64(at),
1512                    anchor: to_i64(at),
1513                    fragment_data,
1514                };
1515                let result = document_editing_commands::insert_fragment(
1516                    &inner.ctx,
1517                    Some(inner.stack_id),
1518                    &dto,
1519                )?;
1520                let inserted = if common::database::rope_helpers::rope_positions_match_flow(store) {
1521                    let (start, old_end, new_end) = common::database::rope_helpers::changed_span(
1522                        &rope_before,
1523                        &store.rope.read(),
1524                        at,
1525                    );
1526                    Insertion {
1527                        at: start,
1528                        removed: old_end - start,
1529                        added: new_end - start,
1530                    }
1531                } else {
1532                    // What the paste added, in all; up to the caret when the
1533                    // lengths cannot be read, as before.
1534                    let new_pos = to_usize(result.new_position);
1535                    let added = before
1536                        .zip(max_cursor_position_of(&inner))
1537                        .map_or(new_pos.saturating_sub(at), |(before, after)| {
1538                            after.saturating_sub(before)
1539                        });
1540                    Insertion {
1541                        at,
1542                        removed: 0,
1543                        added,
1544                    }
1545                };
1546                Ok((result, inserted))
1547            };
1548            let ((result, inserted), removed, deleted_from) = if pos != anchor {
1549                delete_then(&inner, pos, anchor, |at| paste_at(at, true))?
1550            } else {
1551                (paste_at(pos, replacing_an_empty_text)?, 0, pos)
1552            };
1553
1554            // What the deletion took starts where it left the caret when that
1555            // is before the range's start (see `delete_then`).
1556            let edit_pos = pos.min(anchor).min(deleted_from);
1557            let new_pos = to_usize(result.new_position);
1558            self.finish_edit_from(
1559                &mut inner,
1560                edit_pos,
1561                removed,
1562                inserted,
1563                new_pos,
1564                to_usize(result.blocks_added),
1565                true,
1566                origin,
1567            )
1568        };
1569        crate::inner::dispatch_queued_events(queued);
1570        Ok(())
1571    }
1572
1573    /// Extract the current selection as a [`DocumentFragment`].
1574    ///
1575    /// The fragment holds the text the selection starts in: the main text, with the
1576    /// quotations its whole paragraphs stand in, or the one footnote body it starts in.
1577    /// A note's reference travels; its body stays where it is defined. Each paragraph is
1578    /// held once, in reading order. A table the selection holds the anchor of, runs into
1579    /// from the text beside it, or runs out of into the text beside it, is held whole, in a
1580    /// quotation as anywhere else, as a removal of the same selection takes it. An ordered
1581    /// list keeps the numbers its items wore. An empty paragraph closing the text is held
1582    /// when the selection reaches the text's end.
1583    pub fn selection(&self) -> DocumentFragment {
1584        let (pos, anchor) = self.read_cursor();
1585
1586        // For cell/mixed selections, compute position/anchor that span the
1587        // full cell range so ExtractFragment detects cross-cell correctly.
1588        let (extract_pos, extract_anchor) = match self.selection_kind() {
1589            SelectionKind::Cells(ref range) => match self.cell_range_positions(range) {
1590                Some((start, end)) => (start, end),
1591                None => return DocumentFragment::new(),
1592            },
1593            SelectionKind::Mixed {
1594                ref cell_range,
1595                text_before,
1596                text_after,
1597            } => {
1598                let (cell_start, cell_end) = match self.cell_range_positions(cell_range) {
1599                    Some(p) => p,
1600                    None => return DocumentFragment::new(),
1601                };
1602                // The whole table is selected, its anchor with it: a range from its first
1603                // cell only met that cell's paragraphs when the table has one cell, and the
1604                // copy held them without the table.
1605                let table_start = self
1606                    .table_anchor_position(cell_range.table_id)
1607                    .unwrap_or(cell_start)
1608                    .min(cell_start);
1609                let start = if text_before {
1610                    pos.min(anchor).min(table_start)
1611                } else {
1612                    table_start
1613                };
1614                let end = if text_after {
1615                    pos.max(anchor)
1616                } else {
1617                    cell_end
1618                };
1619                (start.min(cell_start), end.max(cell_end))
1620            }
1621            SelectionKind::None => return DocumentFragment::new(),
1622            SelectionKind::Text => (pos, anchor),
1623        };
1624
1625        if extract_pos == extract_anchor {
1626            return DocumentFragment::new();
1627        }
1628
1629        let inner = self.doc.lock();
1630        let dto = frontend::document_inspection::ExtractFragmentDto {
1631            position: to_i64(extract_pos),
1632            anchor: to_i64(extract_anchor),
1633        };
1634        match document_inspection_commands::extract_fragment(&inner.ctx, &dto) {
1635            Ok(result) => DocumentFragment::from_raw(result.fragment_data, result.plain_text),
1636            Err(_) => DocumentFragment::new(),
1637        }
1638    }
1639
1640    /// Insert an image at the cursor. Replaces selection if any.
1641    ///
1642    /// `name` keys the image's bytes in the document's resource table (see
1643    /// [`crate::TextDocument::add_resource`]); `alt` is its accessible
1644    /// description and its export representation, and may be empty.
1645    ///
1646    /// Refused, with the text left as it was, in a code block: a code block is
1647    /// verbatim text, which the save writes without an image.
1648    pub fn insert_image(&self, name: &str, alt: &str, width: u32, height: u32) -> Result<()> {
1649        let _settled = self.settle_transient_edits();
1650        let (pos, anchor) = self.read_cursor();
1651        let queued = {
1652            let mut inner = self.doc.lock();
1653
1654            let image_at = |at: usize| -> Result<_> {
1655                let dto = frontend::document_editing::InsertImageDto {
1656                    position: to_i64(at),
1657                    anchor: to_i64(at),
1658                    image_name: name.into(),
1659                    alt: alt.into(),
1660                    width: width as i64,
1661                    height: height as i64,
1662                    quality: 100,
1663                };
1664                Ok(document_editing_commands::insert_image(
1665                    &inner.ctx,
1666                    Some(inner.stack_id),
1667                    &dto,
1668                )?)
1669            };
1670            let before = max_cursor_position_of(&inner);
1671            let result = if pos != anchor {
1672                delete_then(&inner, pos, anchor, image_at)?.0
1673            } else {
1674                image_at(pos)?
1675            };
1676
1677            let edit_pos = pos.min(anchor);
1678            let new_pos = to_usize(result.new_position);
1679            // One position: the image's `U+FFFC`.
1680            let removed = removed_since(&inner, before, 1, pos.max(anchor) - edit_pos);
1681            self.finish_edit_ext(
1682                &mut inner,
1683                edit_pos,
1684                removed,
1685                Insertion::ending_at(new_pos, 1),
1686                new_pos,
1687                1,
1688                false,
1689            )
1690        };
1691        crate::inner::dispatch_queued_events(queued);
1692        Ok(())
1693    }
1694
1695    /// Insert a new frame at the cursor.
1696    pub fn insert_frame(&self) -> Result<()> {
1697        let _settled = self.settle_transient_edits();
1698        let (pos, anchor) = self.read_cursor();
1699        let queued = {
1700            let mut inner = self.doc.lock();
1701            // The frame's paragraph is reported, and moves the cursors after it, as the
1702            // diff of the text finds it (see `remove_table`).
1703            let before = crate::document::capture_block_state(&inner);
1704            let dto = frontend::document_editing::InsertFrameDto {
1705                position: to_i64(pos),
1706                anchor: to_i64(anchor),
1707            };
1708            document_editing_commands::insert_frame(&inner.ctx, Some(inner.stack_id), &dto)?;
1709            inner.modified = true;
1710            inner.invalidate_text_cache();
1711            inner.rehighlight_affected(pos.min(anchor));
1712            crate::document::emit_content_change_events(&mut inner, &before);
1713            inner.check_block_count_changed();
1714            inner.check_flow_changed();
1715            self.queue_undo_redo_event(&mut inner)
1716        };
1717        crate::inner::dispatch_queued_events(queued);
1718        Ok(())
1719    }
1720
1721    /// Insert a table at the cursor position.
1722    ///
1723    /// Creates a `rows × columns` table with empty cells.
1724    /// The cursor moves into the first cell of the table.
1725    /// Returns a handle to the created table.
1726    pub fn insert_table(&self, rows: usize, columns: usize) -> Result<TextTable> {
1727        let _settled = self.settle_transient_edits();
1728        let (pos, anchor) = self.read_cursor();
1729        let (table_id, queued) = {
1730            let mut inner = self.doc.lock();
1731            // The table's anchor and cells are reported, and move the cursors after
1732            // them, as the diff of the text finds them (see `remove_table`).
1733            let before = crate::document::capture_block_state(&inner);
1734            let dto = frontend::document_editing::InsertTableDto {
1735                position: to_i64(pos),
1736                anchor: to_i64(anchor),
1737                rows: to_i64(rows),
1738                columns: to_i64(columns),
1739            };
1740            let result =
1741                document_editing_commands::insert_table(&inner.ctx, Some(inner.stack_id), &dto)?;
1742            let new_pos = to_usize(result.new_position);
1743            let table_id = to_usize(result.table_id);
1744            inner.invalidate_text_cache();
1745            crate::document::emit_content_change_events(&mut inner, &before);
1746            {
1747                let mut d = self.data.lock();
1748                d.position = new_pos;
1749                d.anchor = new_pos;
1750                d.whole_text_selected = false;
1751                d.anchor_in_table = None;
1752            }
1753            inner.modified = true;
1754            inner.rehighlight_affected(pos.min(anchor));
1755            inner.check_block_count_changed();
1756            inner.check_flow_changed();
1757            (table_id, self.queue_undo_redo_event(&mut inner))
1758        };
1759        crate::inner::dispatch_queued_events(queued);
1760        Ok(TextTable {
1761            doc: self.doc.clone(),
1762            table_id,
1763        })
1764    }
1765
1766    /// Returns the table the cursor is currently inside, if any.
1767    ///
1768    /// Returns `None` if the cursor is in the main document flow
1769    /// (not inside a table cell).
1770    pub fn current_table(&self) -> Option<TextTable> {
1771        self.current_table_cell().map(|c| c.table)
1772    }
1773
1774    /// Returns the table cell the cursor is currently inside, if any.
1775    ///
1776    /// Returns `None` if the cursor is not inside a table cell.
1777    /// When `Some`, provides the table, row, and column.
1778    pub fn current_table_cell(&self) -> Option<TableCellRef> {
1779        let pos = self.position();
1780        let inner = self.doc.lock();
1781        // The caret's block: at the end of a paragraph, that paragraph, and on a table's
1782        // anchor, the table's first cell (see `block_at_caret_dto`).
1783        let block_id = crate::inner::block_at_caret_dto(&inner.ctx, pos)
1784            .ok()?
1785            .block_id as usize;
1786
1787        let block = crate::text_block::TextBlock {
1788            doc: self.doc.clone(),
1789            block_id,
1790        };
1791        // Release inner lock before calling table_cell() which also locks
1792        drop(inner);
1793        block.table_cell()
1794    }
1795
1796    // ── Frame / blockquote queries ──────────
1797
1798    /// The innermost frame enclosing the cursor's current block, or `None`
1799    /// if the cursor sits directly in the root frame (no enclosing
1800    /// sub-frame). The returned `depth` is the nesting level from the root
1801    /// (1 for a direct child of root, 2 for a grandchild, etc.).
1802    pub fn current_frame(&self) -> Option<FrameRef> {
1803        let pos = self.position();
1804        let inner = self.doc.lock();
1805        let block_info = Self::caret_block(&inner, pos)?;
1806        let block_id = block_info.block_id as u64;
1807        cursor_frame_ref(&inner, block_id)
1808    }
1809
1810    /// True if the cursor's block lives inside any blockquote frame
1811    /// (at any nesting level). The block is the caret's: at the end of a
1812    /// quoted paragraph, that paragraph, whatever follows it.
1813    pub fn is_in_blockquote(&self) -> bool {
1814        self.current_blockquote_frame_id().is_some()
1815    }
1816
1817    /// Id of the innermost blockquote frame enclosing the cursor's block,
1818    /// or `None` if not in a blockquote.
1819    pub fn current_blockquote_frame_id(&self) -> Option<usize> {
1820        let pos = self.position();
1821        let inner = self.doc.lock();
1822        let block_info = Self::caret_block(&inner, pos)?;
1823        innermost_blockquote_frame_id(&inner, block_info.block_id as u64)
1824    }
1825
1826    /// Nesting depth of the cursor inside blockquote frames: 0 = not in
1827    /// any quote, 1 = top-level quote, 2 = quote inside a quote, …
1828    pub fn blockquote_depth_at_cursor(&self) -> usize {
1829        let pos = self.position();
1830        let inner = self.doc.lock();
1831        let Some(block_info) = Self::caret_block(&inner, pos) else {
1832            return 0;
1833        };
1834        blockquote_depth_for_block(&inner, block_info.block_id as u64)
1835    }
1836
1837    /// True iff the cursor's block is the first positive entry in its
1838    /// owning frame's `child_order`. Used by the keyboard handler to
1839    /// decide whether Backspace should unwrap the enclosing frame.
1840    /// A single-block frame returns true for both `is_first_*` and
1841    /// `is_last_*`.
1842    pub fn is_first_block_in_current_frame(&self) -> bool {
1843        matches!(
1844            block_position_in_current_frame(self),
1845            Some(BlockEdge::First) | Some(BlockEdge::OnlyOne)
1846        )
1847    }
1848
1849    /// True iff the cursor's block is the last positive entry in its
1850    /// owning frame's `child_order`. Used by the keyboard handler to
1851    /// decide whether forward Delete should unwrap the enclosing frame.
1852    pub fn is_last_block_in_current_frame(&self) -> bool {
1853        matches!(
1854            block_position_in_current_frame(self),
1855            Some(BlockEdge::Last) | Some(BlockEdge::OnlyOne)
1856        )
1857    }
1858
1859    /// True iff the block at the cursor has no characters of content.
1860    /// Used by the Enter handler to decide whether to exit a blockquote.
1861    pub fn current_block_is_empty(&self) -> bool {
1862        let pos = self.position();
1863        let inner = self.doc.lock();
1864        let Some(block_info) = Self::caret_block(&inner, pos) else {
1865            return false;
1866        };
1867        let store = inner.ctx.db_context.get_store();
1868        let block_entity = store
1869            .blocks
1870            .read()
1871            .get(&(block_info.block_id as common::types::EntityId))
1872            .cloned();
1873        match block_entity {
1874            Some(b) => {
1875                let len = common::database::rope_helpers::block_char_length(&b, store);
1876                len == 0
1877            }
1878            None => false,
1879        }
1880    }
1881
1882    /// True iff the cursor's anchor and head sit in different frames.
1883    /// Used by the toolbar to disable the "toggle blockquote" button on
1884    /// selections that cross frame boundaries.
1885    pub fn selection_spans_multiple_frames(&self) -> bool {
1886        let (pos, anchor) = self.read_cursor();
1887        if pos == anchor {
1888            return false;
1889        }
1890        let inner = self.doc.lock();
1891        // The blocks the selection's first and last characters are in (see
1892        // `selection_block_ids`).
1893        let Some((first, last)) = Self::selection_block_ids(&inner, pos, anchor) else {
1894            return false;
1895        };
1896        crate::text_block::find_parent_frame(&inner, first)
1897            != crate::text_block::find_parent_frame(&inner, last)
1898    }
1899
1900    /// The blocks the selection from `pos` to `anchor` starts and ends in: the block at the
1901    /// character index of its start, and the caret's block at its end (see `caret_block`),
1902    /// so a selection ending at the end of a paragraph ends in that paragraph. Read at the
1903    /// character index, its end was the next paragraph: a selection of exactly one paragraph
1904    /// was quoted with the one after it, and a selection of all of a quoted paragraph was
1905    /// taken for one across two frames. A caret, `pos` and `anchor` equal, is in the caret's
1906    /// block at both ends.
1907    fn selection_block_ids(
1908        inner: &TextDocumentInner,
1909        pos: usize,
1910        anchor: usize,
1911    ) -> Option<(u64, u64)> {
1912        let (lo, hi) = (pos.min(anchor), pos.max(anchor));
1913        let last = Self::caret_block(inner, hi)?.block_id as u64;
1914        if lo == hi {
1915            return Some((last, last));
1916        }
1917        let first = document_inspection_commands::get_block_at_position(
1918            &inner.ctx,
1919            &frontend::document_inspection::GetBlockAtPositionDto {
1920                position: to_i64(lo),
1921            },
1922        )
1923        .ok()?
1924        .block_id as u64;
1925        Some((first, last))
1926    }
1927
1928    // ── Blockquote mutations ──────────
1929
1930    /// Wrap the current block (or the blocks in the current selection)
1931    /// in a new blockquote frame nested inside the cursor's current
1932    /// parent frame. Returns an error if the selection spans multiple
1933    /// frames.
1934    pub fn wrap_selection_in_blockquote(&self) -> Result<()> {
1935        let _settled = self.settle_transient_edits();
1936        if self.selection_spans_multiple_frames() {
1937            return Err(DocumentError::InvalidArgument(
1938                "Cannot wrap selection in blockquote: selection spans multiple frames".into(),
1939            ));
1940        }
1941        let (start_block_id, end_block_id) = self.resolve_selection_block_range()?;
1942        let dto = frontend::document_editing::WrapBlocksInFrameDto {
1943            start_block_id: start_block_id as i64,
1944            end_block_id: end_block_id as i64,
1945            position: Some(frontend::document_editing::FramePosition::InFlow),
1946            top_margin: None,
1947            bottom_margin: None,
1948            left_margin: None,
1949            right_margin: None,
1950            padding: None,
1951            border: None,
1952            is_blockquote: Some(true),
1953        };
1954        let queued = {
1955            let mut inner = self.doc.lock();
1956            let _result = document_editing_commands::wrap_blocks_in_frame(
1957                &inner.ctx,
1958                Some(inner.stack_id),
1959                &dto,
1960            )?;
1961            inner.modified = true;
1962            // Frame-structure change: blocks didn't move and no text
1963            // changed, but block left-margins shift visually. Fire
1964            // FormatChanged (kind = Block) so the widget triggers a
1965            // paragraph relayout — same pattern as list operations
1966            // ([`add_block_to_list`] et al.). `ContentsChanged` with
1967            // chars_added/removed = 0 was misleading and caused the
1968            // incremental relayout to no-op until the next full repaint.
1969            inner.queue_event(DocumentEvent::FormatChanged {
1970                position: 0,
1971                length: 0,
1972                kind: crate::flow::FormatChangeKind::Block,
1973            });
1974            self.queue_undo_redo_event(&mut inner)
1975        };
1976        crate::inner::dispatch_queued_events(queued);
1977        Ok(())
1978    }
1979
1980    /// Wrap the current block in a new blockquote frame at the current
1981    /// nesting level. Equivalent to `wrap_selection_in_blockquote()`
1982    /// when there is no selection.
1983    pub fn insert_blockquote(&self) -> Result<()> {
1984        let _settled = self.settle_transient_edits();
1985        self.wrap_selection_in_blockquote()
1986    }
1987
1988    /// If the cursor is inside any blockquote, unwrap the innermost one
1989    /// (lift its blocks into the parent frame and delete the frame).
1990    /// Otherwise, wrap the current block / selection in a new
1991    /// blockquote. Mirrors the toggle behaviour of a toolbar button.
1992    pub fn toggle_blockquote(&self) -> Result<()> {
1993        let _settled = self.settle_transient_edits();
1994        if let Some(frame_id) = self.current_blockquote_frame_id() {
1995            self.unwrap_frame_by_id(frame_id)
1996        } else {
1997            self.wrap_selection_in_blockquote()
1998        }
1999    }
2000
2001    /// Unwrap the innermost frame enclosing the cursor (any frame, not
2002    /// just blockquotes). Errors if the cursor's block sits in the root
2003    /// frame.
2004    pub fn unwrap_current_frame(&self) -> Result<()> {
2005        let _settled = self.settle_transient_edits();
2006        let frame_ref = self.current_frame().ok_or_else(|| {
2007            DocumentError::InvalidCursorContext("Cursor is not inside any sub-frame".into())
2008        })?;
2009        self.unwrap_frame_by_id(frame_ref.frame_id)
2010    }
2011
2012    /// Extract the cursor's current block from its innermost enclosing
2013    /// blockquote frame, lifting it one nesting level. If the cursor is
2014    /// not in a blockquote, errors.
2015    pub fn unwrap_current_block_from_blockquote(&self) -> Result<()> {
2016        let _settled = self.settle_transient_edits();
2017        if self.current_blockquote_frame_id().is_none() {
2018            return Err(DocumentError::InvalidCursorContext(
2019                "Cursor is not inside a blockquote".into(),
2020            ));
2021        }
2022        let block_id = self.current_block_id_for_mutation()?;
2023        let dto = frontend::document_editing::UnwrapBlockFromFrameDto {
2024            block_id: block_id as i64,
2025        };
2026        let queued = {
2027            let mut inner = self.doc.lock();
2028            let _result = document_editing_commands::unwrap_block_from_frame(
2029                &inner.ctx,
2030                Some(inner.stack_id),
2031                &dto,
2032            )?;
2033            inner.modified = true;
2034            // See note in `wrap_selection_in_blockquote` — frame-structure
2035            // change without text mutation; fire FormatChanged so the
2036            // widget relayouts paragraph margins.
2037            inner.queue_event(DocumentEvent::FormatChanged {
2038                position: 0,
2039                length: 0,
2040                kind: crate::flow::FormatChangeKind::Block,
2041            });
2042            self.queue_undo_redo_event(&mut inner)
2043        };
2044        crate::inner::dispatch_queued_events(queued);
2045        Ok(())
2046    }
2047
2048    /// Wrap the current block in a new blockquote frame. If the cursor
2049    /// is already inside a blockquote, this creates a deeper nested
2050    /// quote (depth + 1). If outside, this creates a top-level quote.
2051    pub fn increase_blockquote_depth(&self) -> Result<()> {
2052        let _settled = self.settle_transient_edits();
2053        self.wrap_selection_in_blockquote()
2054    }
2055
2056    /// Pop the cursor out of one nesting level of blockquotes. If the
2057    /// cursor is in a depth-N quote with multiple blocks, the current
2058    /// block is extracted (splitting the quote if needed). If the
2059    /// current block is the only one in the quote, the whole quote is
2060    /// unwrapped.
2061    pub fn decrease_blockquote_depth(&self) -> Result<()> {
2062        let _settled = self.settle_transient_edits();
2063        if self.current_blockquote_frame_id().is_none() {
2064            return Err(DocumentError::InvalidCursorContext(
2065                "Cursor is not inside a blockquote to decrease depth".into(),
2066            ));
2067        }
2068        self.unwrap_current_block_from_blockquote()
2069    }
2070
2071    fn unwrap_frame_by_id(&self, frame_id: usize) -> Result<()> {
2072        let dto = frontend::document_editing::UnwrapFrameDto {
2073            frame_id: frame_id as i64,
2074        };
2075        let queued = {
2076            let mut inner = self.doc.lock();
2077            let _result =
2078                document_editing_commands::unwrap_frame(&inner.ctx, Some(inner.stack_id), &dto)?;
2079            inner.modified = true;
2080            // See note in `wrap_selection_in_blockquote` — frame-structure
2081            // change without text mutation; fire FormatChanged so the
2082            // widget relayouts paragraph margins.
2083            inner.queue_event(DocumentEvent::FormatChanged {
2084                position: 0,
2085                length: 0,
2086                kind: crate::flow::FormatChangeKind::Block,
2087            });
2088            self.queue_undo_redo_event(&mut inner)
2089        };
2090        crate::inner::dispatch_queued_events(queued);
2091        Ok(())
2092    }
2093
2094    /// The caret's block (see `caret_block`): at the end of the last quoted paragraph, the
2095    /// paragraph lifted out of its quotation is that one.
2096    fn current_block_id_for_mutation(&self) -> Result<usize> {
2097        let pos = self.position();
2098        let inner = self.doc.lock();
2099        let block_info = crate::inner::block_at_caret_dto(&inner.ctx, pos)?;
2100        Ok(block_info.block_id as usize)
2101    }
2102
2103    /// The first and last blocks of the selection, or the caret's block twice (see
2104    /// `selection_block_ids`): with the caret at the end of a paragraph, the paragraph
2105    /// quoted is that one, where it was the next.
2106    fn resolve_selection_block_range(&self) -> Result<(usize, usize)> {
2107        let (pos, anchor) = self.read_cursor();
2108        let inner = self.doc.lock();
2109        let (first, last) = Self::selection_block_ids(&inner, pos, anchor)
2110            .ok_or_else(|| DocumentError::NotFound("no block at the selection's ends".into()))?;
2111        Ok((first as usize, last as usize))
2112    }
2113
2114    // ── Table structure mutations (explicit-ID) ──────────
2115
2116    /// Remove a table from the document by its ID.
2117    pub fn remove_table(&self, table_id: usize) -> Result<()> {
2118        let _settled = self.settle_transient_edits();
2119        let queued = {
2120            let mut inner = self.doc.lock();
2121            // ⚠ Snapshotted **before** the command, so the text change it makes
2122            // can be reported as a real diff afterwards. Every structural table
2123            // edit below does the same: they know how many rows or cells they
2124            // touched and not where in the document's text that lands, and
2125            // working that out by hand would be seven chances to be subtly
2126            // wrong in a figure consumers shift their offsets by.
2127            let before = crate::document::capture_block_state(&inner);
2128            let dto = frontend::document_editing::RemoveTableDto {
2129                table_id: to_i64(table_id),
2130            };
2131            document_editing_commands::remove_table(&inner.ctx, Some(inner.stack_id), &dto)?;
2132            inner.modified = true;
2133            inner.invalidate_text_cache();
2134            inner.rehighlight_all();
2135            crate::document::emit_content_change_events(&mut inner, &before);
2136            inner.check_block_count_changed();
2137            inner.check_flow_changed();
2138            self.queue_undo_redo_event(&mut inner)
2139        };
2140        crate::inner::dispatch_queued_events(queued);
2141        Ok(())
2142    }
2143
2144    /// Insert a row into a table at the given index.
2145    pub fn insert_table_row(&self, table_id: usize, row_index: usize) -> Result<()> {
2146        let _settled = self.settle_transient_edits();
2147        let queued = {
2148            let mut inner = self.doc.lock();
2149            let before = crate::document::capture_block_state(&inner);
2150            let dto = frontend::document_editing::InsertTableRowDto {
2151                table_id: to_i64(table_id),
2152                row_index: to_i64(row_index),
2153            };
2154            document_editing_commands::insert_table_row(&inner.ctx, Some(inner.stack_id), &dto)?;
2155            inner.modified = true;
2156            inner.invalidate_text_cache();
2157            inner.rehighlight_all();
2158            crate::document::emit_content_change_events(&mut inner, &before);
2159            inner.check_block_count_changed();
2160            self.queue_undo_redo_event(&mut inner)
2161        };
2162        crate::inner::dispatch_queued_events(queued);
2163        Ok(())
2164    }
2165
2166    /// Insert a column into a table at the given index.
2167    pub fn insert_table_column(&self, table_id: usize, column_index: usize) -> Result<()> {
2168        let _settled = self.settle_transient_edits();
2169        let queued = {
2170            let mut inner = self.doc.lock();
2171            let before = crate::document::capture_block_state(&inner);
2172            let dto = frontend::document_editing::InsertTableColumnDto {
2173                table_id: to_i64(table_id),
2174                column_index: to_i64(column_index),
2175            };
2176            document_editing_commands::insert_table_column(&inner.ctx, Some(inner.stack_id), &dto)?;
2177            inner.modified = true;
2178            inner.invalidate_text_cache();
2179            inner.rehighlight_all();
2180            crate::document::emit_content_change_events(&mut inner, &before);
2181            inner.check_block_count_changed();
2182            self.queue_undo_redo_event(&mut inner)
2183        };
2184        crate::inner::dispatch_queued_events(queued);
2185        Ok(())
2186    }
2187
2188    /// Remove a row from a table. Fails if only one row remains.
2189    pub fn remove_table_row(&self, table_id: usize, row_index: usize) -> Result<()> {
2190        let _settled = self.settle_transient_edits();
2191        let queued = {
2192            let mut inner = self.doc.lock();
2193            let before = crate::document::capture_block_state(&inner);
2194            let dto = frontend::document_editing::RemoveTableRowDto {
2195                table_id: to_i64(table_id),
2196                row_index: to_i64(row_index),
2197            };
2198            document_editing_commands::remove_table_row(&inner.ctx, Some(inner.stack_id), &dto)?;
2199            inner.modified = true;
2200            inner.invalidate_text_cache();
2201            inner.rehighlight_all();
2202            crate::document::emit_content_change_events(&mut inner, &before);
2203            inner.check_block_count_changed();
2204            self.queue_undo_redo_event(&mut inner)
2205        };
2206        crate::inner::dispatch_queued_events(queued);
2207        Ok(())
2208    }
2209
2210    /// Remove a column from a table. Fails if only one column remains.
2211    pub fn remove_table_column(&self, table_id: usize, column_index: usize) -> Result<()> {
2212        let _settled = self.settle_transient_edits();
2213        let queued = {
2214            let mut inner = self.doc.lock();
2215            let before = crate::document::capture_block_state(&inner);
2216            let dto = frontend::document_editing::RemoveTableColumnDto {
2217                table_id: to_i64(table_id),
2218                column_index: to_i64(column_index),
2219            };
2220            document_editing_commands::remove_table_column(&inner.ctx, Some(inner.stack_id), &dto)?;
2221            inner.modified = true;
2222            inner.invalidate_text_cache();
2223            inner.rehighlight_all();
2224            crate::document::emit_content_change_events(&mut inner, &before);
2225            inner.check_block_count_changed();
2226            self.queue_undo_redo_event(&mut inner)
2227        };
2228        crate::inner::dispatch_queued_events(queued);
2229        Ok(())
2230    }
2231
2232    /// Merge a rectangular range of cells within a table.
2233    pub fn merge_table_cells(
2234        &self,
2235        table_id: usize,
2236        start_row: usize,
2237        start_column: usize,
2238        end_row: usize,
2239        end_column: usize,
2240    ) -> Result<()> {
2241        let _settled = self.settle_transient_edits();
2242        let queued = {
2243            let mut inner = self.doc.lock();
2244            let before = crate::document::capture_block_state(&inner);
2245            let dto = frontend::document_editing::MergeTableCellsDto {
2246                table_id: to_i64(table_id),
2247                start_row: to_i64(start_row),
2248                start_column: to_i64(start_column),
2249                end_row: to_i64(end_row),
2250                end_column: to_i64(end_column),
2251            };
2252            document_editing_commands::merge_table_cells(&inner.ctx, Some(inner.stack_id), &dto)?;
2253            inner.modified = true;
2254            inner.invalidate_text_cache();
2255            inner.rehighlight_all();
2256            crate::document::emit_content_change_events(&mut inner, &before);
2257            inner.check_block_count_changed();
2258            self.queue_undo_redo_event(&mut inner)
2259        };
2260        crate::inner::dispatch_queued_events(queued);
2261        Ok(())
2262    }
2263
2264    /// Split a previously merged cell.
2265    pub fn split_table_cell(
2266        &self,
2267        cell_id: usize,
2268        split_rows: usize,
2269        split_columns: usize,
2270    ) -> Result<()> {
2271        let _settled = self.settle_transient_edits();
2272        let queued = {
2273            let mut inner = self.doc.lock();
2274            let before = crate::document::capture_block_state(&inner);
2275            let dto = frontend::document_editing::SplitTableCellDto {
2276                cell_id: to_i64(cell_id),
2277                split_rows: to_i64(split_rows),
2278                split_columns: to_i64(split_columns),
2279            };
2280            document_editing_commands::split_table_cell(&inner.ctx, Some(inner.stack_id), &dto)?;
2281            inner.modified = true;
2282            inner.invalidate_text_cache();
2283            inner.rehighlight_all();
2284            crate::document::emit_content_change_events(&mut inner, &before);
2285            inner.check_block_count_changed();
2286            self.queue_undo_redo_event(&mut inner)
2287        };
2288        crate::inner::dispatch_queued_events(queued);
2289        Ok(())
2290    }
2291
2292    // ── Table formatting (explicit-ID) ───────────────────
2293
2294    /// Set formatting on a table.
2295    pub fn set_table_format(
2296        &self,
2297        table_id: usize,
2298        format: &crate::flow::TableFormat,
2299    ) -> Result<()> {
2300        let _settled = self.settle_transient_edits();
2301        let queued = {
2302            let mut inner = self.doc.lock();
2303            let dto = format.to_set_dto(table_id);
2304            document_formatting_commands::set_table_format(&inner.ctx, Some(inner.stack_id), &dto)?;
2305            inner.modified = true;
2306            inner.queue_event(DocumentEvent::FormatChanged {
2307                position: 0,
2308                length: 0,
2309                kind: crate::flow::FormatChangeKind::Block,
2310            });
2311            self.queue_undo_redo_event(&mut inner)
2312        };
2313        crate::inner::dispatch_queued_events(queued);
2314        Ok(())
2315    }
2316
2317    /// Set formatting on a table cell.
2318    pub fn set_table_cell_format(
2319        &self,
2320        cell_id: usize,
2321        format: &crate::flow::CellFormat,
2322    ) -> Result<()> {
2323        let _settled = self.settle_transient_edits();
2324        let queued = {
2325            let mut inner = self.doc.lock();
2326            let dto = format.to_set_dto(cell_id);
2327            document_formatting_commands::set_table_cell_format(
2328                &inner.ctx,
2329                Some(inner.stack_id),
2330                &dto,
2331            )?;
2332            inner.modified = true;
2333            inner.queue_event(DocumentEvent::FormatChanged {
2334                position: 0,
2335                length: 0,
2336                kind: crate::flow::FormatChangeKind::Block,
2337            });
2338            self.queue_undo_redo_event(&mut inner)
2339        };
2340        crate::inner::dispatch_queued_events(queued);
2341        Ok(())
2342    }
2343
2344    // ── Table convenience (position-based) ───────────────
2345
2346    /// Remove the table the cursor is currently inside.
2347    /// Returns an error if the cursor is not inside a table.
2348    pub fn remove_current_table(&self) -> Result<()> {
2349        let _settled = self.settle_transient_edits();
2350        let table = self.current_table().ok_or_else(|| {
2351            DocumentError::InvalidCursorContext("cursor is not inside a table".into())
2352        })?;
2353        self.remove_table(table.id())
2354    }
2355
2356    /// Insert a row above the cursor's current row.
2357    /// Returns an error if the cursor is not inside a table.
2358    pub fn insert_row_above(&self) -> Result<()> {
2359        let _settled = self.settle_transient_edits();
2360        let cell_ref = self.current_table_cell().ok_or_else(|| {
2361            DocumentError::InvalidCursorContext("cursor is not inside a table".into())
2362        })?;
2363        self.insert_table_row(cell_ref.table.id(), cell_ref.row)
2364    }
2365
2366    /// Insert a row below the cursor's current row.
2367    /// Returns an error if the cursor is not inside a table.
2368    pub fn insert_row_below(&self) -> Result<()> {
2369        let _settled = self.settle_transient_edits();
2370        let cell_ref = self.current_table_cell().ok_or_else(|| {
2371            DocumentError::InvalidCursorContext("cursor is not inside a table".into())
2372        })?;
2373        self.insert_table_row(cell_ref.table.id(), cell_ref.row + 1)
2374    }
2375
2376    /// Insert a column before the cursor's current column.
2377    /// Returns an error if the cursor is not inside a table.
2378    pub fn insert_column_before(&self) -> Result<()> {
2379        let _settled = self.settle_transient_edits();
2380        let cell_ref = self.current_table_cell().ok_or_else(|| {
2381            DocumentError::InvalidCursorContext("cursor is not inside a table".into())
2382        })?;
2383        self.insert_table_column(cell_ref.table.id(), cell_ref.column)
2384    }
2385
2386    /// Insert a column after the cursor's current column.
2387    /// Returns an error if the cursor is not inside a table.
2388    pub fn insert_column_after(&self) -> Result<()> {
2389        let _settled = self.settle_transient_edits();
2390        let cell_ref = self.current_table_cell().ok_or_else(|| {
2391            DocumentError::InvalidCursorContext("cursor is not inside a table".into())
2392        })?;
2393        self.insert_table_column(cell_ref.table.id(), cell_ref.column + 1)
2394    }
2395
2396    /// Remove the row at the cursor's current position.
2397    /// Returns an error if the cursor is not inside a table.
2398    pub fn remove_current_row(&self) -> Result<()> {
2399        let _settled = self.settle_transient_edits();
2400        let cell_ref = self.current_table_cell().ok_or_else(|| {
2401            DocumentError::InvalidCursorContext("cursor is not inside a table".into())
2402        })?;
2403        self.remove_table_row(cell_ref.table.id(), cell_ref.row)
2404    }
2405
2406    /// Remove the column at the cursor's current position.
2407    /// Returns an error if the cursor is not inside a table.
2408    pub fn remove_current_column(&self) -> Result<()> {
2409        let _settled = self.settle_transient_edits();
2410        let cell_ref = self.current_table_cell().ok_or_else(|| {
2411            DocumentError::InvalidCursorContext("cursor is not inside a table".into())
2412        })?;
2413        self.remove_table_column(cell_ref.table.id(), cell_ref.column)
2414    }
2415
2416    /// Merge cells spanned by the current selection.
2417    ///
2418    /// Both cursor position and anchor must be inside the same table.
2419    /// The cell range is derived from the cells at position and anchor.
2420    /// Returns an error if the cursor is not inside a table or position
2421    /// and anchor are in different tables.
2422    pub fn merge_selected_cells(&self) -> Result<()> {
2423        let _settled = self.settle_transient_edits();
2424        let pos_cell = self.current_table_cell().ok_or_else(|| {
2425            DocumentError::InvalidCursorContext("cursor position is not inside a table".into())
2426        })?;
2427
2428        // The anchor's cell, read as the position's is, as a caret's (see `table_cell_at`):
2429        // at the end of a cell's text, that cell. Read at the character index, it was the
2430        // next cell, and a selection from the end of a cell's text into the next merged the
2431        // next cell alone.
2432        let (_pos, anchor) = self.read_cursor();
2433        let anchor_cell = self.table_cell_at(anchor).ok_or_else(|| {
2434            DocumentError::InvalidCursorContext("cursor anchor is not inside a table".into())
2435        })?;
2436
2437        if pos_cell.table.id() != anchor_cell.table.id() {
2438            return Err(DocumentError::InvalidArgument(
2439                "position and anchor are in different tables".into(),
2440            ));
2441        }
2442
2443        let start_row = pos_cell.row.min(anchor_cell.row);
2444        let start_col = pos_cell.column.min(anchor_cell.column);
2445        let end_row = pos_cell.row.max(anchor_cell.row);
2446        let end_col = pos_cell.column.max(anchor_cell.column);
2447
2448        self.merge_table_cells(pos_cell.table.id(), start_row, start_col, end_row, end_col)
2449    }
2450
2451    /// Split the cell at the cursor's current position.
2452    /// Returns an error if the cursor is not inside a table.
2453    pub fn split_current_cell(&self, split_rows: usize, split_columns: usize) -> Result<()> {
2454        let _settled = self.settle_transient_edits();
2455        let cell_ref = self.current_table_cell().ok_or_else(|| {
2456            DocumentError::InvalidCursorContext("cursor is not inside a table".into())
2457        })?;
2458        // Get the cell entity ID from the table handle
2459        let cell = cell_ref
2460            .table
2461            .cell(cell_ref.row, cell_ref.column)
2462            .ok_or_else(|| DocumentError::NotFound("cell not found".into()))?;
2463        // TextTableCell stores cell_id
2464        self.split_table_cell(cell.id(), split_rows, split_columns)
2465    }
2466
2467    /// Set formatting on the table the cursor is currently inside.
2468    /// Returns an error if the cursor is not inside a table.
2469    pub fn set_current_table_format(&self, format: &crate::flow::TableFormat) -> Result<()> {
2470        let _settled = self.settle_transient_edits();
2471        let table = self.current_table().ok_or_else(|| {
2472            DocumentError::InvalidCursorContext("cursor is not inside a table".into())
2473        })?;
2474        self.set_table_format(table.id(), format)
2475    }
2476
2477    /// Set formatting on the cell the cursor is currently inside.
2478    /// Returns an error if the cursor is not inside a table.
2479    pub fn set_current_cell_format(&self, format: &crate::flow::CellFormat) -> Result<()> {
2480        let _settled = self.settle_transient_edits();
2481        let cell_ref = self.current_table_cell().ok_or_else(|| {
2482            DocumentError::InvalidCursorContext("cursor is not inside a table".into())
2483        })?;
2484        let cell = cell_ref
2485            .table
2486            .cell(cell_ref.row, cell_ref.column)
2487            .ok_or_else(|| DocumentError::NotFound("cell not found".into()))?;
2488        self.set_table_cell_format(cell.id(), format)
2489    }
2490
2491    // ── Cell selection queries ────────────────────────────────
2492
2493    /// Determine the kind of selection the cursor currently has.
2494    ///
2495    /// Returns [`Cells`](crate::SelectionKind::Cells) when position and anchor are in
2496    /// different cells of the same table (rectangular cell selection), or
2497    /// when an explicit cell-selection override is active.
2498    pub fn selection_kind(&self) -> crate::flow::SelectionKind {
2499        use crate::flow::{CellRange, SelectionKind};
2500
2501        // Check override first
2502        {
2503            let d = self.data.lock();
2504            if let Some(ref range) = d.cell_selection_override {
2505                return SelectionKind::Cells(range.clone());
2506            }
2507            if d.position == d.anchor {
2508                return SelectionKind::None;
2509            }
2510        }
2511
2512        let (pos, anchor) = self.read_cursor();
2513
2514        // Look up table cell for position and anchor
2515        let pos_cell = self.table_cell_at(pos);
2516        let anchor_cell = self.selection_anchor_cell(anchor, pos_cell.as_ref());
2517
2518        match (&pos_cell, &anchor_cell) {
2519            (None, None) => {
2520                // Both endpoints are outside tables. Check whether a table
2521                // sits between them — if so, all its cells must be selected
2522                // (Word behaviour).
2523                let (start, end) = (pos.min(anchor), pos.max(anchor));
2524                if let Some(t) = self.find_table_between(start, end) {
2525                    let table_id = t.id();
2526                    let rows = t.rows();
2527                    let cols = t.columns();
2528                    let range = CellRange {
2529                        table_id,
2530                        start_row: 0,
2531                        start_col: 0,
2532                        end_row: if rows > 0 { rows - 1 } else { 0 },
2533                        end_col: if cols > 0 { cols - 1 } else { 0 },
2534                    };
2535                    let spans = self.collect_cell_spans(table_id);
2536                    SelectionKind::Mixed {
2537                        cell_range: range.expand_for_spans(&spans),
2538                        text_before: true,
2539                        text_after: true,
2540                    }
2541                } else {
2542                    SelectionKind::Text
2543                }
2544            }
2545            (Some(pc), Some(ac)) => {
2546                if pc.table.id() != ac.table.id() {
2547                    // Different tables — treat as text (whole tables selected between them)
2548                    return SelectionKind::Text;
2549                }
2550                if pc.row == ac.row && pc.column == ac.column {
2551                    // Same cell — text selection within one cell
2552                    return SelectionKind::Text;
2553                }
2554                // Different cells, same table — rectangular cell selection
2555                let range = CellRange {
2556                    table_id: pc.table.id(),
2557                    start_row: pc.row.min(ac.row),
2558                    start_col: pc.column.min(ac.column),
2559                    end_row: pc.row.max(ac.row),
2560                    end_col: pc.column.max(ac.column),
2561                };
2562                let spans = self.collect_cell_spans(pc.table.id());
2563                SelectionKind::Cells(range.expand_for_spans(&spans))
2564            }
2565            (Some(tc), None) | (None, Some(tc)) => {
2566                // One endpoint inside a table, the other outside — mixed
2567                // selection.  Following Word behaviour, select ALL cells in
2568                // the table (not just from the entry edge to the cursor row).
2569                let table_id = tc.table.id();
2570                let rows = tc.table.rows();
2571                let cols = tc.table.columns();
2572
2573                let inside_pos = if pos_cell.is_some() { pos } else { anchor };
2574                let outside_pos = if pos_cell.is_some() { anchor } else { pos };
2575
2576                let text_before = outside_pos < inside_pos;
2577                let text_after = !text_before;
2578
2579                let range = CellRange {
2580                    table_id,
2581                    start_row: 0,
2582                    start_col: 0,
2583                    end_row: if rows > 0 { rows - 1 } else { 0 },
2584                    end_col: if cols > 0 { cols - 1 } else { 0 },
2585                };
2586                let spans = self.collect_cell_spans(table_id);
2587                SelectionKind::Mixed {
2588                    cell_range: range.expand_for_spans(&spans),
2589                    text_before,
2590                    text_after,
2591                }
2592            }
2593        }
2594    }
2595
2596    /// Returns `true` when the current selection involves whole-cell selection.
2597    pub fn is_cell_selection(&self) -> bool {
2598        matches!(
2599            self.selection_kind(),
2600            crate::flow::SelectionKind::Cells(_) | crate::flow::SelectionKind::Mixed { .. }
2601        )
2602    }
2603
2604    /// Returns the rectangular cell range if the cursor has a cell selection.
2605    pub fn selected_cell_range(&self) -> Option<crate::flow::CellRange> {
2606        match self.selection_kind() {
2607            crate::flow::SelectionKind::Cells(r) => Some(r),
2608            crate::flow::SelectionKind::Mixed { cell_range, .. } => Some(cell_range),
2609            _ => None,
2610        }
2611    }
2612
2613    /// Returns all cells in the selected rectangular range.
2614    pub fn selected_cells(&self) -> Vec<TableCellRef> {
2615        let range = match self.selected_cell_range() {
2616            Some(r) => r,
2617            None => return Vec::new(),
2618        };
2619        let table = TextTable {
2620            doc: self.doc.clone(),
2621            table_id: range.table_id,
2622        };
2623        let mut cells = Vec::new();
2624        for row in range.start_row..=range.end_row {
2625            for col in range.start_col..=range.end_col {
2626                if table.cell(row, col).is_some() {
2627                    cells.push(TableCellRef {
2628                        table: table.clone(),
2629                        row,
2630                        column: col,
2631                    });
2632                }
2633            }
2634        }
2635        cells
2636    }
2637
2638    // ── Explicit cell selection ─────────────────────────────
2639
2640    /// Set an explicit single-cell selection override.
2641    pub fn select_table_cell(&self, table_id: usize, row: usize, col: usize) {
2642        let mut d = self.data.lock();
2643        d.cell_selection_override = Some(crate::flow::CellRange {
2644            table_id,
2645            start_row: row,
2646            start_col: col,
2647            end_row: row,
2648            end_col: col,
2649        });
2650    }
2651
2652    /// Set an explicit rectangular cell-range selection override.
2653    pub fn select_cell_range(
2654        &self,
2655        table_id: usize,
2656        start_row: usize,
2657        start_col: usize,
2658        end_row: usize,
2659        end_col: usize,
2660    ) {
2661        let range = crate::flow::CellRange {
2662            table_id,
2663            start_row,
2664            start_col,
2665            end_row,
2666            end_col,
2667        };
2668        let spans = self.collect_cell_spans(table_id);
2669        let mut d = self.data.lock();
2670        d.cell_selection_override = Some(range.expand_for_spans(&spans));
2671    }
2672
2673    /// Clear any cell-selection override without changing position/anchor.
2674    pub fn clear_cell_selection(&self) {
2675        let mut d = self.data.lock();
2676        d.cell_selection_override = None;
2677    }
2678
2679    /// Compute (min_position, max_position) spanning all blocks in a cell range.
2680    /// Returns `None` if the table or cells cannot be found.
2681    fn cell_range_positions(&self, range: &CellRange) -> Option<(usize, usize)> {
2682        let inner = self.doc.lock();
2683        let main_frame_id = get_main_frame_id(&inner);
2684        // A table in a quotation is found too (see `flow_in_reading_order`).
2685        let flow = crate::text_frame::flow_in_reading_order(&inner, &self.doc, main_frame_id);
2686        drop(inner);
2687
2688        // Find the table matching the range's table_id
2689        let table = flow.into_iter().find_map(|e| match e {
2690            FlowElement::Table(t) if t.id() == range.table_id => Some(t),
2691            _ => None,
2692        })?;
2693
2694        let mut min_pos = usize::MAX;
2695        let mut max_pos = 0usize;
2696
2697        for row in range.start_row..=range.end_row {
2698            for col in range.start_col..=range.end_col {
2699                if let Some(cell) = table.cell(row, col) {
2700                    for block in cell.blocks() {
2701                        let bp = block.position();
2702                        let bl = block.length();
2703                        min_pos = min_pos.min(bp);
2704                        max_pos = max_pos.max(bp + bl);
2705                    }
2706                }
2707            }
2708        }
2709
2710        if min_pos == usize::MAX {
2711            return None;
2712        }
2713
2714        // Extend max_pos past the last block to ensure cross-cell detection
2715        Some((min_pos, max_pos + 1))
2716    }
2717
2718    // ── Cell selection helpers (private) ─────────────────────
2719
2720    /// Where the anchor of the table `table_id` stands, when the rope is the document's
2721    /// position space.
2722    fn table_anchor_position(&self, table_id: usize) -> Option<usize> {
2723        let inner = self.doc.lock();
2724        let store = inner.ctx.db_context.get_store();
2725        common::database::rope_helpers::table_anchor_position(
2726            store,
2727            table_id as common::types::EntityId,
2728        )
2729        .map(to_usize)
2730    }
2731
2732    /// Look up which table cell contains the given document position, if any.
2733    fn table_cell_at(&self, position: usize) -> Option<TableCellRef> {
2734        let inner = self.doc.lock();
2735        // The caret's block (see `block_at_caret_dto`): on a table's anchor, its first cell.
2736        let block_id = crate::inner::block_at_caret_dto(&inner.ctx, position)
2737            .ok()?
2738            .block_id as usize;
2739
2740        let block = crate::text_block::TextBlock {
2741            doc: self.doc.clone(),
2742            block_id,
2743        };
2744        drop(inner);
2745        block.table_cell()
2746    }
2747
2748    /// The cell a selection's fixed end `anchor` stands in, given the cell `position_cell`
2749    /// its moving end stands in, for the table trap of [`set_position`](Self::set_position)
2750    /// and for [`selection_kind`](Self::selection_kind).
2751    ///
2752    /// On a table's anchor, that is the table's first cell only when the moving end is in
2753    /// the same table. A selection from a table's anchor that runs back before the table ends
2754    /// there and holds none of it; one that runs past the table holds it whole, from its
2755    /// start; one that runs into a table before it takes that table in whole, as the table
2756    /// trap does for any selection entering a table from outside it. Read as in the first cell
2757    /// whatever the moving end did, a selection started on the anchor, where the Right or the
2758    /// Down arrow from the paragraph before a table leaves the caret, jumped forward over the
2759    /// table when dragged back into that paragraph, and dragged into the table before it was
2760    /// taken for one between two tables: the cut emptied that table's cells, left its grid,
2761    /// and the paste put their words back into its first cell. A moving end on a table's
2762    /// anchor stands in the first cell, as a caret there does: moved onto it from the
2763    /// paragraph before, a selection takes the table in.
2764    fn selection_anchor_cell(
2765        &self,
2766        anchor: usize,
2767        position_cell: Option<&TableCellRef>,
2768    ) -> Option<TableCellRef> {
2769        let cell = self.table_cell_at(anchor)?;
2770        let on_table_anchor = {
2771            let inner = self.doc.lock();
2772            common::database::rope_helpers::snap_off_table_anchor(
2773                inner.ctx.db_context.get_store(),
2774                to_i64(anchor),
2775                true,
2776            ) != to_i64(anchor)
2777        };
2778        let moving_end_in_the_table =
2779            position_cell.is_some_and(|moving| moving.table.id() == cell.table.id());
2780        (!on_table_anchor || moving_end_in_the_table).then_some(cell)
2781    }
2782
2783    /// `position`, or, when it falls on a table's anchor, the end of what comes before the
2784    /// table, for the moves that step back over the text. A lookup on the anchor reads the
2785    /// table's first cell, as a caret there does (see `block_at_caret_dto`): stepping back
2786    /// from the start of that cell met the cell again, and a word to the left, a paragraph
2787    /// up or the previous word went nowhere.
2788    fn back_off_table_anchor(&self, position: usize) -> usize {
2789        let inner = self.doc.lock();
2790        to_usize(common::database::rope_helpers::snap_off_table_anchor(
2791            inner.ctx.db_context.get_store(),
2792            to_i64(position),
2793            false,
2794        ))
2795    }
2796
2797    /// Find the first table whose cell blocks fall within the range `(start, end)`.
2798    fn find_table_between(&self, start: usize, end: usize) -> Option<TextTable> {
2799        let inner = self.doc.lock();
2800        let main_frame_id = get_main_frame_id(&inner);
2801        // A table in a quotation is found too (see `flow_in_reading_order`).
2802        let flow = crate::text_frame::flow_in_reading_order(&inner, &self.doc, main_frame_id);
2803        drop(inner);
2804
2805        for elem in flow {
2806            if let FlowElement::Table(t) = elem {
2807                // Check whether the first cell's block position is between
2808                // the two endpoints (i.e. the table is inside the range).
2809                if let Some(first_cell) = t.cell(0, 0) {
2810                    let blocks = first_cell.blocks();
2811                    if let Some(fb) = blocks.first() {
2812                        let p = fb.position();
2813                        if p > start && p < end {
2814                            return Some(t);
2815                        }
2816                    }
2817                }
2818            }
2819        }
2820        None
2821    }
2822
2823    /// Collect `(row, col, row_span, col_span)` tuples for all cells in a table.
2824    fn collect_cell_spans(&self, table_id: usize) -> Vec<(usize, usize, usize, usize)> {
2825        let inner = self.doc.lock();
2826        let table_dto =
2827            match frontend::commands::table_commands::get_table(&inner.ctx, &(table_id as u64))
2828                .ok()
2829                .flatten()
2830            {
2831                Some(t) => t,
2832                None => return Vec::new(),
2833            };
2834
2835        let mut spans = Vec::with_capacity(table_dto.cells.len());
2836        for &cell_id in &table_dto.cells {
2837            if let Some(cell) =
2838                frontend::commands::table_cell_commands::get_table_cell(&inner.ctx, &cell_id)
2839                    .ok()
2840                    .flatten()
2841            {
2842                spans.push((
2843                    cell.row as usize,
2844                    cell.column as usize,
2845                    cell.row_span.max(1) as usize,
2846                    cell.column_span.max(1) as usize,
2847                ));
2848            }
2849        }
2850        spans
2851    }
2852
2853    /// Delete the character after the cursor (Delete key).
2854    pub fn delete_char(&self) -> Result<()> {
2855        let _settled = self.settle_transient_edits();
2856        let (pos, anchor) = self.read_cursor();
2857        let (del_pos, del_anchor) = if pos != anchor {
2858            (pos, anchor)
2859        } else {
2860            // No-op at end of document (symmetric with delete_previous_char at start)
2861            let end = {
2862                let inner = self.doc.lock();
2863                max_cursor_position_of(&inner).unwrap_or(0)
2864            };
2865            if pos >= end {
2866                return Ok(());
2867            }
2868            // Delete the whole grapheme cluster after the cursor so a
2869            // single Delete on `👋🏻` or `e\u{0301}` removes the
2870            // user-perceived character, not just its first scalar.
2871            let to = self.next_grapheme_boundary(pos);
2872            if to == pos {
2873                return Ok(());
2874            }
2875            (pos, to)
2876        };
2877        self.do_delete(del_pos, del_anchor, pos != anchor)
2878    }
2879
2880    /// Delete the character before the cursor (Backspace key).
2881    pub fn delete_previous_char(&self) -> Result<()> {
2882        let _settled = self.settle_transient_edits();
2883        let (pos, anchor) = self.read_cursor();
2884        let (del_pos, del_anchor) = if pos != anchor {
2885            (pos, anchor)
2886        } else if pos > 0 {
2887            let from = self.prev_grapheme_boundary(pos);
2888            if from == pos {
2889                return Ok(());
2890            }
2891            (from, pos)
2892        } else {
2893            return Ok(());
2894        };
2895        self.do_delete(del_pos, del_anchor, pos != anchor)
2896    }
2897
2898    /// Delete the selected text. Returns the deleted text. No-op if no selection.
2899    ///
2900    /// A selection edits the text it starts in: the main text, or the one footnote body it
2901    /// starts in. Selecting from the main text to the end of the document, or all of it,
2902    /// takes the main text and leaves the notes' bodies, which come after it, as they are;
2903    /// [`selection`](Self::selection) copies the same text. A body stays even when the
2904    /// removal took every reference to its note, as a cut does before the paste that puts
2905    /// the references back: the document keeps it, every save writes it as a definition no
2906    /// reference names, and no move of a caret from the main text reaches it.
2907    /// [`clear`](crate::TextDocument::clear) and the loads replace everything, bodies
2908    /// included.
2909    ///
2910    /// A removal that leaves the text empty leaves this cursor standing for all of that
2911    /// empty text: a fragment inserted next at the caret replaces the text, as it would have
2912    /// replaced the selection (see [`insert_fragment`](Self::insert_fragment)), so a cut of
2913    /// all of a text pasted back is the text as it was. Typed text keeps the formatting of
2914    /// the empty paragraph, which is the first removed paragraph's.
2915    ///
2916    /// A selection with one end in a table and the other outside it takes the whole table,
2917    /// as [`selection`](Self::selection) copies it (see
2918    /// [`set_position`](Self::set_position)). A selection from inside one paragraph to
2919    /// inside another, holding whole the tables between them, joins the two paragraphs, as
2920    /// a selection of text does.
2921    ///
2922    /// Backspace and Delete across a paragraph that would bring an image or a footnote
2923    /// reference into a code block join nothing, and a selection across one takes its text
2924    /// and joins nothing.
2925    pub fn remove_selected_text(&self) -> Result<String> {
2926        let _settled = self.settle_transient_edits();
2927        let (pos, anchor) = self.read_cursor();
2928        if pos == anchor {
2929            return Ok(String::new());
2930        }
2931        let (deleted, queued) = {
2932            let mut inner = self.doc.lock();
2933            self.remove_locked(&mut inner, pos, anchor, Recording::History)?
2934        };
2935        crate::inner::dispatch_queued_events(queued);
2936        Ok(deleted)
2937    }
2938
2939    /// Remove the selection `[pos, anchor)` (either order), the document locked, recorded
2940    /// as `recording` says, and leave this cursor where it was. Returns the removed text
2941    /// and the events to dispatch.
2942    pub(crate) fn remove_locked(
2943        &self,
2944        inner: &mut TextDocumentInner,
2945        pos: usize,
2946        anchor: usize,
2947        recording: Recording,
2948    ) -> Result<(String, QueuedEvents)> {
2949        let (result, removed) = measured_delete(inner, pos, anchor, true, recording)?;
2950        check_transient_change(recording, pos, anchor, removed)?;
2951        let stands_for_the_empty_text = self.finish_delete(
2952            inner,
2953            pos.min(anchor),
2954            removed,
2955            result.new_position,
2956            true,
2957            recording,
2958        );
2959        Ok((
2960            result.deleted_text,
2961            self.announce_deletion(inner, stands_for_the_empty_text, recording),
2962        ))
2963    }
2964
2965    // ── List operations ──────────────────────────────────────
2966
2967    /// Returns the list that the block at the cursor position belongs to,
2968    /// or `None` if the current block is not a list item.
2969    ///
2970    /// The block is the caret's (see [`TextDocument::block_at_caret`](crate::TextDocument::block_at_caret)):
2971    /// at the end of a list item, that item. This and the other list helpers
2972    /// acting on the current block used to read the block at the character
2973    /// index, the next paragraph there, so moving an item a level in or out
2974    /// with the caret at the end of its text moved the item after it.
2975    pub fn current_list(&self) -> Option<crate::TextList> {
2976        let pos = self.position();
2977        let inner = self.doc.lock();
2978        let block_info = crate::inner::block_at_caret_dto(&inner.ctx, pos).ok()?;
2979        let block = crate::text_block::TextBlock {
2980            doc: self.doc.clone(),
2981            block_id: block_info.block_id as usize,
2982        };
2983        drop(inner);
2984        block.list()
2985    }
2986
2987    /// Turn the block(s) in the selection into a list.
2988    ///
2989    /// The blocks may sit in the main text, a quotation, a table cell or a
2990    /// footnote's body. A list runs on inside one frame only, and only as long
2991    /// as no quotation or table comes between its items, so a selection
2992    /// crossing one makes a list on each side of it. Blocks that leave another
2993    /// list for this one take that list away when they were all it held.
2994    pub fn create_list(&self, style: ListStyle) -> Result<()> {
2995        let _settled = self.settle_transient_edits();
2996        let (pos, anchor) = self.read_cursor();
2997        let queued = {
2998            let mut inner = self.doc.lock();
2999            let dto = frontend::document_editing::CreateListDto {
3000                position: to_i64(pos),
3001                anchor: to_i64(anchor),
3002                style: style.clone(),
3003            };
3004            document_editing_commands::create_list(&inner.ctx, Some(inner.stack_id), &dto)?;
3005            inner.modified = true;
3006            inner.rehighlight_affected(pos.min(anchor));
3007            inner.queue_event(DocumentEvent::ContentsChanged {
3008                position: pos.min(anchor),
3009                chars_removed: 0,
3010                chars_added: 0,
3011                blocks_affected: 1,
3012            });
3013            self.queue_undo_redo_event(&mut inner)
3014        };
3015        crate::inner::dispatch_queued_events(queued);
3016        Ok(())
3017    }
3018
3019    /// Insert a new list item at the cursor position.
3020    pub fn insert_list(&self, style: ListStyle) -> Result<()> {
3021        let _settled = self.settle_transient_edits();
3022        let (pos, anchor) = self.read_cursor();
3023        let queued = {
3024            let mut inner = self.doc.lock();
3025            let dto = frontend::document_editing::InsertListDto {
3026                position: to_i64(pos),
3027                anchor: to_i64(anchor),
3028                style: style.clone(),
3029            };
3030            let result =
3031                document_editing_commands::insert_list(&inner.ctx, Some(inner.stack_id), &dto)?;
3032            let edit_pos = pos.min(anchor);
3033            let removed = pos.max(anchor) - edit_pos;
3034            let new_pos = to_usize(result.new_position);
3035            self.finish_edit_ext(
3036                &mut inner,
3037                edit_pos,
3038                removed,
3039                Insertion {
3040                    at: edit_pos,
3041                    removed: 0,
3042                    added: new_pos.saturating_sub(edit_pos),
3043                },
3044                new_pos,
3045                1,
3046                false,
3047            )
3048        };
3049        crate::inner::dispatch_queued_events(queued);
3050        Ok(())
3051    }
3052
3053    /// Set formatting on a list by its ID.
3054    pub fn set_list_format(&self, list_id: usize, format: &crate::ListFormat) -> Result<()> {
3055        let _settled = self.settle_transient_edits();
3056        let queued = {
3057            let mut inner = self.doc.lock();
3058            let dto = format.to_set_dto(list_id);
3059            document_formatting_commands::set_list_format(&inner.ctx, Some(inner.stack_id), &dto)?;
3060            inner.modified = true;
3061            inner.queue_event(DocumentEvent::FormatChanged {
3062                position: 0,
3063                length: 0,
3064                kind: crate::flow::FormatChangeKind::List,
3065            });
3066            self.queue_undo_redo_event(&mut inner)
3067        };
3068        crate::inner::dispatch_queued_events(queued);
3069        Ok(())
3070    }
3071
3072    /// Set formatting on the list that the current block belongs to.
3073    /// Returns an error if the cursor is not inside a list item.
3074    pub fn set_current_list_format(&self, format: &crate::ListFormat) -> Result<()> {
3075        let _settled = self.settle_transient_edits();
3076        let list = self.current_list().ok_or_else(|| {
3077            DocumentError::InvalidCursorContext("cursor is not inside a list".into())
3078        })?;
3079        self.set_list_format(list.id(), format)
3080    }
3081
3082    /// Add a block to a list by their IDs.
3083    pub fn add_block_to_list(&self, block_id: usize, list_id: usize) -> Result<()> {
3084        let _settled = self.settle_transient_edits();
3085        let queued = {
3086            let mut inner = self.doc.lock();
3087            let dto = frontend::document_editing::AddBlockToListDto {
3088                block_id: to_i64(block_id),
3089                list_id: to_i64(list_id),
3090            };
3091            document_editing_commands::add_block_to_list(&inner.ctx, Some(inner.stack_id), &dto)?;
3092            inner.modified = true;
3093            // List membership is a formatting/layout concern, not a text
3094            // change — fire FormatChanged so consumers re-layout (the
3095            // block's horizontal position and list marker depend on
3096            // its list assignment). ContentsChanged with position=0
3097            // was misleading and caused incremental relayouts to
3098            // re-shape the wrong block.
3099            inner.queue_event(DocumentEvent::FormatChanged {
3100                position: 0,
3101                length: 0,
3102                kind: crate::flow::FormatChangeKind::List,
3103            });
3104            self.queue_undo_redo_event(&mut inner)
3105        };
3106        crate::inner::dispatch_queued_events(queued);
3107        Ok(())
3108    }
3109
3110    /// Add the block at the cursor position to a list: the caret's block, as
3111    /// [`current_list`](Self::current_list) reads it.
3112    pub fn add_current_block_to_list(&self, list_id: usize) -> Result<()> {
3113        let _settled = self.settle_transient_edits();
3114        let pos = self.position();
3115        let inner = self.doc.lock();
3116        let block_info = crate::inner::block_at_caret_dto(&inner.ctx, pos)?;
3117        drop(inner);
3118        self.add_block_to_list(block_info.block_id as usize, list_id)
3119    }
3120
3121    /// Remove a block from its list by block ID.
3122    pub fn remove_block_from_list(&self, block_id: usize) -> Result<()> {
3123        let _settled = self.settle_transient_edits();
3124        let queued = {
3125            let mut inner = self.doc.lock();
3126            let dto = frontend::document_editing::RemoveBlockFromListDto {
3127                block_id: to_i64(block_id),
3128            };
3129            document_editing_commands::remove_block_from_list(
3130                &inner.ctx,
3131                Some(inner.stack_id),
3132                &dto,
3133            )?;
3134            inner.modified = true;
3135            // See `add_block_to_list` — list-membership is a
3136            // formatting/layout change, not a text content change.
3137            inner.queue_event(DocumentEvent::FormatChanged {
3138                position: 0,
3139                length: 0,
3140                kind: crate::flow::FormatChangeKind::List,
3141            });
3142            self.queue_undo_redo_event(&mut inner)
3143        };
3144        crate::inner::dispatch_queued_events(queued);
3145        Ok(())
3146    }
3147
3148    /// Remove the block at the cursor position from its list: the caret's
3149    /// block, as [`current_list`](Self::current_list) reads it.
3150    /// Returns an error if the current block is not a list item.
3151    pub fn remove_current_block_from_list(&self) -> Result<()> {
3152        let _settled = self.settle_transient_edits();
3153        let pos = self.position();
3154        let inner = self.doc.lock();
3155        let block_info = crate::inner::block_at_caret_dto(&inner.ctx, pos)?;
3156        drop(inner);
3157        self.remove_block_from_list(block_info.block_id as usize)
3158    }
3159
3160    /// Remove a list item by index within the list.
3161    /// Resolves the index to a block, then removes it from the list.
3162    pub fn remove_list_item(&self, list_id: usize, index: usize) -> Result<()> {
3163        let _settled = self.settle_transient_edits();
3164        let list = crate::text_list::TextList {
3165            doc: self.doc.clone(),
3166            list_id,
3167        };
3168        let block = list.item(index).ok_or_else(|| {
3169            DocumentError::OutOfRange(format!("list item index {index} out of range"))
3170        })?;
3171        self.remove_block_from_list(block.id())
3172    }
3173
3174    // ── Format queries ───────────────────────────────────────
3175
3176    /// Get the character format at the cursor position. Reads the
3177    /// covering `FormatRun` (or image anchor) directly from the store.
3178    pub fn char_format(&self) -> Result<TextFormat> {
3179        let pos = self.position();
3180        let inner = self.doc.lock();
3181
3182        // Locate the block containing the cursor.
3183        let dto = frontend::document_inspection::GetBlockAtPositionDto {
3184            position: to_i64(pos),
3185        };
3186        let block_info = document_inspection_commands::get_block_at_position(&inner.ctx, &dto)?;
3187        let block_id = block_info.block_id as u64;
3188        let mut block_dto =
3189            frontend::commands::block_commands::get_block(&inner.ctx, &block_id)?
3190                .ok_or_else(|| DocumentError::NotFound("block not found at position".into()))?;
3191        let store = inner.ctx.db_context.get_store();
3192        crate::inner::refresh_block_position(&mut block_dto, store);
3193
3194        // Convert document-wide char position to a byte offset within
3195        // the block's content (read from the rope).
3196        let local_char = pos.saturating_sub(block_dto.document_position as usize);
3197        let entity: common::entities::Block = block_dto.clone().into();
3198        let plain_owned = common::database::rope_helpers::block_content_via_store(&entity, store);
3199        let plain: &str = &plain_owned;
3200        let byte_offset: u32 = plain
3201            .char_indices()
3202            .nth(local_char)
3203            .map(|(b, _)| b as u32)
3204            .unwrap_or(plain.len() as u32);
3205
3206        // If there's an image anchor at this exact byte position, use
3207        // its format.
3208        let images = store
3209            .block_images
3210            .read()
3211            .get(&block_id)
3212            .cloned()
3213            .unwrap_or_default();
3214        if let Some(img) = images.iter().find(|i| i.byte_offset == byte_offset) {
3215            return Ok(TextFormat::from(&img.format));
3216        }
3217
3218        // Otherwise find the FormatRun covering the byte position.
3219        let runs = store
3220            .format_runs
3221            .read()
3222            .get(&block_id)
3223            .cloned()
3224            .unwrap_or_default();
3225        let fmt = runs
3226            .iter()
3227            .find(|r| r.byte_start <= byte_offset && byte_offset < r.byte_end)
3228            .map(|r| TextFormat::from(&r.format))
3229            .unwrap_or_default();
3230        Ok(fmt)
3231    }
3232
3233    /// Get the block format of the block containing the cursor.
3234    ///
3235    /// Resolved with caret semantics, as "containing the cursor" says: a cursor at the end of
3236    /// a paragraph is still in it. Reading the character-index answer instead reported the
3237    /// NEXT paragraph's format there — which is what the editor's format panel showed for the
3238    /// whole time the caret sat at the end of the line being typed.
3239    pub fn block_format(&self) -> Result<BlockFormat> {
3240        let pos = self.position();
3241        let inner = self.doc.lock();
3242        let block_info = crate::inner::block_at_caret_dto(&inner.ctx, pos)?;
3243        let block_id = block_info.block_id as u64;
3244        let block = frontend::commands::block_commands::get_block(&inner.ctx, &block_id)?
3245            .ok_or_else(|| DocumentError::NotFound("block not found".into()))?;
3246        Ok(BlockFormat::from(&block))
3247    }
3248
3249    // ── Format application ───────────────────────────────────
3250
3251    /// Set the character format for the selection.
3252    pub fn set_char_format(&self, format: &TextFormat) -> Result<()> {
3253        let _settled = self.settle_transient_edits();
3254        let (pos, anchor) = self.read_cursor();
3255        let queued = {
3256            let mut inner = self.doc.lock();
3257            let dto = format.to_set_dto(pos, anchor);
3258            document_formatting_commands::set_text_format(&inner.ctx, Some(inner.stack_id), &dto)?;
3259            let start = pos.min(anchor);
3260            let length = pos.max(anchor) - start;
3261            inner.modified = true;
3262            inner.queue_event(DocumentEvent::FormatChanged {
3263                position: start,
3264                length,
3265                kind: crate::flow::FormatChangeKind::Character,
3266            });
3267            self.queue_undo_redo_event(&mut inner)
3268        };
3269        crate::inner::dispatch_queued_events(queued);
3270        Ok(())
3271    }
3272
3273    /// The hyperlink the cursor sits in, with its full reach.
3274    ///
3275    /// A link has no identity of its own — it is a stretch of runs agreeing on
3276    /// a destination — so this reports the *extent*, coalesced across any runs
3277    /// an inner bold or italic split it into. See [`LinkExtent`].
3278    ///
3279    /// `None` when the cursor is not on a link. Uses the same caret semantics
3280    /// as [`block_format`](Self::block_format): a cursor at the end of a link
3281    /// is still in it.
3282    pub fn link_at_caret(&self) -> Option<LinkExtent> {
3283        let pos = self.position();
3284        let block_id = {
3285            let inner = self.doc.lock();
3286            crate::inner::block_at_caret_dto(&inner.ctx, pos)
3287                .ok()?
3288                .block_id as usize
3289        };
3290        let block = TextBlock {
3291            doc: self.doc.clone(),
3292            block_id,
3293        };
3294        crate::link_extent::link_extent_at(&block, pos)
3295    }
3296
3297    /// Remove the hyperlink from the selection.
3298    ///
3299    /// Not expressible through [`merge_char_format`](Self::merge_char_format):
3300    /// its fields merge, so `anchor_href: None` means "leave the link alone",
3301    /// never "take it off". Which is why the removal is its own verb, and why
3302    /// [`TextFormat::clear_link`](crate::TextFormat::clear_link) exists as a
3303    /// flag rather than as an absent field.
3304    ///
3305    /// Note the selection must be non-empty — a zero-width range formats
3306    /// nothing, here as everywhere else. Callers editing an existing link
3307    /// should select its [`LinkExtent`] first.
3308    pub fn clear_char_anchor(&self) -> Result<()> {
3309        let _settled = self.settle_transient_edits();
3310        self.merge_char_format(&TextFormat {
3311            clear_link: true,
3312            ..Default::default()
3313        })
3314    }
3315
3316    /// Merge a character format into the selection.
3317    pub fn merge_char_format(&self, format: &TextFormat) -> Result<()> {
3318        let _settled = self.settle_transient_edits();
3319        let (pos, anchor) = self.read_cursor();
3320        let queued = {
3321            let mut inner = self.doc.lock();
3322            let dto = format.to_merge_dto(pos, anchor);
3323            document_formatting_commands::merge_text_format(
3324                &inner.ctx,
3325                Some(inner.stack_id),
3326                &dto,
3327            )?;
3328            let start = pos.min(anchor);
3329            let length = pos.max(anchor) - start;
3330            inner.modified = true;
3331            inner.queue_event(DocumentEvent::FormatChanged {
3332                position: start,
3333                length,
3334                kind: crate::flow::FormatChangeKind::Character,
3335            });
3336            self.queue_undo_redo_event(&mut inner)
3337        };
3338        crate::inner::dispatch_queued_events(queued);
3339        Ok(())
3340    }
3341
3342    /// Set the block format for the current block (or all blocks in selection).
3343    ///
3344    /// Making a paragraph that holds an image or a footnote reference a code block is
3345    /// refused, the text left as it was: a code block is verbatim text, which the save
3346    /// writes without them. A table cell's paragraph is never made a code block: a table
3347    /// cell is written as one line of text, and the other formats asked for still apply.
3348    pub fn set_block_format(&self, format: &BlockFormat) -> Result<()> {
3349        let _settled = self.settle_transient_edits();
3350        let (pos, anchor) = self.read_cursor();
3351        let queued = {
3352            let mut inner = self.doc.lock();
3353            let dto = format.to_set_dto(pos, anchor);
3354            document_formatting_commands::set_block_format(&inner.ctx, Some(inner.stack_id), &dto)?;
3355            let start = pos.min(anchor);
3356            let length = pos.max(anchor) - start;
3357            inner.modified = true;
3358            inner.queue_event(DocumentEvent::FormatChanged {
3359                position: start,
3360                length,
3361                kind: crate::flow::FormatChangeKind::Block,
3362            });
3363            self.queue_undo_redo_event(&mut inner)
3364        };
3365        crate::inner::dispatch_queued_events(queued);
3366        Ok(())
3367    }
3368
3369    /// Set the frame format.
3370    pub fn set_frame_format(&self, frame_id: usize, format: &FrameFormat) -> Result<()> {
3371        let _settled = self.settle_transient_edits();
3372        let (pos, anchor) = self.read_cursor();
3373        let queued = {
3374            let mut inner = self.doc.lock();
3375            let dto = format.to_set_dto(pos, anchor, frame_id);
3376            document_formatting_commands::set_frame_format(&inner.ctx, Some(inner.stack_id), &dto)?;
3377            let start = pos.min(anchor);
3378            let length = pos.max(anchor) - start;
3379            inner.modified = true;
3380            inner.queue_event(DocumentEvent::FormatChanged {
3381                position: start,
3382                length,
3383                kind: crate::flow::FormatChangeKind::Block,
3384            });
3385            self.queue_undo_redo_event(&mut inner)
3386        };
3387        crate::inner::dispatch_queued_events(queued);
3388        Ok(())
3389    }
3390
3391    // ── Edit blocks (composite undo) ─────────────────────────
3392
3393    /// Begin a group of operations that will be undone as a single unit.
3394    ///
3395    /// The block belongs to the document, not to this cursor: the edits of every cursor go
3396    /// into it while it is open, and any cursor's [`end_edit_block`](Self::end_edit_block)
3397    /// ends the innermost block open on the document. Every begin must be balanced by one
3398    /// end: a block left open keeps gathering every later edit, and none of them reaches
3399    /// the undo history until it ends.
3400    pub fn begin_edit_block(&self) {
3401        let mut inner = self.doc.lock();
3402        undo_redo_commands::begin_composite(&inner.ctx, Some(inner.stack_id));
3403        inner.edit_block_depth += 1;
3404    }
3405
3406    /// End the current edit block.
3407    pub fn end_edit_block(&self) {
3408        let mut inner = self.doc.lock();
3409        undo_redo_commands::end_composite(&inner.ctx);
3410        inner.end_edit_block_caret();
3411    }
3412
3413    /// Alias for [`begin_edit_block`](Self::begin_edit_block).
3414    ///
3415    /// Semantically indicates that the new composite should be merged with
3416    /// the previous one (e.g., consecutive keystrokes grouped into a single
3417    /// undo unit). The current backend treats this identically to
3418    /// `begin_edit_block`; future versions may implement automatic merging.
3419    pub fn join_previous_edit_block(&self) {
3420        self.begin_edit_block();
3421    }
3422
3423    // ── Private helpers ─────────────────────────────────────
3424
3425    /// Queue an `UndoRedoChanged` event and return all queued events for dispatch, having
3426    /// noted where the edit left this cursor for an undo and a redo of it.
3427    fn queue_undo_redo_event(&self, inner: &mut TextDocumentInner) -> QueuedEvents {
3428        inner.note_edit_caret(&self.data);
3429        let can_undo = undo_redo_commands::can_undo(&inner.ctx, Some(inner.stack_id));
3430        let can_redo = undo_redo_commands::can_redo(&inner.ctx, Some(inner.stack_id));
3431        inner.queue_event(DocumentEvent::UndoRedoChanged { can_undo, can_redo });
3432        inner.take_queued_events()
3433    }
3434
3435    fn do_delete(&self, pos: usize, anchor: usize, selection: bool) -> Result<()> {
3436        let queued = {
3437            let mut inner = self.doc.lock();
3438            let (result, removed) =
3439                measured_delete(&inner, pos, anchor, selection, Recording::History)?;
3440            let stands_for_the_empty_text = self.finish_delete(
3441                &mut inner,
3442                pos.min(anchor),
3443                removed,
3444                result.new_position,
3445                selection,
3446                Recording::History,
3447            );
3448            self.announce_deletion(&mut inner, stands_for_the_empty_text, Recording::History)
3449        };
3450        crate::inner::dispatch_queued_events(queued);
3451        Ok(())
3452    }
3453
3454    /// What follows a deletion: this cursor to where the use case put the
3455    /// caret, and, when anything went, the other cursors moved back by what
3456    /// went and the change announced. A deletion that removed nothing (see
3457    /// [`measured_delete`]) changed nothing to announce.
3458    ///
3459    /// A `selection` removed that left the text empty leaves this cursor
3460    /// standing for all of that empty text, as
3461    /// [`select(SelectionType::Document)`](Self::select) would: a paste that
3462    /// follows at the caret replaces the text, as a paste over the selection
3463    /// would have. Cutting all of a text and pasting it back put every
3464    /// paragraph into the formatting and quotations the empty paragraph the
3465    /// cut left had kept from the first one: a scene opening with an epigraph
3466    /// came back quoted from end to end. Typing keeps that formatting, as it
3467    /// does over a selection, and any other move or edit ends it.
3468    ///
3469    /// Returns whether the cursor stands for the empty text: the caller marks
3470    /// it so once the deletion's history is announced (see
3471    /// [`announce_deletion`](Self::announce_deletion)), which ends every
3472    /// whole-text selection taken before it.
3473    ///
3474    /// A transient deletion (`recording`) leaves the modified flag alone, as a transient
3475    /// insertion does (see [`finish_edit_as`](Self::finish_edit_as)), and never stands for
3476    /// the empty text: what it leaves is not what the recorded text is.
3477    fn finish_delete(
3478        &self,
3479        inner: &mut TextDocumentInner,
3480        edit_pos: usize,
3481        removed: usize,
3482        new_position: i64,
3483        selection: bool,
3484        recording: Recording,
3485    ) -> bool {
3486        let recorded = recording == Recording::History;
3487        let new_pos = to_usize(new_position);
3488        // A range that empties a table cell takes the cell's text from its
3489        // start, which can lie before the range's: the caret goes there, and
3490        // so does the start of what went.
3491        let edit_pos = edit_pos.min(new_pos);
3492        if removed > 0 {
3493            inner.adjust_cursors(edit_pos, removed, 0);
3494        }
3495        let stands_for_the_empty_text =
3496            recorded && selection && removed > 0 && new_pos == 0 && main_text_is_empty(inner);
3497        if stands_for_the_empty_text {
3498            // What the removal left, for a paste into it after an undo or a redo back to it
3499            // (see `EmptiedText`).
3500            inner.emptied_text = crate::inner::EmptiedText::of(inner.ctx.db_context.get_store());
3501        }
3502        {
3503            let mut d = self.data.lock();
3504            d.position = new_pos;
3505            d.anchor = new_pos;
3506            d.whole_text_selected = false;
3507            d.anchor_in_table = None;
3508        }
3509        if removed > 0 {
3510            if recorded {
3511                inner.modified = true;
3512            }
3513            inner.invalidate_text_cache();
3514            inner.rehighlight_affected(edit_pos);
3515            inner.queue_event(DocumentEvent::ContentsChanged {
3516                position: edit_pos,
3517                chars_removed: removed,
3518                chars_added: 0,
3519                blocks_affected: 1,
3520            });
3521        }
3522        inner.check_block_count_changed();
3523        inner.check_flow_changed();
3524        stands_for_the_empty_text
3525    }
3526
3527    /// Close a deletion: its history announced, which ends every whole-text selection (see
3528    /// `TextDocumentInner::end_whole_text_selections`), then this cursor marked as standing
3529    /// for the whole of the empty text when the removal left it so (see
3530    /// [`finish_delete`](Self::finish_delete)). Returns the events to dispatch.
3531    ///
3532    /// A transient deletion announces no history, which has not moved.
3533    fn announce_deletion(
3534        &self,
3535        inner: &mut TextDocumentInner,
3536        stands_for_the_empty_text: bool,
3537        recording: Recording,
3538    ) -> QueuedEvents {
3539        let queued = match recording {
3540            Recording::History => self.queue_undo_redo_event(inner),
3541            Recording::Transient => inner.take_queued_events(),
3542        };
3543        self.data.lock().whole_text_selected = stands_for_the_empty_text;
3544        queued
3545    }
3546
3547    /// Resolve a MoveOperation to a concrete position.
3548    fn resolve_move(&self, op: MoveOperation, n: usize) -> usize {
3549        let pos = self.position();
3550        match op {
3551            MoveOperation::NoMove => pos,
3552            MoveOperation::Start => 0,
3553            MoveOperation::End => {
3554                let inner = self.doc.lock();
3555                max_cursor_position_of(&inner).unwrap_or(pos)
3556            }
3557            MoveOperation::NextCharacter | MoveOperation::Right => {
3558                let mut cur = pos;
3559                for _ in 0..n {
3560                    let next = self.next_grapheme_boundary(cur);
3561                    if next == cur {
3562                        break;
3563                    }
3564                    cur = next;
3565                }
3566                cur
3567            }
3568            MoveOperation::PreviousCharacter | MoveOperation::Left => {
3569                let mut cur = pos;
3570                for _ in 0..n {
3571                    let prev = self.prev_grapheme_boundary(cur);
3572                    if prev == cur {
3573                        break;
3574                    }
3575                    cur = prev;
3576                }
3577                cur
3578            }
3579            MoveOperation::StartOfBlock | MoveOperation::StartOfLine => {
3580                let inner = self.doc.lock();
3581                let dto = frontend::document_inspection::GetBlockAtPositionDto {
3582                    position: to_i64(pos),
3583                };
3584                document_inspection_commands::get_block_at_position(&inner.ctx, &dto)
3585                    .map(|info| to_usize(info.block_start))
3586                    .unwrap_or(pos)
3587            }
3588            MoveOperation::EndOfBlock | MoveOperation::EndOfLine => {
3589                let inner = self.doc.lock();
3590                let dto = frontend::document_inspection::GetBlockAtPositionDto {
3591                    position: to_i64(pos),
3592                };
3593                document_inspection_commands::get_block_at_position(&inner.ctx, &dto)
3594                    .map(|info| to_usize(info.block_start) + to_usize(info.block_length))
3595                    .unwrap_or(pos)
3596            }
3597            MoveOperation::NextBlock => {
3598                let inner = self.doc.lock();
3599                let dto = frontend::document_inspection::GetBlockAtPositionDto {
3600                    position: to_i64(pos),
3601                };
3602                document_inspection_commands::get_block_at_position(&inner.ctx, &dto)
3603                    .map(|info| {
3604                        // Move past current block + 1 (block separator)
3605                        to_usize(info.block_start) + to_usize(info.block_length) + 1
3606                    })
3607                    .unwrap_or(pos)
3608            }
3609            MoveOperation::PreviousBlock => {
3610                let inner = self.doc.lock();
3611                let dto = frontend::document_inspection::GetBlockAtPositionDto {
3612                    position: to_i64(pos),
3613                };
3614                let block_start =
3615                    document_inspection_commands::get_block_at_position(&inner.ctx, &dto)
3616                        .map(|info| to_usize(info.block_start))
3617                        .unwrap_or(pos);
3618                if block_start >= 2 {
3619                    // Skip past the block separator (which maps to the current block), and
3620                    // back over a table's anchor when the block is the table's first cell:
3621                    // the anchor reads as that cell, and the move went nowhere.
3622                    let before = common::database::rope_helpers::snap_off_table_anchor(
3623                        inner.ctx.db_context.get_store(),
3624                        to_i64(block_start - 2),
3625                        false,
3626                    );
3627                    let prev_dto =
3628                        frontend::document_inspection::GetBlockAtPositionDto { position: before };
3629                    document_inspection_commands::get_block_at_position(&inner.ctx, &prev_dto)
3630                        .map(|info| to_usize(info.block_start))
3631                        .unwrap_or(0)
3632                } else {
3633                    0
3634                }
3635            }
3636            MoveOperation::NextWord | MoveOperation::EndOfWord | MoveOperation::WordRight => {
3637                let (_, end) = self.find_word_boundaries(pos);
3638                // Move past the word end to the next word
3639                if end == pos {
3640                    // Already at a boundary, skip whitespace
3641                    let inner = self.doc.lock();
3642                    let max_pos = max_cursor_position_of(&inner).unwrap_or(0);
3643                    let scan_len = max_pos.saturating_sub(pos).min(64);
3644                    if scan_len == 0 {
3645                        return pos;
3646                    }
3647                    let dto = frontend::document_inspection::GetTextAtPositionDto {
3648                        position: to_i64(pos),
3649                        length: to_i64(scan_len),
3650                    };
3651                    if let Ok(r) =
3652                        document_inspection_commands::get_text_at_position(&inner.ctx, &dto)
3653                    {
3654                        for (i, ch) in r.text.chars().enumerate() {
3655                            if ch.is_alphanumeric() || ch == '_' {
3656                                // Found start of next word, find its end
3657                                let word_pos = pos + i;
3658                                drop(inner);
3659                                let (_, word_end) = self.find_word_boundaries(word_pos);
3660                                return word_end;
3661                            }
3662                        }
3663                    }
3664                    pos + scan_len
3665                } else {
3666                    end
3667                }
3668            }
3669            MoveOperation::PreviousWord | MoveOperation::StartOfWord | MoveOperation::WordLeft => {
3670                let (start, _) = self.find_word_boundaries(pos);
3671                if start < pos {
3672                    start
3673                } else if pos > 0 {
3674                    // Cursor is at a word start or on whitespace — scan backwards
3675                    // to find the start of the previous word.
3676                    let mut search = pos - 1;
3677                    loop {
3678                        // Back over a table's anchor, which reads as the table's first cell:
3679                        // from the start of that cell, the scan met the cell's own word and
3680                        // stopped where it began.
3681                        search = self.back_off_table_anchor(search);
3682                        let (ws, we) = self.find_word_boundaries(search);
3683                        if ws < we && ws < pos {
3684                            // Found a word; return its start
3685                            break ws;
3686                        }
3687                        // Still on whitespace/non-word; keep scanning
3688                        if search == 0 {
3689                            break 0;
3690                        }
3691                        search -= 1;
3692                    }
3693                } else {
3694                    0
3695                }
3696            }
3697            MoveOperation::StartOfSentence | MoveOperation::PreviousSentence => {
3698                let mut cur = pos;
3699                for _ in 0..n.max(1) {
3700                    let start = match self.find_sentence_boundaries(cur) {
3701                        Some((start, _)) => start,
3702                        None => break,
3703                    };
3704                    // Already at the start (or `PreviousSentence`, which always steps): resolve
3705                    // again from just before it to reach the sentence before this one.
3706                    if start < cur && op == MoveOperation::StartOfSentence {
3707                        cur = start;
3708                    } else if cur > 0 {
3709                        // Back over a table's anchor (see `back_off_table_anchor`).
3710                        match self.find_sentence_boundaries(self.back_off_table_anchor(cur - 1)) {
3711                            Some((prev, _)) if prev < cur => cur = prev,
3712                            // Nothing but whitespace behind: fall back to the block edge rather
3713                            // than stalling, so a repeated keystroke still makes progress.
3714                            _ => cur = cur.saturating_sub(1),
3715                        }
3716                    } else {
3717                        break;
3718                    }
3719                }
3720                cur
3721            }
3722            MoveOperation::EndOfSentence => {
3723                let mut cur = pos;
3724                for _ in 0..n.max(1) {
3725                    let end = match self.find_sentence_boundaries(cur) {
3726                        Some((_, end)) => end,
3727                        None => break,
3728                    };
3729                    if end > cur {
3730                        cur = end;
3731                    } else {
3732                        match self.find_sentence_boundaries(cur + 1) {
3733                            Some((_, next)) if next > cur => cur = next,
3734                            _ => break,
3735                        }
3736                    }
3737                }
3738                cur
3739            }
3740            MoveOperation::NextSentence => {
3741                let mut cur = pos;
3742                for _ in 0..n.max(1) {
3743                    // Step past this sentence's end, then take the start of whatever follows —
3744                    // which skips the whitespace between them.
3745                    let end = match self.find_sentence_boundaries(cur) {
3746                        Some((_, end)) => end,
3747                        None => break,
3748                    };
3749                    match self.find_sentence_boundaries(end + 1) {
3750                        Some((start, _)) if start > cur => cur = start,
3751                        _ => {
3752                            if end > cur {
3753                                cur = end;
3754                            } else {
3755                                break;
3756                            }
3757                        }
3758                    }
3759                }
3760                cur
3761            }
3762            MoveOperation::Up | MoveOperation::Down => {
3763                // Up/Down are visual operations that depend on line wrapping.
3764                // Without layout info, treat as PreviousBlock/NextBlock.
3765                if matches!(op, MoveOperation::Up) {
3766                    self.resolve_move(MoveOperation::PreviousBlock, 1)
3767                } else {
3768                    self.resolve_move(MoveOperation::NextBlock, 1)
3769                }
3770            }
3771        }
3772    }
3773
3774    /// Snap the cursor's current position to the nearest grapheme
3775    /// cluster boundary, moving forward if currently mid-cluster.
3776    /// No-op when already at a boundary.
3777    ///
3778    /// Applied automatically by `cursor_at` and `set_position` so a
3779    /// caller passing an arbitrary scalar index never lands inside a
3780    /// cluster — without this, a round-trip such as
3781    /// `NextCharacter → PreviousCharacter` would stop at the cluster
3782    /// start rather than the start position, because the pre-advance
3783    /// state wasn't a boundary to begin with.
3784    pub(crate) fn snap_position_to_grapheme_boundary(&self) {
3785        let pos = {
3786            let data = self.data.lock();
3787            data.position
3788        };
3789        let snapped = self.forward_grapheme_boundary_at_or_after(pos);
3790        if snapped != pos {
3791            let mut data = self.data.lock();
3792            data.position = snapped;
3793            if data.anchor == pos {
3794                data.anchor = snapped;
3795            }
3796            data.whole_text_selected = false;
3797        }
3798    }
3799
3800    /// Return `pos` if it sits at a grapheme cluster boundary within
3801    /// its block; otherwise return the end position of the containing
3802    /// cluster (snap forward). Block separators are always treated as
3803    /// boundaries.
3804    ///
3805    /// Leaves out-of-range positions (`pos > max_cursor_position_of`)
3806    /// unchanged — the snap must never silently upgrade an out-of-
3807    /// range cursor to a valid one, because edit ops rely on the
3808    /// out-of-range check to stay no-ops.
3809    fn forward_grapheme_boundary_at_or_after(&self, pos: usize) -> usize {
3810        let inner = self.doc.lock();
3811        let end = max_cursor_position_of(&inner).unwrap_or(pos);
3812        if pos >= end {
3813            return pos;
3814        }
3815        let block_dto = frontend::document_inspection::GetBlockAtPositionDto {
3816            position: to_i64(pos),
3817        };
3818        let Ok(block_info) =
3819            document_inspection_commands::get_block_at_position(&inner.ctx, &block_dto)
3820        else {
3821            return pos;
3822        };
3823        let block_start = to_usize(block_info.block_start);
3824        let block_length = to_usize(block_info.block_length);
3825        let offset_in_block = pos.saturating_sub(block_start);
3826        // Block boundaries (start / end) are always cluster boundaries.
3827        if offset_in_block == 0 || offset_in_block >= block_length {
3828            return pos;
3829        }
3830        let text_dto = frontend::document_inspection::GetTextAtPositionDto {
3831            position: to_i64(block_start),
3832            length: to_i64(block_length),
3833        };
3834        let Ok(r) = document_inspection_commands::get_text_at_position(&inner.ctx, &text_dto)
3835        else {
3836            return pos;
3837        };
3838        let text = r.text;
3839        drop(inner);
3840        // Walk grapheme clusters, accumulating char counts. The first
3841        // boundary >= offset_in_block is the snap target.
3842        let mut acc = 0usize;
3843        for g in text.graphemes(true) {
3844            if acc >= offset_in_block {
3845                return block_start + acc;
3846            }
3847            acc += g.chars().count();
3848        }
3849        block_start + acc
3850    }
3851
3852    /// Return the cursor position after advancing one extended grapheme
3853    /// cluster from `pos`. A grapheme cluster is what a user perceives
3854    /// as a single character — decomposed accents (`e` + `U+0301`),
3855    /// skin-tone emoji, ZWJ sequences, and regional-indicator flags
3856    /// are all single clusters even though they contain multiple
3857    /// Unicode scalars.
3858    ///
3859    /// Block separators (the single scalar between blocks in the
3860    /// cursor-position space) are treated as their own unit: advancing
3861    /// from the end of a block goes to the start of the next block
3862    /// (one scalar forward) without touching the grapheme path.
3863    /// Returns `pos` unchanged when already at the document end.
3864    fn next_grapheme_boundary(&self, pos: usize) -> usize {
3865        let inner = self.doc.lock();
3866        let end = max_cursor_position_of(&inner).unwrap_or(pos);
3867        if pos >= end {
3868            return pos;
3869        }
3870        let block_dto = frontend::document_inspection::GetBlockAtPositionDto {
3871            position: to_i64(pos),
3872        };
3873        let block_info =
3874            match document_inspection_commands::get_block_at_position(&inner.ctx, &block_dto) {
3875                Ok(info) => info,
3876                Err(_) => return pos + 1,
3877            };
3878        let block_start = to_usize(block_info.block_start);
3879        let block_length = to_usize(block_info.block_length);
3880        let offset_in_block = pos.saturating_sub(block_start);
3881        if offset_in_block >= block_length {
3882            // At block end — advance across the separator into the
3883            // next block.
3884            return (pos + 1).min(end);
3885        }
3886        let text_dto = frontend::document_inspection::GetTextAtPositionDto {
3887            position: to_i64(pos),
3888            length: to_i64(block_length - offset_in_block),
3889        };
3890        let text = match document_inspection_commands::get_text_at_position(&inner.ctx, &text_dto) {
3891            Ok(r) => r.text,
3892            Err(_) => return pos + 1,
3893        };
3894        drop(inner);
3895        match text.graphemes(true).next() {
3896            Some(g) if !g.is_empty() => (pos + g.chars().count()).min(end),
3897            _ => (pos + 1).min(end),
3898        }
3899    }
3900
3901    /// Return the cursor position before the extended grapheme cluster
3902    /// that ends at `pos`. Counterpart to [`Self::next_grapheme_boundary`].
3903    /// Crosses block separators one scalar at a time.
3904    fn prev_grapheme_boundary(&self, pos: usize) -> usize {
3905        if pos == 0 {
3906            return 0;
3907        }
3908        let inner = self.doc.lock();
3909        let block_dto = frontend::document_inspection::GetBlockAtPositionDto {
3910            position: to_i64(pos.saturating_sub(1)),
3911        };
3912        let block_info =
3913            match document_inspection_commands::get_block_at_position(&inner.ctx, &block_dto) {
3914                Ok(info) => info,
3915                Err(_) => return pos - 1,
3916            };
3917        let block_start = to_usize(block_info.block_start);
3918        let block_length = to_usize(block_info.block_length);
3919        let block_end = block_start + block_length;
3920        // If `pos` sits past the block text (on a separator), step back
3921        // one scalar rather than running grapheme analysis across a
3922        // boundary.
3923        if pos > block_end {
3924            return pos - 1;
3925        }
3926        if block_length == 0 || pos <= block_start {
3927            return pos.saturating_sub(1);
3928        }
3929        let scan_len = pos - block_start;
3930        let text_dto = frontend::document_inspection::GetTextAtPositionDto {
3931            position: to_i64(block_start),
3932            length: to_i64(scan_len),
3933        };
3934        let text = match document_inspection_commands::get_text_at_position(&inner.ctx, &text_dto) {
3935            Ok(r) => r.text,
3936            Err(_) => return pos - 1,
3937        };
3938        drop(inner);
3939        match text.graphemes(true).next_back() {
3940            Some(g) if !g.is_empty() => pos - g.chars().count(),
3941            _ => pos - 1,
3942        }
3943    }
3944
3945    /// Find the word boundaries around `pos`. Returns (start, end).
3946    /// Uses Unicode word segmentation for correct handling of non-ASCII text.
3947    ///
3948    /// Single-pass: tracks the last word seen to avoid a second iteration
3949    /// when the cursor is at the end of the last word (ISSUE-18).
3950    fn find_word_boundaries(&self, pos: usize) -> (usize, usize) {
3951        let inner = self.doc.lock();
3952        // Get block info so we can fetch the full block text
3953        let block_dto = frontend::document_inspection::GetBlockAtPositionDto {
3954            position: to_i64(pos),
3955        };
3956        let block_info =
3957            match document_inspection_commands::get_block_at_position(&inner.ctx, &block_dto) {
3958                Ok(info) => info,
3959                Err(_) => return (pos, pos),
3960            };
3961
3962        let block_start = to_usize(block_info.block_start);
3963        let block_length = to_usize(block_info.block_length);
3964        if block_length == 0 {
3965            return (pos, pos);
3966        }
3967
3968        let dto = frontend::document_inspection::GetTextAtPositionDto {
3969            position: to_i64(block_start),
3970            length: to_i64(block_length),
3971        };
3972        let text = match document_inspection_commands::get_text_at_position(&inner.ctx, &dto) {
3973            Ok(r) => r.text,
3974            Err(_) => return (pos, pos),
3975        };
3976
3977        // cursor_offset is the char offset within the block text
3978        let cursor_offset = pos.saturating_sub(block_start);
3979
3980        // Single pass: track the last word seen for end-of-last-word check
3981        let mut last_char_start = 0;
3982        let mut last_char_end = 0;
3983
3984        for (word_byte_start, word) in text.unicode_word_indices() {
3985            // Convert byte offset to char offset
3986            let word_char_start = text[..word_byte_start].chars().count();
3987            let word_char_len = word.chars().count();
3988            let word_char_end = word_char_start + word_char_len;
3989
3990            last_char_start = word_char_start;
3991            last_char_end = word_char_end;
3992
3993            if cursor_offset >= word_char_start && cursor_offset < word_char_end {
3994                return (block_start + word_char_start, block_start + word_char_end);
3995            }
3996        }
3997
3998        // Check if cursor is exactly at the end of the last word
3999        if cursor_offset == last_char_end && last_char_start < last_char_end {
4000            return (block_start + last_char_start, block_start + last_char_end);
4001        }
4002
4003        (pos, pos)
4004    }
4005
4006    /// The sentence boundaries around `pos`, as absolute char offsets, in this cursor's
4007    /// [`content_locale`](Self::content_locale). `None` when the block holds no sentence.
4008    ///
4009    /// Block-scoped like [`find_word_boundaries`](Self::find_word_boundaries) — the whole point
4010    /// of a paragraph break is that it ends a sentence.
4011    fn find_sentence_boundaries(&self, pos: usize) -> Option<(usize, usize)> {
4012        let locale = self.data.lock().content_locale.clone();
4013
4014        let inner = self.doc.lock();
4015        let block_dto = frontend::document_inspection::GetBlockAtPositionDto {
4016            position: to_i64(pos),
4017        };
4018        let block_info =
4019            document_inspection_commands::get_block_at_position(&inner.ctx, &block_dto).ok()?;
4020        let block_start = to_usize(block_info.block_start);
4021        let block_length = to_usize(block_info.block_length);
4022        if block_length == 0 {
4023            return None;
4024        }
4025        let dto = frontend::document_inspection::GetTextAtPositionDto {
4026            position: to_i64(block_start),
4027            length: to_i64(block_length),
4028        };
4029        let text = document_inspection_commands::get_text_at_position(&inner.ctx, &dto)
4030            .ok()?
4031            .text;
4032        drop(inner);
4033
4034        let offset = pos.saturating_sub(block_start);
4035        let (start, end) =
4036            frontend::common::parser_tools::sentence_bounds(&text, offset, locale.as_deref())?;
4037        Some((block_start + start, block_start + end))
4038    }
4039}
4040
4041// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
4042// Frame-awareness helpers used by the public Cursor methods above.
4043// Each takes the locked TextDocumentInner so callers can reuse one
4044// store snapshot.
4045// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
4046
4047#[derive(Clone, Copy, PartialEq, Eq)]
4048enum BlockEdge {
4049    First,
4050    Middle,
4051    Last,
4052    OnlyOne,
4053}
4054
4055/// Build a `FrameRef` for the innermost non-root frame containing
4056/// `block_id`. Returns `None` if the block sits directly in the root
4057/// frame (i.e. the only enclosing frame is the root).
4058fn cursor_frame_ref(inner: &TextDocumentInner, block_id: u64) -> Option<FrameRef> {
4059    let parent = crate::text_block::find_parent_frame(inner, block_id)?;
4060    let store = inner.ctx.db_context.get_store();
4061    let frames = store.frames.read();
4062    let frame = frames.get(&parent)?.clone();
4063    frame.parent_frame?;
4064    let is_blockquote = frame.fmt_is_blockquote.unwrap_or(false);
4065
4066    let mut depth = 0;
4067    let mut current = Some(parent);
4068    while let Some(id) = current {
4069        let Some(f) = frames.get(&id) else {
4070            break;
4071        };
4072        if f.parent_frame.is_none() {
4073            break;
4074        }
4075        depth += 1;
4076        current = f.parent_frame;
4077    }
4078
4079    Some(FrameRef {
4080        frame_id: frame.id as usize,
4081        parent_frame_id: frame.parent_frame.map(|id| id as usize),
4082        is_blockquote,
4083        depth,
4084    })
4085}
4086
4087/// Walk up the parent_frame chain from the block's immediate parent and
4088/// return the first blockquote frame found (innermost). `None` if no
4089/// enclosing frame is a blockquote.
4090fn innermost_blockquote_frame_id(inner: &TextDocumentInner, block_id: u64) -> Option<usize> {
4091    let mut current = crate::text_block::find_parent_frame(inner, block_id);
4092    let store = inner.ctx.db_context.get_store();
4093    let frames = store.frames.read();
4094    while let Some(id) = current {
4095        let f = frames.get(&id)?;
4096        if f.fmt_is_blockquote == Some(true) {
4097            return Some(f.id as usize);
4098        }
4099        current = f.parent_frame;
4100    }
4101    None
4102}
4103
4104/// Count how many blockquote frames sit on the parent_frame chain above
4105/// `block_id`. 0 if no enclosing frame is a blockquote.
4106fn blockquote_depth_for_block(inner: &TextDocumentInner, block_id: u64) -> usize {
4107    let mut current = crate::text_block::find_parent_frame(inner, block_id);
4108    let store = inner.ctx.db_context.get_store();
4109    let frames = store.frames.read();
4110    let mut count = 0;
4111    while let Some(id) = current {
4112        let Some(f) = frames.get(&id) else {
4113            break;
4114        };
4115        if f.fmt_is_blockquote == Some(true) {
4116            count += 1;
4117        }
4118        current = f.parent_frame;
4119    }
4120    count
4121}
4122
4123/// Resolve the cursor's block, find its immediate parent frame, and
4124/// determine the block's edge position within that frame's `child_order`
4125/// (counting only positive entries — sub-frames are skipped because they
4126/// are structurally different elements). Returns `None` if the cursor's
4127/// block has no entry in any frame's `child_order`.
4128fn block_position_in_current_frame(cursor: &TextCursor) -> Option<BlockEdge> {
4129    let pos = cursor.position();
4130    let inner = cursor.doc.lock();
4131    // The caret's block: at the end of the last paragraph of a quotation, that paragraph.
4132    let block_info = TextCursor::caret_block(&inner, pos)?;
4133    let block_id = block_info.block_id as common::types::EntityId;
4134    let parent_id = crate::text_block::find_parent_frame(&inner, block_info.block_id as u64)?;
4135    let store = inner.ctx.db_context.get_store();
4136    let frames = store.frames.read();
4137    let frame = frames.get(&parent_id)?;
4138    let block_positions: Vec<usize> = frame
4139        .child_order
4140        .iter()
4141        .enumerate()
4142        .filter_map(|(i, &e)| {
4143            if e > 0 {
4144                Some((i, e as common::types::EntityId))
4145            } else {
4146                None
4147            }
4148        })
4149        .filter(|(_, id)| *id == block_id)
4150        .map(|(i, _)| i)
4151        .collect();
4152    let block_idx = *block_positions.first()?;
4153    let positive_entries: Vec<usize> = frame
4154        .child_order
4155        .iter()
4156        .enumerate()
4157        .filter_map(|(i, &e)| if e > 0 { Some(i) } else { None })
4158        .collect();
4159    let first_pos = *positive_entries.first()?;
4160    let last_pos = *positive_entries.last()?;
4161    let is_first = block_idx == first_pos;
4162    let is_last = block_idx == last_pos;
4163    let edge = match (is_first, is_last, positive_entries.len()) {
4164        (_, _, 1) => BlockEdge::OnlyOne,
4165        (true, _, _) => BlockEdge::First,
4166        (_, true, _) => BlockEdge::Last,
4167        _ => BlockEdge::Middle,
4168    };
4169    Some(edge)
4170}