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    /// Rows and columns of the matrix whose cell holds the caret.
201    pub fn matrix_shape(&self) -> Option<(usize, usize)> {
202        self.tree.matrix_shape_at(self.cursor)
203    }
204
205    /// Everything a keymap needs to know about the caret in one call.
206    pub fn input_context(&self) -> InputContext {
207        InputContext {
208            in_text_slot: self.in_text_slot(),
209            menu_open: self.menu.is_some(),
210            closing_delimiter: self.innermost_delim().and_then(|(_, close, body)| self.at_end_of(body).then_some(close)),
211            serial: self.serial,
212        }
213    }
214
215    /// Choose whether horizontal motion steps over host boxes or stops and reports them.
216    pub fn set_host_box_policy(&mut self, policy: HostBoxPolicy) {
217        self.policy = policy;
218    }
219
220    /// Choose where [`Editor::render`] puts the caret inside an empty slot, its left edge unless set.
221    pub fn set_empty_slot_caret(&mut self, place: EmptySlotCaret) {
222        self.empty_caret = place;
223    }
224
225    /// Put the caret at an edge of the formula, clearing selection and menu.
226    pub fn place_at(&mut self, edge: Edge) {
227        let root = self.tree.root();
228        let index = match edge {
229            Edge::Start => 0,
230            Edge::End => self.tree.len(root),
231        };
232        self.cursor = Cursor { seq: root, index };
233        self.anchor = None;
234        self.menu = None;
235        self.serial += 1;
236    }
237
238    /// LaTeX for typesetting, with `\phantom{x}` boxes in empty slots so they can be drawn.
239    pub fn source(&self) -> Source {
240        export::source(&self.tree, self.id, self.revision, true)
241    }
242
243    /// Clean LaTeX with spans, so hosts can map a caret to a byte offset in what users see.
244    pub fn display_source(&self) -> Source {
245        export::source(&self.tree, self.id, self.revision, false)
246    }
247
248    fn check(&self, source: &Source) -> Result<(), StaleSource> {
249        if source.revision == self.revision && source.spans.owner == self.id {
250            Ok(())
251        } else {
252            Err(StaleSource { source: source.revision, editor: self.revision })
253        }
254    }
255
256    /// Geometry for the caret, selection, placeholders, menu, and host boxes over `fragment`.
257    pub fn render(&self, source: &Source, fragment: &Fragment) -> Result<RenderOutput, StaleSource> {
258        self.check(source)?;
259        let menu = self.menu.as_ref().map(|m| m.anchor);
260        Ok(matcher::render(&self.tree, self.cursor, self.sel(), &source.spans, fragment, menu, self.empty_caret))
261    }
262
263    /// The caret nearest `at`, `None` when the fragment has no geometry to hit.
264    pub fn hit_test(&self, source: &Source, fragment: &Fragment, at: Point) -> Result<Option<CaretPath>, StaleSource> {
265        self.check(source)?;
266        let hit = matcher::hit_test(&self.tree, &source.spans, fragment, at);
267        Ok(hit.map(|c| self.tree.path_of(nav::normalize(&self.tree, c))))
268    }
269
270    /// The current state for a host undo stack.
271    pub fn snapshot(&self) -> Snapshot {
272        Snapshot { document: self.document(), cursor: self.cursor(), selection: self.selection() }
273    }
274
275    /// Return to a snapshot, closing the menu and advancing the revision, unchanged on error.
276    pub fn restore(&mut self, s: &Snapshot) -> Result<(), RestoreError> {
277        s.document.validate().map_err(RestoreError::Document)?;
278        let tree = Tree::from_doc(&s.document);
279        let (cursor, anchor) = match &s.selection {
280            Some(sel) => {
281                let a = tree.resolve(&sel.anchor)?;
282                let f = tree.resolve(&sel.focus)?;
283                if a.seq != f.seq {
284                    return Err(PathError::SplitSelection.into());
285                }
286                (f, Some(a.index))
287            }
288            None => (tree.resolve(&s.cursor)?, None),
289        };
290        self.tree = tree;
291        self.cursor = cursor;
292        self.anchor = anchor;
293        self.menu = None;
294        self.revision += 1;
295        self.serial += 1;
296        self.normalize();
297        Ok(())
298    }
299
300    /// The selected nodes as a standalone document for the clipboard.
301    pub fn selection_document(&self) -> Option<Document> {
302        let s = self.sel()?;
303        let items = self.tree.items(s.seq);
304        let hi = s.hi().min(items.len());
305        Some(Document::new(items[s.lo()..hi].iter().filter_map(|&n| self.tree.node_to_doc(n)).collect()))
306    }
307
308    /// The selection as clean LaTeX for external clipboards.
309    pub fn selection_tex(&self) -> Option<String> {
310        self.sel().map(|s| export::range_tex(&self.tree, s))
311    }
312
313    /// Run one command and report what it did.
314    pub fn exec(&mut self, cmd: Command) -> Outcome {
315        let edits = self.tree.edits;
316        let before = self.position();
317        let mut out = Outcome::default();
318        self.serial += 1;
319        self.run(cmd, &mut out);
320        out.changed = self.tree.edits != edits;
321        if out.changed {
322            self.revision += 1;
323        }
324        out.moved = self.position() != before;
325        out.revision = self.revision;
326        out
327    }
328
329    fn position(&self) -> (CaretPath, Option<usize>) {
330        (self.cursor(), self.sel().map(|s| s.anchor))
331    }
332
333    fn sel(&self) -> Option<SeqRange> {
334        let a = self.anchor.filter(|&a| a != self.cursor.index)?;
335        Some(SeqRange { seq: self.cursor.seq, anchor: a, focus: self.cursor.index })
336    }
337
338    fn set(&mut self, c: Cursor) {
339        self.cursor = c;
340        self.anchor = None;
341    }
342
343    /// Apply an edit result, a refused edit leaves caret and selection alone.
344    fn edit(&mut self, result: Option<Cursor>) {
345        if let Some(c) = result {
346            self.set(c);
347        }
348    }
349
350    fn run(&mut self, cmd: Command, out: &mut Outcome) {
351        if self.menu.is_some() {
352            if self.run_menu(&cmd) {
353                self.normalize();
354                return;
355            }
356            // Any other command closes the menu and then runs normally.
357            self.menu = None;
358        }
359        self.dispatch(cmd, out);
360        self.normalize();
361    }
362
363    fn dispatch(&mut self, cmd: Command, out: &mut Outcome) {
364        let at = self.cursor;
365        let sel = self.sel();
366        match cmd {
367            Command::Move(dir @ (Dir::Left | Dir::Right)) => {
368                let right = dir == Dir::Right;
369                if self.policy == HostBoxPolicy::Enter {
370                    if let Some(token) = self.host_box_neighbor(right) {
371                        let side = if right { Side::Before } else { Side::After };
372                        out.entered_host_box = Some(HostBoxEntry { token, side });
373                        return;
374                    }
375                }
376                let next = if right { nav::move_right(&self.tree, at) } else { nav::move_left(&self.tree, at) };
377                match next {
378                    Some(c) => self.set(c),
379                    None => self.boundary(if right { ExitDir::Right } else { ExitDir::Left }, out),
380                }
381            }
382            Command::Move(dir) => {
383                let up = dir == Dir::Up;
384                match nav::vertical(&self.tree, at, up) {
385                    Some(c) => self.set(c),
386                    None => self.boundary(if up { ExitDir::Up } else { ExitDir::Down }, out),
387                }
388            }
389            Command::MoveLineStart => self.set(Cursor { seq: at.seq, index: 0 }),
390            Command::MoveLineEnd => self.set(Cursor { seq: at.seq, index: self.tree.len(at.seq) }),
391            Command::Tab => match self.next_fill_target(true) {
392                Some(c) => self.set(c),
393                None => out.exit = Some(ExitDir::Right),
394            },
395            Command::ShiftTab => match self.next_fill_target(false) {
396                Some(c) => self.set(c),
397                None => out.exit = Some(ExitDir::Left),
398            },
399            Command::MoveTo(path) => {
400                if let Ok(c) = self.tree.resolve(&path) {
401                    self.set(c);
402                }
403            }
404            Command::ExtendTo(path) => {
405                if let Ok(target) = self.tree.resolve(&path) {
406                    let anchor = Cursor { seq: at.seq, index: self.anchor.unwrap_or(at.index) };
407                    self.select(selection::extend_to(&self.tree, anchor, target));
408                }
409            }
410            Command::Extend(dir @ (Dir::Left | Dir::Right)) => {
411                let s = sel.unwrap_or(SeqRange { seq: at.seq, anchor: at.index, focus: at.index });
412                self.select(selection::extend(&self.tree, s, dir == Dir::Right));
413            }
414            Command::Extend(_) => {}
415            Command::SelectAll => self.select(selection::select_all(&self.tree)),
416            Command::Collapse | Command::Confirm => self.anchor = None,
417            Command::MenuSelect(_) => {}
418            Command::InsertAtom(sym) => {
419                let r = self.tree.insert_atom(at, sel, sym);
420                self.edit(r);
421            }
422            Command::InsertHostBox(token) => {
423                let r = self.tree.insert_host_box(at, sel, token);
424                self.edit(r);
425            }
426            Command::InsertText(text) => self.insert_text(&text),
427            Command::InsertFraction(style) => {
428                let r = self.tree.insert_fraction(at, style, sel);
429                self.edit(r);
430            }
431            Command::InsertScript(slot) => {
432                // `_` and `^` right after a big operator move into its limits.
433                if let (None, Some(c)) = (sel, self.tree.bigop_limit_target(at, slot)) {
434                    self.set(c);
435                } else {
436                    let r = self.tree.attach_script(at, slot, sel);
437                    self.edit(r);
438                }
439            }
440            Command::InsertBigOp(op) => {
441                let r = self.tree.insert_big_op(at, sel, op);
442                self.edit(r);
443            }
444            Command::InsertSqrt => {
445                let r = self.tree.insert_sqrt(at, sel);
446                self.edit(r);
447            }
448            Command::InsertDelimiters { open, close } => {
449                let r = self.tree.insert_delimiters(at, open, close, sel);
450                self.edit(r);
451            }
452            Command::InsertAccent(mark) => {
453                let r = self.tree.insert_accent(at, mark, sel);
454                self.edit(r);
455            }
456            Command::InsertUnderOver(spec) => {
457                let r = self.tree.insert_under_over(at, spec, sel);
458                self.edit(r);
459            }
460            Command::InsertStyled(variant) => {
461                let r = self.tree.insert_styled(at, variant, sel);
462                self.edit(r);
463            }
464            Command::InsertMatrix { env, rows, cols } => {
465                let r = self.tree.insert_matrix(at, sel, env, rows, cols);
466                self.edit(r);
467            }
468            Command::InsertDocument(doc) => {
469                if doc.validate().is_err() {
470                    return;
471                }
472                let r = self.tree.insert_doc(at, sel, &doc);
473                self.edit(r);
474            }
475            Command::DeleteBackward | Command::DeleteForward => {
476                let back = cmd == Command::DeleteBackward;
477                let neighbor = if back {
478                    nav::adjacent_structure_backward(&self.tree, at)
479                } else {
480                    nav::adjacent_structure_forward(&self.tree, at)
481                };
482                if let Some(s) = sel {
483                    let c = self.tree.delete_range(s);
484                    self.set(c);
485                } else if let Some(node) = neighbor {
486                    self.select_or_open_menu(node);
487                } else if at.seq == self.tree.root() && self.tree.is_empty(at.seq) {
488                    out.close = true;
489                } else {
490                    let c = if back { self.tree.delete_backward(at) } else { self.tree.delete_forward(at) };
491                    self.set(c);
492                }
493            }
494            Command::MatrixInsertRow(side) => {
495                let r = self.tree.matrix_insert_row(at, side);
496                self.edit(r);
497            }
498            Command::MatrixDeleteRow => {
499                let r = self.tree.matrix_delete_row(at);
500                self.edit(r);
501            }
502            Command::MatrixInsertCol(side) => {
503                let r = self.tree.matrix_insert_col(at, side);
504                self.edit(r);
505            }
506            Command::MatrixDeleteCol => {
507                let r = self.tree.matrix_delete_col(at);
508                self.edit(r);
509            }
510            Command::ReplaceTyped { typed, with } => {
511                if sel.is_none() && self.typed_matches(&typed) {
512                    let n = typed.chars().count();
513                    let c = self.tree.delete_range(SeqRange { seq: at.seq, anchor: at.index - n, focus: at.index });
514                    self.set(c);
515                    self.normalize();
516                    for cmd in with {
517                        self.run(cmd, out);
518                    }
519                }
520            }
521            Command::CloseDelimiter(close) => {
522                if sel.is_none() {
523                    if let Some(after) = self.closing_target(close) {
524                        self.set(after);
525                        return;
526                    }
527                }
528                if let Some(sym) = Symbol::from_char(close) {
529                    let r = self.tree.insert_atom(at, sel, sym);
530                    self.edit(r);
531                }
532            }
533        }
534    }
535
536    /// Consume commands the open menu understands, `false` lets the command close it and run.
537    fn run_menu(&mut self, cmd: &Command) -> bool {
538        let Some(menu) = self.menu.as_mut() else {
539            return false;
540        };
541        match cmd {
542            Command::InsertAtom(sym) if sym.latex.chars().count() == 1 => {
543                menu.query.push_str(&sym.latex);
544                menu.selected = 0;
545            }
546            Command::InsertText(text) => {
547                menu.query.push_str(text);
548                menu.selected = 0;
549            }
550            // With an empty filter both deletes remove the structure, otherwise they edit the filter.
551            Command::DeleteBackward | Command::DeleteForward => {
552                if menu.query.pop().is_none() {
553                    self.commit_menu_row(0);
554                } else {
555                    menu.selected = 0;
556                }
557            }
558            Command::Move(Dir::Up) => menu.selected = menu.selected.saturating_sub(1),
559            Command::Move(Dir::Down) => {
560                let max = menu.visible().len().saturating_sub(1);
561                menu.selected = (menu.selected + 1).min(max);
562            }
563            Command::Confirm => {
564                let selected = menu.selected;
565                self.commit_menu_row(selected);
566            }
567            Command::MenuSelect(i) => self.commit_menu_row(*i),
568            Command::Collapse => self.menu = None,
569            _ => return false,
570        }
571        true
572    }
573
574    /// Commit a visible menu row by deleting or swapping the anchored structure.
575    fn commit_menu_row(&mut self, visible_idx: usize) {
576        let Some(menu) = self.menu.take() else {
577            return;
578        };
579        match menu.visible().get(visible_idx) {
580            Some(RowEffect::Delete) => {
581                if let Some((seq, idx)) = self.tree.index_in_parent(menu.anchor) {
582                    let c = self.tree.delete_range(SeqRange { seq, anchor: idx, focus: idx + 1 });
583                    self.set(c);
584                }
585            }
586            Some(RowEffect::Swap(kind)) => self.tree.apply_swap(menu.anchor, kind),
587            None => {}
588        }
589    }
590
591    /// Open the swap or delete menu for swappable structures, else select the node.
592    fn select_or_open_menu(&mut self, node: NodeId) {
593        match self.tree.swap_variants(node) {
594            Some(variants) => self.menu = Some(Menu::for_node(node, variants)),
595            None => {
596                if let Some((seq, idx)) = self.tree.index_in_parent(node) {
597                    self.select(SeqRange { seq, anchor: idx, focus: idx + 1 });
598                }
599            }
600        }
601    }
602
603    fn select(&mut self, s: SeqRange) {
604        self.cursor = Cursor { seq: s.seq, index: s.focus };
605        self.anchor = Some(s.anchor);
606    }
607
608    fn insert_text(&mut self, text: &str) {
609        let text_slot = self.tree.is_text_slot(self.cursor.seq);
610        let mut sel = self.sel();
611        let mut at = self.cursor;
612        let mut any = false;
613        for ch in text.chars() {
614            if ch == ' ' && !text_slot {
615                continue;
616            }
617            let Some(sym) = Symbol::from_char(ch) else { continue };
618            if let Some(c) = self.tree.insert_atom(at, sel.take(), sym) {
619                at = c;
620                any = true;
621            }
622        }
623        if any {
624            self.set(at);
625        }
626    }
627
628    /// Collapse an active selection at a boundary, or report the exit for a plain caret.
629    fn boundary(&mut self, dir: ExitDir, out: &mut Outcome) {
630        if self.sel().is_some() {
631            self.anchor = None;
632        } else {
633            out.exit = Some(dir);
634        }
635    }
636
637    /// The token of the host box the caret would cross next.
638    fn host_box_neighbor(&self, right: bool) -> Option<u32> {
639        let items = self.tree.items(self.cursor.seq);
640        let node = if right { items.get(self.cursor.index) } else { items.get(self.cursor.index.checked_sub(1)?) };
641        match self.tree.kind(*node?) {
642            Some(Kind::HostBox { token }) => Some(*token),
643            _ => None,
644        }
645    }
646
647    /// Whether the atoms directly left of the caret spell `typed`.
648    fn typed_matches(&self, typed: &str) -> bool {
649        let items = self.tree.items(self.cursor.seq);
650        let n = typed.chars().count();
651        let Some(start) = self.cursor.index.checked_sub(n) else {
652            return false;
653        };
654        typed.chars().zip(&items[start..self.cursor.index]).all(|(ch, &node)| {
655            matches!((self.tree.kind(node), Symbol::from_char(ch)), (Some(Kind::Atom(s)), Some(e)) if s.latex == e.latex)
656        })
657    }
658
659    /// The innermost delimiters around the caret as `(node, close, body)`.
660    fn innermost_delim(&self) -> Option<(NodeId, char, SeqId)> {
661        let mut seq = self.cursor.seq;
662        loop {
663            let node = self.tree.seq_parent(seq)?;
664            if let Some(Kind::Delim { close, body, .. }) = self.tree.kind(node) {
665                return Some((node, *close, *body));
666            }
667            seq = self.tree.before_parent(seq)?.seq;
668        }
669    }
670
671    /// Whether moving right from the caret would only climb out until the end of `body`.
672    fn at_end_of(&self, body: SeqId) -> bool {
673        let mut cur = self.cursor;
674        loop {
675            if cur.index != self.tree.len(cur.seq) {
676                return false;
677            }
678            if cur.seq == body {
679                return true;
680            }
681            let Some(node) = self.tree.seq_parent(cur.seq) else {
682                return false;
683            };
684            if self.tree.child_seqs(node).last() != Some(&cur.seq) {
685                return false;
686            }
687            let Some((seq, idx)) = self.tree.index_in_parent(node) else {
688                return false;
689            };
690            cur = Cursor { seq, index: idx + 1 };
691        }
692    }
693
694    /// The gap after the innermost enclosing delimiters closed by `close` whose end the caret is at.
695    fn closing_target(&self, close: char) -> Option<Cursor> {
696        let mut seq = self.cursor.seq;
697        loop {
698            let node = self.tree.seq_parent(seq)?;
699            if let Some(Kind::Delim { close: c, body, .. }) = self.tree.kind(node) {
700                if *c == close && self.at_end_of(*body) {
701                    let (pseq, idx) = self.tree.index_in_parent(node)?;
702                    return Some(Cursor { seq: pseq, index: idx + 1 });
703                }
704            }
705            seq = self.tree.before_parent(seq)?.seq;
706        }
707    }
708
709    fn next_fill_target(&self, forward: bool) -> Option<Cursor> {
710        let at = self.cursor;
711        let tree = &self.tree;
712        let empty_start = |s: SeqId| tree.is_empty(s).then_some(Cursor { seq: s, index: 0 });
713        if forward {
714            // Big operator limits fill in reading order, lower then upper.
715            if let Some(Kind::BigOp { lower, upper, .. }) = tree.seq_parent(at.seq).and_then(|p| tree.kind(p)) {
716                if at.seq == *lower {
717                    if let Some(c) = empty_start(*upper) {
718                        return Some(c);
719                    }
720                }
721            }
722            let prev = at.index.checked_sub(1).and_then(|i| tree.items(at.seq).get(i));
723            if let Some(Kind::BigOp { lower, upper, .. }) = prev.and_then(|&p| tree.kind(p)) {
724                if let Some(c) = empty_start(*lower).or_else(|| empty_start(*upper)) {
725                    return Some(c);
726                }
727            }
728            // From a radicand, visit an empty degree before continuing.
729            if let Some(Kind::Sqrt { index, radicand }) = tree.seq_parent(at.seq).and_then(|p| tree.kind(p)) {
730                if at.seq == *radicand {
731                    if let Some(c) = empty_start(*index) {
732                        return Some(c);
733                    }
734                }
735            }
736        }
737        nav::next_empty_slot(tree, at, forward).map(|seq| Cursor { seq, index: 0 })
738    }
739
740    /// Restore every caret invariant, run after each command and state setter.
741    fn normalize(&mut self) {
742        let root = self.tree.root();
743        if !self.tree.seqs.contains_key(self.cursor.seq) {
744            self.cursor = Cursor { seq: root, index: self.tree.len(root) };
745            self.anchor = None;
746        }
747        let len = self.tree.len(self.cursor.seq);
748        self.cursor.index = self.cursor.index.min(len);
749        self.anchor = self.anchor.map(|a| a.min(len));
750        loop {
751            match self.anchor {
752                Some(a) if a != self.cursor.index => {
753                    // A focus on an illegal gap grows the selection to cover the whole Script.
754                    if !nav::is_illegal(&self.tree, self.cursor) {
755                        break;
756                    }
757                    let Some(p) = self.tree.before_parent(self.cursor.seq) else { break };
758                    self.anchor = Some(p.index + 1);
759                    self.cursor = p;
760                }
761                _ => {
762                    self.anchor = None;
763                    self.cursor = nav::normalize(&self.tree, self.cursor);
764                    break;
765                }
766            }
767        }
768        if self.menu.as_ref().is_some_and(|m| !self.tree.nodes.contains_key(m.anchor)) {
769            self.menu = None;
770        }
771    }
772
773    #[cfg(test)]
774    pub(crate) fn tree(&self) -> &Tree {
775        &self.tree
776    }
777
778    #[cfg(test)]
779    pub(crate) fn raw_cursor(&self) -> Cursor {
780        self.cursor
781    }
782
783    #[cfg(test)]
784    pub(crate) fn raw_anchor(&self) -> Option<usize> {
785        self.anchor
786    }
787
788    #[cfg(test)]
789    pub(crate) fn menu_anchor(&self) -> Option<NodeId> {
790        self.menu.as_ref().map(|m| m.anchor)
791    }
792}