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