Skip to main content

mathtex_editor_core/
editor.rs

1//! The editor: document, caret, selection, and menu state, changed only by explicit calls.
2
3use std::fmt;
4use std::sync::atomic::{AtomicU64, Ordering};
5
6use mathtex_ir::Fragment;
7use serde::{Deserialize, Serialize};
8
9use crate::command::{Command, Dir, Edge, ExitDir, HostBoxEntry, HostBoxPolicy, Outcome, Side};
10use crate::doc::{Document, DocumentError};
11use crate::export::{self, Source};
12use crate::geometry::{EmptySlotCaret, Point, RenderOutput, StaleSource};
13use crate::menu::{Menu, MenuView, RowEffect};
14use crate::model::{Cursor, Kind, NodeId, SeqId, SeqRange, Symbol, Tree};
15use crate::path::{CaretPath, PathError, Selection};
16use crate::{matcher, nav, selection};
17
18/// Distinguishes editors so a [`Source`] only renders against the editor that exported it.
19static NEXT_EDITOR: AtomicU64 = AtomicU64::new(1);
20
21/// Everything needed to put an editor back into a previous state, the host keeps its own undo stack.
22#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
23pub struct Snapshot {
24    /// The document.
25    pub document: Document,
26    /// The caret.
27    pub cursor: CaretPath,
28    /// The selection, whose focus wins over `cursor` when present.
29    pub selection: Option<Selection>,
30}
31
32/// Why [`Editor::restore`] refused a snapshot.
33#[derive(Debug, Clone, PartialEq, Eq)]
34pub enum RestoreError {
35    /// The snapshot's document breaks a rule of [`Document::validate`].
36    Document(DocumentError),
37    /// A caret of the snapshot does not resolve in its document.
38    Path(PathError),
39}
40
41impl From<PathError> for RestoreError {
42    fn from(e: PathError) -> Self {
43        RestoreError::Path(e)
44    }
45}
46
47impl fmt::Display for RestoreError {
48    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
49        match self {
50            RestoreError::Document(e) => write!(f, "invalid snapshot document: {e}"),
51            RestoreError::Path(e) => write!(f, "invalid snapshot caret: {e}"),
52        }
53    }
54}
55
56impl std::error::Error for RestoreError {}
57
58/// Facts a keymap needs to interpret the next key.
59#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
60pub struct InputContext {
61    /// The caret is inside `\text{}`, where keys insert literal text.
62    pub in_text_slot: bool,
63    /// The swap or delete menu is open and takes typed characters as its filter.
64    pub menu_open: bool,
65    /// The close character of the innermost delimiters whose end the caret sits at.
66    pub closing_delimiter: Option<char>,
67    /// Counts `exec`, `restore`, and caret setter calls, so a keymap sees whether anything ran between keys.
68    pub serial: u64,
69}
70
71/// A headless structural math editor that never typesets, keeps no history, and has no callbacks.
72pub struct Editor {
73    tree: Tree,
74    cursor: Cursor,
75    /// Selection anchor gap in `cursor.seq`, the caret is the focus.
76    anchor: Option<usize>,
77    menu: Option<Menu>,
78    revision: u64,
79    serial: u64,
80    id: u64,
81    policy: HostBoxPolicy,
82    empty_caret: EmptySlotCaret,
83}
84
85impl Default for Editor {
86    fn default() -> Self {
87        Self::new()
88    }
89}
90
91impl Editor {
92    /// An empty editor.
93    pub fn new() -> Self {
94        Self::with_tree(Tree::new())
95    }
96
97    /// An editor holding `doc`, which must pass [`Document::validate`], see [`Document::repair`].
98    pub fn from_document(doc: &Document) -> Result<Self, DocumentError> {
99        doc.validate()?;
100        Ok(Self::with_tree(Tree::from_doc(doc)))
101    }
102
103    fn with_tree(tree: Tree) -> Self {
104        let cursor = Cursor { seq: tree.root(), index: 0 };
105        Self {
106            tree,
107            cursor,
108            anchor: None,
109            menu: None,
110            revision: 0,
111            serial: 0,
112            id: NEXT_EDITOR.fetch_add(1, Ordering::Relaxed),
113            policy: HostBoxPolicy::Skip,
114            empty_caret: EmptySlotCaret::Start,
115        }
116    }
117
118    /// The whole document.
119    pub fn document(&self) -> Document {
120        self.tree.to_doc()
121    }
122
123    /// Advances on every content change and on [`Editor::restore`], never on motion.
124    pub fn revision(&self) -> u64 {
125        self.revision
126    }
127
128    /// The caret, which is the selection focus while a selection is active.
129    pub fn cursor(&self) -> CaretPath {
130        self.tree.path_of(self.cursor)
131    }
132
133    /// Place the caret, collapsing the selection and closing the menu.
134    pub fn set_cursor(&mut self, at: &CaretPath) -> Result<(), PathError> {
135        let c = self.tree.resolve(at)?;
136        self.cursor = c;
137        self.anchor = None;
138        self.menu = None;
139        self.serial += 1;
140        self.normalize();
141        Ok(())
142    }
143
144    /// The active selection, `None` when the caret is collapsed.
145    pub fn selection(&self) -> Option<Selection> {
146        let s = self.sel()?;
147        let steps = self.tree.seq_steps(s.seq);
148        Some(Selection {
149            anchor: CaretPath { steps: steps.clone(), index: s.anchor },
150            focus: CaretPath { steps, index: s.focus },
151        })
152    }
153
154    /// Select between two carets in the same sequence and close the menu.
155    pub fn set_selection(&mut self, anchor: &CaretPath, focus: &CaretPath) -> Result<(), PathError> {
156        let a = self.tree.resolve(anchor)?;
157        let f = self.tree.resolve(focus)?;
158        if a.seq != f.seq {
159            return Err(PathError::SplitSelection);
160        }
161        self.cursor = f;
162        self.anchor = Some(a.index);
163        self.menu = None;
164        self.serial += 1;
165        self.normalize();
166        Ok(())
167    }
168
169    /// Whether the caret is before everything in the formula.
170    pub fn at_start(&self) -> bool {
171        self.cursor == Cursor { seq: self.tree.root(), index: 0 }
172    }
173
174    /// Whether the caret is after everything in the formula.
175    pub fn at_end(&self) -> bool {
176        let root = self.tree.root();
177        self.cursor == Cursor { seq: root, index: self.tree.len(root) }
178    }
179
180    /// Whether the caret is at the start of its slot.
181    pub fn at_slot_start(&self) -> bool {
182        self.cursor.index == 0
183    }
184
185    /// Whether the caret is at the end of its slot.
186    pub fn at_slot_end(&self) -> bool {
187        self.cursor.index == self.tree.len(self.cursor.seq)
188    }
189
190    /// Whether the caret is inside `\text{}`.
191    pub fn in_text_slot(&self) -> bool {
192        self.tree.is_text_slot(self.cursor.seq)
193    }
194
195    /// The open swap or delete menu.
196    pub fn menu(&self) -> Option<MenuView> {
197        self.menu.as_ref().map(Menu::view)
198    }
199
200    /// The structure each open menu row makes with its slots emptied, for typeset previews, `None` for Delete.
201    pub fn menu_previews(&self) -> Vec<Option<Document>> {
202        self.menu.as_ref().map(|m| m.previews(&self.tree)).unwrap_or_default()
203    }
204
205    /// Rows and columns of the matrix whose cell holds the caret.
206    pub fn matrix_shape(&self) -> Option<(usize, usize)> {
207        self.tree.matrix_shape_at(self.cursor)
208    }
209
210    /// Everything a keymap needs to know about the caret in one call.
211    pub fn input_context(&self) -> InputContext {
212        InputContext {
213            in_text_slot: self.in_text_slot(),
214            menu_open: self.menu.is_some(),
215            closing_delimiter: self.innermost_delim().and_then(|(_, close, body)| self.at_end_of(body).then_some(close)),
216            serial: self.serial,
217        }
218    }
219
220    /// Choose whether horizontal motion steps over host boxes or stops and reports them.
221    pub fn set_host_box_policy(&mut self, policy: HostBoxPolicy) {
222        self.policy = policy;
223    }
224
225    /// Choose where [`Editor::render`] puts the caret inside an empty slot, its left edge unless set.
226    pub fn set_empty_slot_caret(&mut self, place: EmptySlotCaret) {
227        self.empty_caret = place;
228    }
229
230    /// Put the caret at an edge of the formula, clearing selection and menu.
231    pub fn place_at(&mut self, edge: Edge) {
232        let root = self.tree.root();
233        let index = match edge {
234            Edge::Start => 0,
235            Edge::End => self.tree.len(root),
236        };
237        self.cursor = Cursor { seq: root, index };
238        self.anchor = None;
239        self.menu = None;
240        self.serial += 1;
241    }
242
243    /// LaTeX for typesetting, with `\phantom{x}` boxes in empty slots so they can be drawn.
244    pub fn source(&self) -> Source {
245        export::source(&self.tree, self.id, self.revision, true)
246    }
247
248    /// Clean LaTeX with spans, so hosts can map a caret to a byte offset in what users see.
249    pub fn display_source(&self) -> Source {
250        export::source(&self.tree, self.id, self.revision, false)
251    }
252
253    fn check(&self, source: &Source) -> Result<(), StaleSource> {
254        if source.revision == self.revision && source.spans.owner == self.id {
255            Ok(())
256        } else {
257            Err(StaleSource { source: source.revision, editor: self.revision })
258        }
259    }
260
261    /// Geometry for the caret, selection, placeholders, menu, and host boxes over `fragment`.
262    pub fn render(&self, source: &Source, fragment: &Fragment) -> Result<RenderOutput, StaleSource> {
263        self.check(source)?;
264        let menu = self.menu.as_ref().map(|m| m.anchor);
265        Ok(matcher::render(&self.tree, self.cursor, self.sel(), &source.spans, fragment, menu, self.empty_caret))
266    }
267
268    /// The caret nearest `at`, `None` when the fragment has no geometry to hit.
269    pub fn hit_test(&self, source: &Source, fragment: &Fragment, at: Point) -> Result<Option<CaretPath>, StaleSource> {
270        self.check(source)?;
271        let hit = matcher::hit_test(&self.tree, &source.spans, fragment, at);
272        Ok(hit.map(|c| self.tree.path_of(nav::normalize(&self.tree, c))))
273    }
274
275    /// The current state for a host undo stack.
276    pub fn snapshot(&self) -> Snapshot {
277        Snapshot { document: self.document(), cursor: self.cursor(), selection: self.selection() }
278    }
279
280    /// Return to a snapshot, closing the menu and advancing the revision, unchanged on error.
281    pub fn restore(&mut self, s: &Snapshot) -> Result<(), RestoreError> {
282        s.document.validate().map_err(RestoreError::Document)?;
283        let tree = Tree::from_doc(&s.document);
284        let (cursor, anchor) = match &s.selection {
285            Some(sel) => {
286                let a = tree.resolve(&sel.anchor)?;
287                let f = tree.resolve(&sel.focus)?;
288                if a.seq != f.seq {
289                    return Err(PathError::SplitSelection.into());
290                }
291                (f, Some(a.index))
292            }
293            None => (tree.resolve(&s.cursor)?, None),
294        };
295        self.tree = tree;
296        self.cursor = cursor;
297        self.anchor = anchor;
298        self.menu = None;
299        self.revision += 1;
300        self.serial += 1;
301        self.normalize();
302        Ok(())
303    }
304
305    /// The selected nodes as a standalone document for the clipboard.
306    pub fn selection_document(&self) -> Option<Document> {
307        let s = self.sel()?;
308        let items = self.tree.items(s.seq);
309        let hi = s.hi().min(items.len());
310        Some(Document::new(items[s.lo()..hi].iter().filter_map(|&n| self.tree.node_to_doc(n)).collect()))
311    }
312
313    /// The selection as clean LaTeX for external clipboards.
314    pub fn selection_tex(&self) -> Option<String> {
315        self.sel().map(|s| export::range_tex(&self.tree, s))
316    }
317
318    /// Run one command and report what it did.
319    pub fn exec(&mut self, cmd: Command) -> Outcome {
320        let edits = self.tree.edits;
321        let before = self.position();
322        let mut out = Outcome::default();
323        self.serial += 1;
324        self.run(cmd, &mut out);
325        out.changed = self.tree.edits != edits;
326        if out.changed {
327            self.revision += 1;
328        }
329        out.moved = self.position() != before;
330        out.revision = self.revision;
331        out
332    }
333
334    fn position(&self) -> (CaretPath, Option<usize>) {
335        (self.cursor(), self.sel().map(|s| s.anchor))
336    }
337
338    fn sel(&self) -> Option<SeqRange> {
339        let a = self.anchor.filter(|&a| a != self.cursor.index)?;
340        Some(SeqRange { seq: self.cursor.seq, anchor: a, focus: self.cursor.index })
341    }
342
343    fn set(&mut self, c: Cursor) {
344        self.cursor = c;
345        self.anchor = None;
346    }
347
348    /// Apply an edit result, a refused edit leaves caret and selection alone.
349    fn edit(&mut self, result: Option<Cursor>) {
350        if let Some(c) = result {
351            self.set(c);
352        }
353    }
354
355    fn run(&mut self, cmd: Command, out: &mut Outcome) {
356        if self.menu.is_some() {
357            if self.run_menu(&cmd) {
358                self.normalize();
359                return;
360            }
361            // Any other command closes the menu and then runs normally.
362            self.menu = None;
363        }
364        self.dispatch(cmd, out);
365        self.normalize();
366    }
367
368    fn dispatch(&mut self, cmd: Command, out: &mut Outcome) {
369        let at = self.cursor;
370        let sel = self.sel();
371        match cmd {
372            Command::Move(dir @ (Dir::Left | Dir::Right)) => {
373                let right = dir == Dir::Right;
374                if self.policy == HostBoxPolicy::Enter {
375                    if let Some(token) = self.host_box_neighbor(right) {
376                        let side = if right { Side::Before } else { Side::After };
377                        out.entered_host_box = Some(HostBoxEntry { token, side });
378                        return;
379                    }
380                }
381                let next = if right { nav::move_right(&self.tree, at) } else { nav::move_left(&self.tree, at) };
382                match next {
383                    Some(c) => self.set(c),
384                    None => self.boundary(if right { ExitDir::Right } else { ExitDir::Left }, out),
385                }
386            }
387            Command::Move(dir) => {
388                let up = dir == Dir::Up;
389                match nav::vertical(&self.tree, at, up) {
390                    Some(c) => self.set(c),
391                    None => self.boundary(if up { ExitDir::Up } else { ExitDir::Down }, out),
392                }
393            }
394            Command::MoveLineStart => self.set(Cursor { seq: at.seq, index: 0 }),
395            Command::MoveLineEnd => self.set(Cursor { seq: at.seq, index: self.tree.len(at.seq) }),
396            Command::Tab => match self.next_fill_target(true) {
397                Some(c) => self.set(c),
398                None => out.exit = Some(ExitDir::Right),
399            },
400            Command::ShiftTab => match self.next_fill_target(false) {
401                Some(c) => self.set(c),
402                None => out.exit = Some(ExitDir::Left),
403            },
404            Command::MoveTo(path) => {
405                if let Ok(c) = self.tree.resolve(&path) {
406                    self.set(c);
407                }
408            }
409            Command::ExtendTo(path) => {
410                if let Ok(target) = self.tree.resolve(&path) {
411                    let anchor = Cursor { seq: at.seq, index: self.anchor.unwrap_or(at.index) };
412                    self.select(selection::extend_to(&self.tree, anchor, target));
413                }
414            }
415            Command::Extend(dir @ (Dir::Left | Dir::Right)) => {
416                let s = sel.unwrap_or(SeqRange { seq: at.seq, anchor: at.index, focus: at.index });
417                self.select(selection::extend(&self.tree, s, dir == Dir::Right));
418            }
419            Command::Extend(_) => {}
420            Command::SelectAll => self.select(selection::select_all(&self.tree)),
421            Command::Collapse | Command::Confirm => self.anchor = None,
422            Command::MenuSelect(_) => {}
423            Command::InsertAtom(sym) => {
424                let r = self.tree.insert_atom(at, sel, sym);
425                self.edit(r);
426            }
427            Command::InsertHostBox(token) => {
428                let r = self.tree.insert_host_box(at, sel, token);
429                self.edit(r);
430            }
431            Command::InsertText(text) => self.insert_text(&text),
432            Command::InsertFraction(style) => {
433                let r = self.tree.insert_fraction(at, style, sel);
434                self.edit(r);
435            }
436            Command::InsertScript(slot) => {
437                // `_` and `^` right after a big operator move into its limits.
438                if let (None, Some(c)) = (sel, self.tree.bigop_limit_target(at, slot)) {
439                    self.set(c);
440                } else {
441                    let r = self.tree.attach_script(at, slot, sel);
442                    self.edit(r);
443                }
444            }
445            Command::InsertBigOp(op) => {
446                let r = self.tree.insert_big_op(at, sel, op);
447                self.edit(r);
448            }
449            Command::InsertSqrt => {
450                let r = self.tree.insert_sqrt(at, sel);
451                self.edit(r);
452            }
453            Command::InsertDelimiters { open, close } => {
454                let r = self.tree.insert_delimiters(at, open, close, sel);
455                self.edit(r);
456            }
457            Command::InsertAccent(mark) => {
458                let r = self.tree.insert_accent(at, mark, sel);
459                self.edit(r);
460            }
461            Command::InsertUnderOver(spec) => {
462                let r = self.tree.insert_under_over(at, spec, sel);
463                self.edit(r);
464            }
465            Command::InsertStyled(variant) => {
466                let r = self.tree.insert_styled(at, variant, sel);
467                self.edit(r);
468            }
469            Command::InsertMatrix { env, rows, cols } => {
470                let r = self.tree.insert_matrix(at, sel, env, rows, cols);
471                self.edit(r);
472            }
473            Command::InsertDocument(doc) => {
474                if doc.validate().is_err() {
475                    return;
476                }
477                let r = self.tree.insert_doc(at, sel, &doc);
478                self.edit(r);
479            }
480            Command::DeleteBackward | Command::DeleteForward => {
481                let back = cmd == Command::DeleteBackward;
482                let neighbor = if back {
483                    nav::adjacent_structure_backward(&self.tree, at)
484                } else {
485                    nav::adjacent_structure_forward(&self.tree, at)
486                };
487                if let Some(s) = sel {
488                    let c = self.tree.delete_range(s);
489                    self.set(c);
490                } else if let Some(node) = neighbor {
491                    self.select_or_open_menu(node);
492                } else if at.seq == self.tree.root() && self.tree.is_empty(at.seq) {
493                    out.close = true;
494                } else {
495                    let c = if back { self.tree.delete_backward(at) } else { self.tree.delete_forward(at) };
496                    self.set(c);
497                }
498            }
499            Command::MatrixInsertRow(side) => {
500                let r = self.tree.matrix_insert_row(at, side);
501                self.edit(r);
502            }
503            Command::MatrixDeleteRow => {
504                let r = self.tree.matrix_delete_row(at);
505                self.edit(r);
506            }
507            Command::MatrixInsertCol(side) => {
508                let r = self.tree.matrix_insert_col(at, side);
509                self.edit(r);
510            }
511            Command::MatrixDeleteCol => {
512                let r = self.tree.matrix_delete_col(at);
513                self.edit(r);
514            }
515            Command::ReplaceTyped { typed, with } => {
516                if sel.is_none() && self.typed_matches(&typed) {
517                    let n = typed.chars().count();
518                    let c = self.tree.delete_range(SeqRange { seq: at.seq, anchor: at.index - n, focus: at.index });
519                    self.set(c);
520                    self.normalize();
521                    for cmd in with {
522                        self.run(cmd, out);
523                    }
524                }
525            }
526            Command::CloseDelimiter(close) => {
527                if sel.is_none() {
528                    if let Some(after) = self.closing_target(close) {
529                        self.set(after);
530                        return;
531                    }
532                }
533                if let Some(sym) = Symbol::from_char(close) {
534                    let r = self.tree.insert_atom(at, sel, sym);
535                    self.edit(r);
536                }
537            }
538        }
539    }
540
541    /// Consume commands the open menu understands, `false` lets the command close it and run.
542    fn run_menu(&mut self, cmd: &Command) -> bool {
543        let Some(menu) = self.menu.as_mut() else {
544            return false;
545        };
546        match cmd {
547            Command::InsertAtom(sym) if sym.latex.chars().count() == 1 => {
548                menu.query.push_str(&sym.latex);
549                menu.selected = 0;
550            }
551            Command::InsertText(text) => {
552                menu.query.push_str(text);
553                menu.selected = 0;
554            }
555            // With an empty filter both deletes remove the structure, otherwise they edit the filter.
556            Command::DeleteBackward | Command::DeleteForward => {
557                if menu.query.pop().is_none() {
558                    self.commit_menu_row(0);
559                } else {
560                    menu.selected = 0;
561                }
562            }
563            Command::Move(Dir::Up) => menu.selected = menu.selected.saturating_sub(1),
564            Command::Move(Dir::Down) => {
565                let max = menu.visible().len().saturating_sub(1);
566                menu.selected = (menu.selected + 1).min(max);
567            }
568            Command::Confirm => {
569                let selected = menu.selected;
570                self.commit_menu_row(selected);
571            }
572            Command::MenuSelect(i) => self.commit_menu_row(*i),
573            Command::Collapse => self.menu = None,
574            _ => return false,
575        }
576        true
577    }
578
579    /// Commit a visible menu row by deleting or swapping the anchored structure.
580    fn commit_menu_row(&mut self, visible_idx: usize) {
581        let Some(menu) = self.menu.take() else {
582            return;
583        };
584        match menu.visible().get(visible_idx) {
585            Some(RowEffect::Delete) => {
586                if let Some((seq, idx)) = self.tree.index_in_parent(menu.anchor) {
587                    let c = self.tree.delete_range(SeqRange { seq, anchor: idx, focus: idx + 1 });
588                    self.set(c);
589                }
590            }
591            Some(RowEffect::Swap(kind)) => self.tree.apply_swap(menu.anchor, kind),
592            None => {}
593        }
594    }
595
596    /// Open the swap or delete menu for swappable structures, else select the node.
597    fn select_or_open_menu(&mut self, node: NodeId) {
598        match self.tree.swap_variants(node) {
599            Some(variants) => self.menu = Some(Menu::for_node(node, variants)),
600            None => {
601                if let Some((seq, idx)) = self.tree.index_in_parent(node) {
602                    self.select(SeqRange { seq, anchor: idx, focus: idx + 1 });
603                }
604            }
605        }
606    }
607
608    fn select(&mut self, s: SeqRange) {
609        self.cursor = Cursor { seq: s.seq, index: s.focus };
610        self.anchor = Some(s.anchor);
611    }
612
613    fn insert_text(&mut self, text: &str) {
614        let text_slot = self.tree.is_text_slot(self.cursor.seq);
615        let mut sel = self.sel();
616        let mut at = self.cursor;
617        let mut any = false;
618        for ch in text.chars() {
619            if ch == ' ' && !text_slot {
620                continue;
621            }
622            let Some(sym) = Symbol::from_char(ch) else { continue };
623            if let Some(c) = self.tree.insert_atom(at, sel.take(), sym) {
624                at = c;
625                any = true;
626            }
627        }
628        if any {
629            self.set(at);
630        }
631    }
632
633    /// Collapse an active selection at a boundary, or report the exit for a plain caret.
634    fn boundary(&mut self, dir: ExitDir, out: &mut Outcome) {
635        if self.sel().is_some() {
636            self.anchor = None;
637        } else {
638            out.exit = Some(dir);
639        }
640    }
641
642    /// The token of the host box the caret would cross next.
643    fn host_box_neighbor(&self, right: bool) -> Option<u32> {
644        let items = self.tree.items(self.cursor.seq);
645        let node = if right { items.get(self.cursor.index) } else { items.get(self.cursor.index.checked_sub(1)?) };
646        match self.tree.kind(*node?) {
647            Some(Kind::HostBox { token }) => Some(*token),
648            _ => None,
649        }
650    }
651
652    /// Whether the atoms directly left of the caret spell `typed`.
653    fn typed_matches(&self, typed: &str) -> bool {
654        let items = self.tree.items(self.cursor.seq);
655        let n = typed.chars().count();
656        let Some(start) = self.cursor.index.checked_sub(n) else {
657            return false;
658        };
659        typed.chars().zip(&items[start..self.cursor.index]).all(|(ch, &node)| {
660            matches!((self.tree.kind(node), Symbol::from_char(ch)), (Some(Kind::Atom(s)), Some(e)) if s.latex == e.latex)
661        })
662    }
663
664    /// The innermost delimiters around the caret as `(node, close, body)`.
665    fn innermost_delim(&self) -> Option<(NodeId, char, SeqId)> {
666        let mut seq = self.cursor.seq;
667        loop {
668            let node = self.tree.seq_parent(seq)?;
669            if let Some(Kind::Delim { close, body, .. }) = self.tree.kind(node) {
670                return Some((node, *close, *body));
671            }
672            seq = self.tree.before_parent(seq)?.seq;
673        }
674    }
675
676    /// Whether moving right from the caret would only climb out until the end of `body`.
677    fn at_end_of(&self, body: SeqId) -> bool {
678        let mut cur = self.cursor;
679        loop {
680            if cur.index != self.tree.len(cur.seq) {
681                return false;
682            }
683            if cur.seq == body {
684                return true;
685            }
686            let Some(node) = self.tree.seq_parent(cur.seq) else {
687                return false;
688            };
689            if self.tree.child_seqs(node).last() != Some(&cur.seq) {
690                return false;
691            }
692            let Some((seq, idx)) = self.tree.index_in_parent(node) else {
693                return false;
694            };
695            cur = Cursor { seq, index: idx + 1 };
696        }
697    }
698
699    /// The gap after the innermost enclosing delimiters closed by `close` whose end the caret is at.
700    fn closing_target(&self, close: char) -> Option<Cursor> {
701        let mut seq = self.cursor.seq;
702        loop {
703            let node = self.tree.seq_parent(seq)?;
704            if let Some(Kind::Delim { close: c, body, .. }) = self.tree.kind(node) {
705                if *c == close && self.at_end_of(*body) {
706                    let (pseq, idx) = self.tree.index_in_parent(node)?;
707                    return Some(Cursor { seq: pseq, index: idx + 1 });
708                }
709            }
710            seq = self.tree.before_parent(seq)?.seq;
711        }
712    }
713
714    fn next_fill_target(&self, forward: bool) -> Option<Cursor> {
715        let at = self.cursor;
716        let tree = &self.tree;
717        let empty_start = |s: SeqId| tree.is_empty(s).then_some(Cursor { seq: s, index: 0 });
718        if forward {
719            // Big operator limits fill in reading order, lower then upper.
720            if let Some(Kind::BigOp { lower, upper, .. }) = tree.seq_parent(at.seq).and_then(|p| tree.kind(p)) {
721                if at.seq == *lower {
722                    if let Some(c) = empty_start(*upper) {
723                        return Some(c);
724                    }
725                }
726            }
727            let prev = at.index.checked_sub(1).and_then(|i| tree.items(at.seq).get(i));
728            if let Some(Kind::BigOp { lower, upper, .. }) = prev.and_then(|&p| tree.kind(p)) {
729                if let Some(c) = empty_start(*lower).or_else(|| empty_start(*upper)) {
730                    return Some(c);
731                }
732            }
733            // From a radicand, visit an empty degree before continuing.
734            if let Some(Kind::Sqrt { index, radicand }) = tree.seq_parent(at.seq).and_then(|p| tree.kind(p)) {
735                if at.seq == *radicand {
736                    if let Some(c) = empty_start(*index) {
737                        return Some(c);
738                    }
739                }
740            }
741        }
742        nav::next_empty_slot(tree, at, forward).map(|seq| Cursor { seq, index: 0 })
743    }
744
745    /// Restore every caret invariant, run after each command and state setter.
746    fn normalize(&mut self) {
747        let root = self.tree.root();
748        if !self.tree.seqs.contains_key(self.cursor.seq) {
749            self.cursor = Cursor { seq: root, index: self.tree.len(root) };
750            self.anchor = None;
751        }
752        let len = self.tree.len(self.cursor.seq);
753        self.cursor.index = self.cursor.index.min(len);
754        self.anchor = self.anchor.map(|a| a.min(len));
755        loop {
756            match self.anchor {
757                Some(a) if a != self.cursor.index => {
758                    // A focus on an illegal gap grows the selection to cover the whole Script.
759                    if !nav::is_illegal(&self.tree, self.cursor) {
760                        break;
761                    }
762                    let Some(p) = self.tree.before_parent(self.cursor.seq) else { break };
763                    self.anchor = Some(p.index + 1);
764                    self.cursor = p;
765                }
766                _ => {
767                    self.anchor = None;
768                    self.cursor = nav::normalize(&self.tree, self.cursor);
769                    break;
770                }
771            }
772        }
773        if self.menu.as_ref().is_some_and(|m| !self.tree.nodes.contains_key(m.anchor)) {
774            self.menu = None;
775        }
776    }
777
778    #[cfg(test)]
779    pub(crate) fn tree(&self) -> &Tree {
780        &self.tree
781    }
782
783    #[cfg(test)]
784    pub(crate) fn raw_cursor(&self) -> Cursor {
785        self.cursor
786    }
787
788    #[cfg(test)]
789    pub(crate) fn raw_anchor(&self) -> Option<usize> {
790        self.anchor
791    }
792
793    #[cfg(test)]
794    pub(crate) fn menu_anchor(&self) -> Option<NodeId> {
795        self.menu.as_ref().map(|m| m.anchor)
796    }
797}