escriba-mode 0.1.32

Modal state machine for escriba — Normal/Insert/Visual/VisualLine/Command + pending-operator + pending-count state.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
//! `escriba-mode` — modal state machine, typed as a sum so illegal mode
//! field combinations are *unrepresentable*.
//!
//! Phase 1: vim-ish Normal/Insert/Visual/VisualLine/Command. The earlier
//! design was a product type — `{ mode, pending_count, pending_operator,
//! minibuffer }` — where nonsense like `mode: Insert` carrying a
//! `pending_operator: Some(Delete)` was *constructible* and only kept sane
//! by a runtime guard inside `enter()`. Per the org-level ★★
//! UNREPRESENTABILITY rule, the fix is structural: model the per-mode state
//! as a SUM so each mode carries ONLY the data that is valid in that mode.
//!
//! - `Normal` carries the pending count (`5dd`) + pending operator (the `d`
//!   in `dw`) — these exist NOWHERE else.
//! - `Insert` / `VisualLine` carry nothing.
//! - `Visual` carries nothing in phase 1 (a future `anchor: Position` lands
//!   here, in the one variant where a visual anchor is meaningful).
//! - `Command` carries ONLY the accumulating minibuffer line.
//!
//! There is no way to construct a `Command` without dropping the pending
//! operator, or an `Insert` that still holds a count — the type system
//! refuses it. The only way to change mode is the typed transition methods
//! (`enter_*` / `enter` / `escape`), so the per-mode invariant is enforced
//! by construction at every transition, not re-checked by a guard.
//!
//! Typestate destination: a future revision can promote this to a
//! phantom-typestate `Modal<P>` where illegal *transitions* (not just
//! illegal field combos) are `E0599` compile errors. That is a larger
//! ripple across the keymap-dispatch and runtime borrow sites; this sum
//! type is the pragmatic first tier — illegal field combinations are
//! already truly-unrepresentable, and the transition surface is sealed
//! behind methods so the typestate promotion is a later, localized change.

extern crate self as escriba_mode;

use escriba_core::{Mode, Operator};
use escriba_memori::{CaretMove, Chars, Offset, Ruler};
use serde::{Deserialize, Serialize};

/// Pending operator-pending state — only meaningful in [`ModalState::Normal`].
///
/// Holds the count prefix being accumulated (`5` in `5dd`) and the pending
/// operator (`d` in `dw`). Both live HERE and only here: no insert-mode or
/// command-mode value can carry them, because the only place the type
/// system admits them is the `Normal` variant.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
pub struct PendingOp {
    /// Accumulating count prefix (`None` ⇒ no count typed yet, effective 1).
    pub count: Option<u32>,
    /// Pending operator awaiting a motion (the `d` in `dw`).
    pub operator: Option<Operator>,
}

/// The modal state machine — a SUM over the five editor modes, each
/// carrying ONLY the data valid in that mode.
///
/// `#[serde(tag = "mode")]` keeps the wire shape readable (`{"mode":
/// "Normal", "pending": {…}}`) and is the parse boundary: a deserialized
/// value can only be one of the legal shapes.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(tag = "mode")]
pub enum ModalState {
    Normal {
        pending: PendingOp,
    },
    Insert,
    Visual,
    VisualLine,
    Command {
        #[serde(flatten)]
        line: ExLine,
    },
}

impl Default for ModalState {
    fn default() -> Self {
        Self::Normal {
            pending: PendingOp::default(),
        }
    }
}

/// The `:` line — its text and the caret editing it, as ONE value.
///
/// They are one value because they have an invariant *between* them —
/// `caret <= text.chars().count()` — and a struct with private fields is the
/// only place an invariant like that can be maintained once rather than at
/// every mutation site.
///
/// That is not a hypothetical. The first version of the ex-line caret kept
/// the two as sibling fields of the enum variant, and `clear_minibuffer`
/// emptied the text while leaving the caret where it was. No test could see
/// it, because a caret past the end is silently clamped by `Ruler` instead of
/// panicking — the only report was `warning: unused variable: caret`, which
/// is the compiler saying "you destructured the invariant's other half and
/// did nothing with it".
///
/// # Wire shape
///
/// `#[serde(flatten)]`ed into `ModalState::Command`, and `text` is renamed to
/// `minibuffer`, so the published schema is unchanged by this refactor:
/// `{"mode": "Command", "minibuffer": "wq", "caret": 2}`. `escriba-api`
/// publishes it, so the encapsulation is internal only.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(from = "ExLineWire")]
pub struct ExLine {
    #[serde(rename = "minibuffer")]
    text: String,
    /// Where the next typed character goes, in CHARS from the start.
    ///
    /// Chars, never bytes — the ex-line is text a human edits, and a byte
    /// caret lands mid-codepoint the first time someone types `:e héllo`.
    /// Same reasoning, and same invariant, as the search prompt's caret.
    #[serde(default)]
    caret: usize,
}

/// The deserialization shadow of [`ExLine`].
///
/// Private fields stop *code* from breaking the invariant; they do nothing
/// about a JSON document that simply asserts `caret: 99` on an empty line.
/// Routing `Deserialize` through this shadow clamps at the parse boundary, so
/// an `ExLine` that exists is an `ExLine` that holds — regardless of where it
/// came from.
#[derive(Deserialize, schemars::JsonSchema)]
struct ExLineWire {
    #[serde(default)]
    minibuffer: String,
    #[serde(default)]
    caret: usize,
}

impl From<ExLineWire> for ExLine {
    fn from(w: ExLineWire) -> Self {
        let caret = w.caret.min(w.minibuffer.chars().count());
        Self {
            text: w.minibuffer,
            caret,
        }
    }
}

impl ExLine {
    /// The text typed so far, without the leading `:`.
    #[must_use]
    pub fn text(&self) -> &str {
        &self.text
    }

    /// The caret, in chars from the start.
    #[must_use]
    pub const fn caret(&self) -> usize {
        self.caret
    }

    /// Length in chars — the caret's upper bound.
    #[must_use]
    pub fn len_chars(&self) -> usize {
        self.text.chars().count()
    }

    /// The caret as a BYTE index, for string surgery.
    ///
    /// The one place the ex-line turns chars into bytes, and it delegates to
    /// `Ruler` rather than a local `char_indices().nth()` — which is what it
    /// was for exactly one commit. That local version was the FOURTH
    /// hand-rolled copy of this conversion in the workspace, written inside
    /// the crate that had just taken a dependency on the vocabulary built to
    /// hold it.
    fn byte_of_caret(&self) -> usize {
        Ruler::new(&self.text)
            .to_bytes(Offset::<Chars>::new(self.caret))
            .raw()
    }

    /// Insert a char AT the caret and step past it.
    pub fn insert(&mut self, ch: char) {
        let at = self.byte_of_caret();
        self.text.insert(at, ch);
        self.caret += 1;
    }

    /// Append a raw fragment and park the caret at the end.
    ///
    /// Appends rather than inserting on purpose: its caller is the command
    /// registry's `__quit__` sentinel handshake, which is writing a fragment
    /// the user did not type.
    pub fn push_str(&mut self, s: &str) {
        self.text.push_str(s);
        self.caret = self.len_chars();
    }

    /// Move the caret.
    pub fn move_caret(&mut self, to: CaretMove) {
        self.caret = to.resolve(self.caret, self.len_chars());
    }

    /// Delete the char AT the caret (`<Del>`). No-op at the end of the line.
    pub fn delete(&mut self) {
        let at = self.byte_of_caret();
        if at < self.text.len() {
            self.text.remove(at);
        }
    }

    /// Delete the char BEFORE the caret (`<BS>`), returning it.
    ///
    /// Deleting before the caret and deleting the tail are the same operation
    /// only while the caret sits at the end — exactly the assumption that made
    /// the search prompt's shadow diverge from the typed prompt.
    pub fn backspace(&mut self) -> Option<char> {
        if self.caret == 0 {
            return None;
        }
        let at = self.byte_of_caret();
        let prev = self.text[..at]
            .char_indices()
            .next_back()
            .map_or(0, |(i, _)| i);
        let ch = self.text.remove(prev);
        self.caret -= 1;
        Some(ch)
    }

    /// Empty the line AND return the caret home.
    ///
    /// Both halves, because they are one value. The version of this that
    /// cleared only the text is what motivated the type.
    pub fn clear(&mut self) {
        self.text.clear();
        self.caret = 0;
    }
}

impl ModalState {
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// The [`Mode`] discriminant of the current state — the projection the
    /// renderers + keymap dispatch read.
    #[must_use]
    pub const fn mode(&self) -> Mode {
        match self {
            Self::Normal { .. } => Mode::Normal,
            Self::Insert => Mode::Insert,
            Self::Visual => Mode::Visual,
            Self::VisualLine => Mode::VisualLine,
            Self::Command { .. } => Mode::Command,
        }
    }

    // ── Typed transitions — the ONLY way to change mode ──────────────────
    //
    // Each transition drops the data that is invalid in the destination
    // mode by *construction*: entering `Insert` builds the `Insert` variant
    // which has no field to hold a pending operator, so the operator is
    // gone — not "cleared by a guard", but structurally absent.

    /// Enter [`Mode::Normal`] with no pending count/operator.
    pub fn enter_normal(&mut self) {
        *self = Self::Normal {
            pending: PendingOp::default(),
        };
    }

    /// Enter [`Mode::Insert`]. Any pending count/operator/minibuffer is
    /// dropped by construction.
    pub fn enter_insert(&mut self) {
        *self = Self::Insert;
    }

    /// Enter [`Mode::Visual`].
    pub fn enter_visual(&mut self) {
        *self = Self::Visual;
    }

    /// Enter [`Mode::VisualLine`].
    pub fn enter_visual_line(&mut self) {
        *self = Self::VisualLine;
    }

    /// Enter [`Mode::Command`] with an empty minibuffer.
    pub fn enter_command(&mut self) {
        *self = Self::Command {
            line: ExLine::default(),
        };
    }

    /// Leave any mode back to a clean [`Mode::Normal`] — the `<Esc>`
    /// transition.
    pub fn escape(&mut self) {
        self.enter_normal();
    }

    /// Dispatch to the matching typed transition for a target [`Mode`].
    ///
    /// Kept for callers that hold a runtime `Mode` value (e.g. the keymap's
    /// `Action::ChangeMode(Mode)`); it is sugar over the `enter_*` methods
    /// and preserves the invariant the same way.
    pub fn enter(&mut self, mode: Mode) {
        match mode {
            Mode::Normal => self.enter_normal(),
            Mode::Insert => self.enter_insert(),
            Mode::Visual => self.enter_visual(),
            Mode::VisualLine => self.enter_visual_line(),
            Mode::Command => self.enter_command(),
        }
    }

    // ── Pending-op surface — no-ops outside Normal ───────────────────────
    //
    // These mutate the `Normal` variant's pending state. Called in any
    // other mode they are silent no-ops: there is no field to mutate, so
    // the count/operator concept simply does not exist there — which is the
    // whole point of the sum type.

    /// Set the pending operator. No-op unless in [`Mode::Normal`].
    pub fn set_operator(&mut self, op: Operator) {
        if let Self::Normal { pending } = self {
            pending.operator = Some(op);
        }
    }

    /// Append a digit to the pending count. No-op unless in [`Mode::Normal`].
    pub fn append_count(&mut self, digit: u32) {
        if let Self::Normal { pending } = self {
            let n = pending.count.unwrap_or(0);
            pending.count = Some(n.saturating_mul(10).saturating_add(digit));
        }
    }

    /// The current pending count (`None` ⇒ none accumulated). Always `None`
    /// outside [`Mode::Normal`].
    #[must_use]
    pub const fn pending_count(&self) -> Option<u32> {
        match self {
            Self::Normal { pending } => pending.count,
            _ => None,
        }
    }

    /// The current pending operator. Always `None` outside [`Mode::Normal`].
    #[must_use]
    pub const fn pending_operator(&self) -> Option<Operator> {
        match self {
            Self::Normal { pending } => pending.operator,
            _ => None,
        }
    }

    /// Take the pending count, leaving it cleared; defaults to 1 (and at
    /// least 1). No-op-returning-1 outside [`Mode::Normal`].
    #[must_use]
    pub fn consume_count(&mut self) -> u32 {
        match self {
            Self::Normal { pending } => pending.count.take().unwrap_or(1).max(1),
            _ => 1,
        }
    }

    /// Clear any pending count without consuming its value.
    pub fn clear_count(&mut self) {
        if let Self::Normal { pending } = self {
            pending.count = None;
        }
    }

    /// Take the pending operator, leaving it cleared.
    #[must_use]
    pub fn consume_operator(&mut self) -> Option<Operator> {
        match self {
            Self::Normal { pending } => pending.operator.take(),
            _ => None,
        }
    }

    // ── Command minibuffer surface — no-ops outside Command ──────────────

    /// Read the command-mode minibuffer (empty string outside
    /// [`Mode::Command`]).
    #[must_use]
    pub fn minibuffer(&self) -> &str {
        match self {
            Self::Command { line } => line.text(),
            _ => "",
        }
    }

    /// Push a char onto the minibuffer. No-op unless in [`Mode::Command`].
    pub fn push_minibuffer(&mut self, ch: char) {
        if let Self::Command { line } = self {
            line.insert(ch);
        }
    }

    /// Move the ex-line caret. No-op outside [`Mode::Command`].
    pub fn move_minibuffer_caret(&mut self, to: CaretMove) {
        if let Self::Command { line } = self {
            line.move_caret(to);
        }
    }

    /// Delete the character AT the caret. No-op at the end of the line.
    pub fn delete_minibuffer_at_caret(&mut self) {
        if let Self::Command { line } = self {
            line.delete();
        }
    }

    /// The ex-line caret, in chars. `0` outside [`Mode::Command`].
    #[must_use]
    pub fn minibuffer_caret(&self) -> usize {
        match self {
            Self::Command { line } => line.caret(),
            _ => 0,
        }
    }

    /// Pop a char off the minibuffer. `None` unless in [`Mode::Command`].
    pub fn pop_minibuffer(&mut self) -> Option<char> {
        match self {
            Self::Command { line } => line.backspace(),
            _ => None,
        }
    }

    /// Append a raw fragment to the minibuffer (used by the command
    /// registry's `__quit__` sentinel handshake). No-op outside
    /// [`Mode::Command`].
    pub fn push_minibuffer_str(&mut self, s: &str) {
        if let Self::Command { line } = self {
            line.push_str(s);
        }
    }

    /// Clear the minibuffer in place. No-op outside [`Mode::Command`].
    pub fn clear_minibuffer(&mut self) {
        if let Self::Command { line } = self {
            line.clear();
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn default_is_clean_normal() {
        let s = ModalState::new();
        assert_eq!(s.mode(), Mode::Normal);
        assert_eq!(s.pending_count(), None);
        assert_eq!(s.pending_operator(), None);
    }

    // ── Legal transitions work ───────────────────────────────────────────

    #[test]
    fn enter_transitions_set_mode() {
        let mut s = ModalState::new();
        s.enter_insert();
        assert_eq!(s.mode(), Mode::Insert);
        s.enter_visual();
        assert_eq!(s.mode(), Mode::Visual);
        s.enter_visual_line();
        assert_eq!(s.mode(), Mode::VisualLine);
        s.enter_command();
        assert_eq!(s.mode(), Mode::Command);
        s.escape();
        assert_eq!(s.mode(), Mode::Normal);
    }

    #[test]
    fn enter_by_mode_value_dispatches() {
        for m in [
            Mode::Normal,
            Mode::Insert,
            Mode::Visual,
            Mode::VisualLine,
            Mode::Command,
        ] {
            let mut s = ModalState::new();
            s.enter(m);
            assert_eq!(s.mode(), m);
        }
    }

    // ── Illegal field combinations are UNREPRESENTABLE ───────────────────

    #[test]
    fn leaving_normal_structurally_drops_pending() {
        // Set a count + operator in Normal, then enter Insert. The pending
        // data is GONE — not because a guard cleared it, but because the
        // `Insert` variant has no field that could hold it. There is no
        // expressible `ModalState::Insert { pending_operator: … }`.
        let mut s = ModalState::new();
        s.set_operator(Operator::Delete);
        s.append_count(5);
        assert_eq!(s.pending_operator(), Some(Operator::Delete));
        assert_eq!(s.pending_count(), Some(5));
        s.enter_insert();
        // The compiler refuses `Insert` carrying these; the accessors prove
        // there is no value to read.
        assert_eq!(s.pending_operator(), None);
        assert_eq!(s.pending_count(), None);
    }

    #[test]
    fn pending_ops_are_noops_outside_normal() {
        // Attempting to set an operator / count while NOT in Normal cannot
        // corrupt the state — the variants have nowhere to store them.
        let mut s = ModalState::new();
        s.enter_insert();
        s.set_operator(Operator::Yank);
        s.append_count(9);
        assert_eq!(s.pending_operator(), None);
        assert_eq!(s.pending_count(), None);
        assert_eq!(s.consume_count(), 1, "no count exists outside Normal");
        assert_eq!(s.consume_operator(), None);
    }

    #[test]
    fn minibuffer_is_noop_outside_command() {
        // An Insert-mode value cannot accumulate a command line — there is
        // no minibuffer field on the `Insert` variant.
        let mut s = ModalState::new();
        s.enter_insert();
        s.push_minibuffer('w');
        assert_eq!(s.minibuffer(), "", "insert mode has no minibuffer");
        assert_eq!(s.pop_minibuffer(), None);
    }

    #[test]
    fn entering_command_clears_prior_minibuffer() {
        let mut s = ModalState::new();
        s.enter_command();
        s.push_minibuffer('q');
        assert_eq!(s.minibuffer(), "q");
        // Re-entering command starts a fresh, empty line.
        s.enter_command();
        assert_eq!(s.minibuffer(), "");
    }

    // ── Behavioral round-trips (parity with the old product type) ────────

    #[test]
    fn normal_resets_pending_state() {
        let mut s = ModalState::new();
        s.enter_insert();
        s.set_operator(Operator::Delete);
        s.append_count(5);
        s.enter_normal();
        assert!(s.pending_count().is_none());
        assert!(s.pending_operator().is_none());
    }

    #[test]
    fn count_accumulates() {
        let mut s = ModalState::new();
        s.append_count(5);
        s.append_count(3);
        assert_eq!(s.consume_count(), 53);
        assert_eq!(s.consume_count(), 1); // default 1 when consumed again
    }

    #[test]
    fn operator_round_trip() {
        let mut s = ModalState::new();
        s.set_operator(Operator::Yank);
        assert_eq!(s.consume_operator(), Some(Operator::Yank));
        assert_eq!(s.consume_operator(), None);
    }

    #[test]
    fn minibuffer_append_pop() {
        let mut s = ModalState::new();
        s.enter_command();
        s.push_minibuffer('w');
        assert_eq!(s.minibuffer(), "w");
        assert_eq!(s.pop_minibuffer(), Some('w'));
    }

    #[test]
    fn minibuffer_str_and_clear() {
        let mut s = ModalState::new();
        s.enter_command();
        s.push_minibuffer_str("__quit__");
        assert!(s.minibuffer().contains("__quit__"));
        s.clear_minibuffer();
        assert_eq!(s.minibuffer(), "");
    }

    /// The wire shape round-trips, and a deserialized value is one of the
    /// legal variants only (the parse boundary rejects illegal shapes).
    #[test]
    fn serde_round_trip_per_variant() {
        for s in [
            ModalState::new(),
            {
                let mut n = ModalState::new();
                n.append_count(12);
                n.set_operator(Operator::Delete);
                n
            },
            ModalState::Insert,
            ModalState::Visual,
            ModalState::VisualLine,
            {
                let mut c = ModalState::new();
                c.enter_command();
                c.push_minibuffer('x');
                c
            },
        ] {
            let json = serde_json::to_string(&s).unwrap();
            let back: ModalState = serde_json::from_str(&json).unwrap();
            assert_eq!(s, back);
        }
    }
}

#[cfg(test)]
mod ex_line_tests {
    use super::*;

    #[test]
    fn clearing_the_ex_line_brings_the_caret_home() {
        // The defect that motivated `ExLine`: the text was emptied and the
        // caret left behind, so the next insert built a line whose caret
        // claimed a position the line did not have.
        let mut s = ModalState::new();
        s.enter_command();
        for ch in "foo".chars() {
            s.push_minibuffer(ch);
        }
        assert_eq!(s.minibuffer_caret(), 3);

        s.clear_minibuffer();
        assert_eq!(s.minibuffer(), "");
        assert_eq!(s.minibuffer_caret(), 0, "the caret is half of the value");

        s.push_minibuffer('x');
        assert_eq!(s.minibuffer(), "x");
        assert_eq!(
            s.minibuffer_caret(),
            1,
            "and one char in means caret 1, not 4"
        );
    }

    #[test]
    fn the_caret_never_exceeds_the_line_it_indexes() {
        // The invariant, exercised across every mutation the type offers.
        let mut line = ExLine::default();
        for ch in "héllo".chars() {
            line.insert(ch);
        }
        line.move_caret(CaretMove::Start);
        line.delete();
        line.backspace();
        line.move_caret(CaretMove::End);
        line.push_str("!");
        line.clear();
        line.insert('a');
        assert!(line.caret() <= line.len_chars());
        assert_eq!(line.text(), "a");
    }

    #[test]
    fn the_published_wire_shape_survives_the_extraction() {
        // `escriba-api` publishes `ModalState`'s schema, so folding two fields
        // into a struct must not be visible on the wire. This test is what
        // makes `#[serde(flatten)]` + the `minibuffer` rename load-bearing
        // rather than decorative.
        let mut s = ModalState::new();
        s.enter_command();
        s.push_minibuffer('w');
        s.push_minibuffer('q');
        s.move_minibuffer_caret(CaretMove::Left);

        let v: serde_json::Value = serde_json::to_value(&s).unwrap();
        assert_eq!(v["mode"], "Command");
        assert_eq!(v["minibuffer"], "wq", "NOT nested under a `line` key");
        assert_eq!(v["caret"], 1);
        assert_eq!(serde_json::from_value::<ModalState>(v).unwrap(), s);
    }

    #[test]
    fn a_caret_past_the_end_is_clamped_at_the_parse_boundary() {
        // Private fields stop code from breaking the invariant. They say
        // nothing about a document that simply asserts a bad caret, which is
        // what the deserialization shadow is for.
        let s: ModalState =
            serde_json::from_str(r#"{"mode":"Command","minibuffer":"ab","caret":99}"#).unwrap();
        assert_eq!(s.minibuffer(), "ab");
        assert_eq!(s.minibuffer_caret(), 2);
    }
}