Skip to main content

text_document/
cursor.rs

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