Skip to main content

text_document/
cursor.rs

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