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