alma 0.1.1

A Bevy-native modal text editor with Vim-style navigation.
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
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
//! Typed buffer edit operations.

use crate::{
    ecs::components::buffer::BufferEntity,
    text_stream::{TextByteStream, TextRange, TextRevision, TextStreamError, ValidatedTextRange},
    vim::VimCursor,
};
use std::fmt::{Debug, Formatter};

/// Maximum undo records retained by one buffer by default.
pub const DEFAULT_UNDO_RECORD_LIMIT: usize = 256;

/// Maximum user-text bytes retained by one buffer's undo history by default.
pub const DEFAULT_UNDO_RETAINED_BYTES: usize = 8 * 1024 * 1024;

/// A synchronous mutation against the authoritative text buffer.
#[derive(Clone, Eq, PartialEq)]
pub struct BufferEdit {
    /// Edit operation.
    operation: BufferEditOperation,
}

/// Redacted debug output for buffer edits.
impl std::fmt::Debug for BufferEdit {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("BufferEdit")
            .field("shape", &BufferEditShape::from_edit(self))
            .finish()
    }
}

/// Internal buffer edit operation.
#[derive(Clone, Debug, Eq, PartialEq)]
enum BufferEditOperation {
    /// Replace the entire buffer.
    SetAll(String),
    /// Insert text at a byte index.
    Insert {
        /// Byte index where text should be inserted.
        byte_index: usize,
        /// Text to insert.
        text: String,
    },
    /// Replace a byte range with text.
    Replace {
        /// Byte range to replace.
        range: BufferEditRange,
        /// Replacement text.
        text: String,
    },
    /// Delete a byte range.
    Delete {
        /// Byte range to delete.
        range: BufferEditRange,
    },
}

/// Range carried by a destructive buffer edit.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum BufferEditRange {
    /// Range that still must be validated against the owner stream.
    Unchecked(TextRange),
    /// Range proven valid against a specific stream revision.
    Validated(ValidatedTextRange),
}

impl BufferEditRange {
    /// Returns this range's byte coordinates.
    const fn text_range(self) -> TextRange {
        match self {
            Self::Unchecked(range) => range,
            Self::Validated(range) => TextRange::new(range.start(), range.end()),
        }
    }

    /// Validates this range against `stream`.
    fn validate(self, stream: &TextByteStream) -> Result<ValidatedTextRange, TextStreamError> {
        match self {
            Self::Unchecked(range) => stream.validate_range(range),
            Self::Validated(range) => stream.validate_validated_range(range),
        }
    }
}

/// Redacted buffer edit operation kind for diagnostics.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum BufferEditKind {
    /// Replace the entire buffer.
    SetAll,
    /// Insert text at a byte index.
    Insert,
    /// Replace a byte range with text.
    Replace,
    /// Delete a byte range.
    Delete,
}

/// Redacted buffer edit shape safe to carry across diagnostic boundaries.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct BufferEditShape {
    /// Operation kind.
    kind: BufferEditKind,
    /// Insertion byte index, when the operation has one.
    byte_index: Option<usize>,
    /// Affected byte range, when the operation has one.
    range: Option<TextRange>,
    /// Byte length of replacement text, deliberately excluding the text itself.
    replacement_byte_len: Option<usize>,
}

impl BufferEditShape {
    /// Builds a redacted diagnostic shape from a full edit request.
    #[must_use]
    pub fn from_edit(edit: &BufferEdit) -> Self {
        Self::from(edit)
    }

    /// Returns the operation kind.
    #[must_use]
    pub const fn kind(&self) -> BufferEditKind {
        self.kind
    }

    /// Returns the insertion byte index, when present.
    #[must_use]
    pub const fn byte_index(&self) -> Option<usize> {
        self.byte_index
    }

    /// Returns the affected byte range, when present.
    #[must_use]
    pub const fn range(&self) -> Option<TextRange> {
        self.range
    }

    /// Returns the replacement byte length, when present.
    #[must_use]
    pub const fn replacement_byte_len(&self) -> Option<usize> {
        self.replacement_byte_len
    }
}

impl From<&BufferEdit> for BufferEditShape {
    fn from(edit: &BufferEdit) -> Self {
        match &edit.operation {
            BufferEditOperation::SetAll(text) => Self {
                kind: BufferEditKind::SetAll,
                byte_index: None,
                range: None,
                replacement_byte_len: Some(text.len()),
            },
            BufferEditOperation::Insert { byte_index, text } => Self {
                kind: BufferEditKind::Insert,
                byte_index: Some(*byte_index),
                range: None,
                replacement_byte_len: Some(text.len()),
            },
            BufferEditOperation::Replace { range, text } => Self {
                kind: BufferEditKind::Replace,
                byte_index: None,
                range: Some(range.text_range()),
                replacement_byte_len: Some(text.len()),
            },
            BufferEditOperation::Delete { range } => Self {
                kind: BufferEditKind::Delete,
                byte_index: None,
                range: Some(range.text_range()),
                replacement_byte_len: None,
            },
        }
    }
}

impl BufferEdit {
    /// Creates an edit that replaces the entire buffer.
    #[must_use]
    pub fn set_all(text: impl Into<String>) -> Self {
        Self {
            operation: BufferEditOperation::SetAll(text.into()),
        }
    }

    /// Creates an edit that inserts text at a byte index.
    #[must_use]
    pub fn insert(byte_index: usize, text: impl Into<String>) -> Self {
        Self {
            operation: BufferEditOperation::Insert {
                byte_index,
                text: text.into(),
            },
        }
    }

    /// Creates a replacement edit from a range that still needs owner-boundary validation.
    #[must_use]
    pub fn replace_unchecked(range: impl Into<TextRange>, text: impl Into<String>) -> Self {
        Self {
            operation: BufferEditOperation::Replace {
                range: BufferEditRange::Unchecked(range.into()),
                text: text.into(),
            },
        }
    }

    /// Creates a replacement edit from a range already validated against a stream revision.
    #[must_use]
    pub fn replace_validated(range: ValidatedTextRange, text: impl Into<String>) -> Self {
        Self {
            operation: BufferEditOperation::Replace {
                range: BufferEditRange::Validated(range),
                text: text.into(),
            },
        }
    }

    /// Creates a deletion edit from a range that still needs owner-boundary validation.
    #[must_use]
    pub fn delete_unchecked(range: impl Into<TextRange>) -> Self {
        Self {
            operation: BufferEditOperation::Delete {
                range: BufferEditRange::Unchecked(range.into()),
            },
        }
    }

    /// Creates a deletion edit from a range already validated against a stream revision.
    #[must_use]
    pub const fn delete_validated(range: ValidatedTextRange) -> Self {
        Self {
            operation: BufferEditOperation::Delete {
                range: BufferEditRange::Validated(range),
            },
        }
    }

    /// Applies this edit to `stream`.
    ///
    /// # Errors
    ///
    /// Returns [`BufferEditError`] when the edit violates buffer text invariants.
    pub fn apply(&self, stream: &mut TextByteStream) -> Result<BufferEditReport, BufferEditError> {
        let previous_revision = stream.revision();

        match &self.operation {
            BufferEditOperation::SetAll(text) => stream.replace_all(text.clone()),
            BufferEditOperation::Insert { byte_index, text } => {
                stream.insert_str(*byte_index, text)?;
            }
            BufferEditOperation::Replace { range, text } => {
                let range = (*range).validate(stream)?;
                stream.replace_validated_range(range, text)?;
            }
            BufferEditOperation::Delete { range } => {
                let range = (*range).validate(stream)?;
                stream.delete_validated_range(range)?;
            }
        }

        Ok(BufferEditReport {
            previous_revision,
            current_revision: stream.revision(),
        })
    }

    /// Applies this edit and clamps `cursor` to the edited buffer.
    ///
    /// # Errors
    ///
    /// Returns [`BufferEditError`] when the edit violates buffer text invariants.
    pub fn apply_with_cursor(
        &self,
        stream: &mut TextByteStream,
        cursor: &mut VimCursor,
    ) -> Result<BufferEditReport, BufferEditError> {
        let report = self.apply(stream)?;
        cursor.clamp_to_text(stream.as_str());
        Ok(report)
    }

    /// Returns the number of user-text bytes retained by this edit.
    const fn retained_text_bytes(&self) -> usize {
        match &self.operation {
            BufferEditOperation::SetAll(text)
            | BufferEditOperation::Insert { text, .. }
            | BufferEditOperation::Replace { text, .. } => text.len(),
            BufferEditOperation::Delete { .. } => 0,
        }
    }
}

/// A validated forward edit paired with the inverse needed for undo.
#[derive(Clone, Eq, PartialEq)]
pub struct EditTransaction {
    /// Edit applied to the current buffer state.
    forward: BufferEdit,
    /// Edit that restores the prior buffer state after `forward` succeeds.
    inverse: BufferEdit,
}

impl Debug for EditTransaction {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("EditTransaction")
            .field("shape", &EditTransactionShape::from(self))
            .finish()
    }
}

impl EditTransaction {
    /// Builds a transaction by validating `edit` against the current stream and capturing undo text.
    ///
    /// # Errors
    ///
    /// Returns [`BufferEditError`] when the edit violates UTF-8 stream invariants.
    pub fn from_edit(edit: BufferEdit, stream: &TextByteStream) -> Result<Self, BufferEditError> {
        match &edit.operation {
            BufferEditOperation::SetAll(_) => Ok(Self {
                forward: edit,
                inverse: BufferEdit::set_all(stream.as_str()),
            }),
            BufferEditOperation::Insert { byte_index, text } => {
                let insertion_point = TextRange::new(*byte_index, *byte_index);
                let _validated = stream.validate_range(insertion_point)?;
                let inverse_range = *byte_index..byte_index.saturating_add(text.len());
                Ok(Self {
                    forward: edit,
                    inverse: BufferEdit::delete_unchecked(inverse_range),
                })
            }
            BufferEditOperation::Replace { range, text } => {
                let validated = (*range).validate(stream)?;
                let removed = stream.as_str()[validated.as_range()].to_owned();
                Ok(Self {
                    forward: BufferEdit::replace_validated(validated, text.clone()),
                    inverse: BufferEdit::replace_unchecked(
                        validated.start()..validated.start().saturating_add(text.len()),
                        removed,
                    ),
                })
            }
            BufferEditOperation::Delete { range } => {
                let validated = (*range).validate(stream)?;
                let removed = stream.as_str()[validated.as_range()].to_owned();
                Ok(Self {
                    forward: BufferEdit::delete_validated(validated),
                    inverse: BufferEdit::insert(validated.start(), removed),
                })
            }
        }
    }

    /// Applies the forward edit.
    ///
    /// # Errors
    ///
    /// Returns [`BufferEditError`] if the owner stream no longer matches the transaction proof.
    pub fn apply(&self, stream: &mut TextByteStream) -> Result<BufferEditReport, BufferEditError> {
        self.forward.apply(stream)
    }

    /// Consumes this transaction into an undo record.
    #[must_use]
    pub fn into_undo_record(self) -> UndoRecord {
        UndoRecord {
            undo: self.inverse,
            redo: self.forward,
        }
    }

    /// Returns a redacted transaction shape.
    #[must_use]
    pub fn shape(&self) -> EditTransactionShape {
        EditTransactionShape::from(self)
    }
}

/// Redacted transaction shape safe for diagnostics.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct EditTransactionShape {
    /// Forward edit shape.
    forward: BufferEditShape,
    /// Inverse edit shape.
    inverse: BufferEditShape,
}

impl EditTransactionShape {
    /// Returns the forward edit shape.
    #[must_use]
    pub const fn forward(&self) -> &BufferEditShape {
        &self.forward
    }

    /// Returns the inverse edit shape.
    #[must_use]
    pub const fn inverse(&self) -> &BufferEditShape {
        &self.inverse
    }
}

impl From<&EditTransaction> for EditTransactionShape {
    fn from(transaction: &EditTransaction) -> Self {
        Self {
            forward: BufferEditShape::from_edit(&transaction.forward),
            inverse: BufferEditShape::from_edit(&transaction.inverse),
        }
    }
}

/// One undoable edit with enough text to replay undo and redo.
#[derive(Clone, Eq, PartialEq)]
pub struct UndoRecord {
    /// Edit that restores the previous buffer state.
    undo: BufferEdit,
    /// Edit that reapplies the original mutation.
    redo: BufferEdit,
}

impl Debug for UndoRecord {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("UndoRecord")
            .field("shape", &UndoRecordShape::from(self))
            .finish()
    }
}

impl UndoRecord {
    /// Returns the undo edit.
    #[must_use]
    pub const fn undo_edit(&self) -> &BufferEdit {
        &self.undo
    }

    /// Returns the redo edit.
    #[must_use]
    pub const fn redo_edit(&self) -> &BufferEdit {
        &self.redo
    }

    /// Returns the user-text bytes retained by this record.
    const fn retained_text_bytes(&self) -> usize {
        self.undo.retained_text_bytes() + self.redo.retained_text_bytes()
    }
}

/// Redacted undo-record shape.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct UndoRecordShape {
    /// Undo edit shape.
    undo: BufferEditShape,
    /// Redo edit shape.
    redo: BufferEditShape,
}

impl From<&UndoRecord> for UndoRecordShape {
    fn from(record: &UndoRecord) -> Self {
        Self {
            undo: BufferEditShape::from_edit(&record.undo),
            redo: BufferEditShape::from_edit(&record.redo),
        }
    }
}

/// Bounded undo and redo history for one authoritative buffer.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct UndoStack {
    /// Records available to undo.
    undo: Vec<UndoRecord>,
    /// Records available to redo.
    redo: Vec<UndoRecord>,
    /// Maximum records retained across the undo side.
    max_records: usize,
    /// Maximum user-text bytes retained across undo and redo.
    max_retained_bytes: usize,
    /// Current retained user-text byte count.
    retained_bytes: usize,
}

impl Default for UndoStack {
    fn default() -> Self {
        Self::bounded(DEFAULT_UNDO_RECORD_LIMIT, DEFAULT_UNDO_RETAINED_BYTES)
    }
}

impl UndoStack {
    /// Creates an undo stack with explicit retention bounds.
    #[must_use]
    pub const fn bounded(max_records: usize, max_retained_bytes: usize) -> Self {
        Self {
            undo: Vec::new(),
            redo: Vec::new(),
            max_records,
            max_retained_bytes,
            retained_bytes: 0,
        }
    }

    /// Records a newly applied transaction and clears redo history.
    pub fn record_applied(&mut self, record: UndoRecord) {
        self.clear_redo();
        if self.max_records == 0 || self.max_retained_bytes == 0 {
            self.undo.clear();
            self.retained_bytes = 0;
            return;
        }

        let retained = record.retained_text_bytes();
        if retained > self.max_retained_bytes {
            self.undo.clear();
            self.retained_bytes = 0;
            return;
        }

        self.retained_bytes = self.retained_bytes.saturating_add(retained);
        self.undo.push(record);
        self.enforce_limits();
    }

    /// Pops the next undo record.
    #[must_use]
    pub fn pop_undo(&mut self) -> Option<UndoRecord> {
        self.pop_from_undo()
    }

    /// Pops the next redo record.
    #[must_use]
    pub fn pop_redo(&mut self) -> Option<UndoRecord> {
        self.pop_from_redo()
    }

    /// Restores an undo record after a failed undo replay.
    pub fn restore_undo(&mut self, record: UndoRecord) {
        self.push_undo_preserving_redo(record);
    }

    /// Restores a redo record after a failed redo replay.
    pub fn restore_redo(&mut self, record: UndoRecord) {
        self.push_redo(record);
    }

    /// Moves a successfully undone record to the redo side.
    pub fn record_undone(&mut self, record: UndoRecord) {
        self.push_redo(record);
    }

    /// Moves a successfully redone record back to the undo side.
    pub fn record_redone(&mut self, record: UndoRecord) {
        self.push_undo_preserving_redo(record);
    }

    /// Returns the number of available undo records.
    #[must_use]
    pub const fn undo_len(&self) -> usize {
        self.undo.len()
    }

    /// Returns the number of available redo records.
    #[must_use]
    pub const fn redo_len(&self) -> usize {
        self.redo.len()
    }

    /// Returns retained user-text bytes.
    #[must_use]
    pub const fn retained_bytes(&self) -> usize {
        self.retained_bytes
    }

    /// Clears redo records after a new edit.
    fn clear_redo(&mut self) {
        let cleared = self
            .redo
            .iter()
            .map(UndoRecord::retained_text_bytes)
            .sum::<usize>();
        self.redo.clear();
        self.retained_bytes = self.retained_bytes.saturating_sub(cleared);
    }

    /// Drops oldest undo records until limits hold.
    fn enforce_limits(&mut self) {
        while self.undo.len() > self.max_records || self.retained_bytes > self.max_retained_bytes {
            let Some(record) = (!self.undo.is_empty()).then(|| self.undo.remove(0)) else {
                break;
            };
            self.retained_bytes = self
                .retained_bytes
                .saturating_sub(record.retained_text_bytes());
        }
    }

    /// Pops from the undo side and updates accounting.
    fn pop_from_undo(&mut self) -> Option<UndoRecord> {
        let record = self.undo.pop()?;
        self.retained_bytes = self
            .retained_bytes
            .saturating_sub(record.retained_text_bytes());
        Some(record)
    }

    /// Pops from the redo side and updates accounting.
    fn pop_from_redo(&mut self) -> Option<UndoRecord> {
        let record = self.redo.pop()?;
        self.retained_bytes = self
            .retained_bytes
            .saturating_sub(record.retained_text_bytes());
        Some(record)
    }

    /// Pushes onto undo without clearing redo.
    fn push_undo_preserving_redo(&mut self, record: UndoRecord) {
        self.retained_bytes = self
            .retained_bytes
            .saturating_add(record.retained_text_bytes());
        self.undo.push(record);
        self.enforce_limits();
    }

    /// Pushes onto redo.
    fn push_redo(&mut self, record: UndoRecord) {
        self.retained_bytes = self
            .retained_bytes
            .saturating_add(record.retained_text_bytes());
        self.redo.push(record);
    }
}

/// Errors returned by buffer edit validation at the buffer owner boundary.
#[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)]
#[non_exhaustive]
pub enum BufferEditError {
    /// The edit would violate the underlying UTF-8 byte-stream invariants.
    #[error("buffer edit violates text invariants: {source}")]
    InvalidTextBoundary {
        /// Lower-level text invariant failure retained for diagnostics.
        #[from]
        source: TextStreamError,
    },
    /// The requested target buffer entity does not exist at the owner boundary.
    #[error("buffer edit target {target:?} does not exist")]
    MissingTarget {
        /// Buffer entity that could not be resolved.
        target: BufferEntity,
    },
}

impl BufferEditError {
    /// Returns the underlying text-stream validation error, when this is a text validation failure.
    #[must_use]
    pub const fn text_error(&self) -> Option<&TextStreamError> {
        match self {
            Self::InvalidTextBoundary { source } => Some(source),
            Self::MissingTarget { .. } => None,
        }
    }
}

/// Revision metadata returned after a successful buffer edit.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct BufferEditReport {
    /// Revision before the edit.
    pub previous_revision: TextRevision,
    /// Revision after the edit.
    pub current_revision: TextRevision,
}

impl BufferEditReport {
    /// Returns whether the edit changed the stream revision.
    #[must_use]
    pub fn changed(self) -> bool {
        self.previous_revision != self.current_revision
    }
}

#[cfg(test)]
mod tests {
    use super::{BufferEdit, BufferEditReport, EditTransaction, UndoStack};
    use crate::{text_stream::TextByteStream, vim::VimCursor};
    use proptest::prelude::*;

    #[test]
    fn insert_bumps_revision() {
        let mut stream = TextByteStream::new("alma");

        let report = BufferEdit::insert(4, String::from("!"))
            .apply(&mut stream)
            .expect("insert should succeed");

        assert_eq!(stream.as_str(), "alma!");
        assert_eq!(
            report,
            BufferEditReport {
                previous_revision: 0.into(),
                current_revision: 1.into()
            }
        );
        assert!(report.changed());
    }

    #[test]
    fn rejects_non_utf8_boundary() {
        let mut stream = TextByteStream::new("");

        let error = BufferEdit::delete_unchecked(1..2)
            .apply(&mut stream)
            .expect_err("lambda byte split should fail");

        assert_eq!(
            error.to_string(),
            "buffer edit violates text invariants: byte index 2 is not a UTF-8 character boundary"
        );
        assert_eq!(
            error.text_error(),
            Some(&crate::text_stream::TextStreamError::NotCharBoundary { index: 2 })
        );
        assert_eq!(stream.as_str(), "");
        assert_eq!(stream.revision(), 0);
    }

    #[test]
    fn clamps_cursor_after_delete() {
        let mut stream = TextByteStream::new("abc");
        let mut cursor = VimCursor::new();
        cursor.set_byte_index(stream.as_str(), 2);

        let _report = BufferEdit::delete_unchecked(1..3)
            .apply_with_cursor(&mut stream, &mut cursor)
            .expect("delete should succeed");

        assert_eq!(stream.as_str(), "a");
        assert_eq!(cursor.byte_index(), 0);
    }

    #[test]
    fn undo_debug_output_redacts_retained_text() {
        let secret = "secret retained text";
        let stream = TextByteStream::new(secret);
        let transaction =
            EditTransaction::from_edit(BufferEdit::delete_unchecked(0..secret.len()), &stream)
                .expect("delete transaction should validate");
        let record = transaction.into_undo_record();
        let mut stack = UndoStack::default();
        stack.record_applied(record);
        let debug = format!("{stack:?}");

        assert!(debug.contains("UndoStack"));
        assert!(debug.contains("byte_len"));
        assert!(!debug.contains(secret));
        assert!(!debug.contains("retained text"));
    }

    proptest! {
        #[test]
        fn valid_buffer_edits_match_string_model(
            prefix in any::<String>(),
            removed in any::<String>(),
            suffix in any::<String>(),
            replacement in any::<String>(),
        ) {
            let original = format!("{prefix}{removed}{suffix}");
            let expected = format!("{prefix}{replacement}{suffix}");
            let range = prefix.len()..prefix.len() + removed.len();
            let mut stream = TextByteStream::new(original);

            let report = BufferEdit::replace_unchecked(range, replacement)
            .apply(&mut stream)
            .expect("generated range should be UTF-8 aligned");

            prop_assert_eq!(stream.as_str(), expected.as_str());
            prop_assert_eq!(report.previous_revision, 0);
            prop_assert_eq!(report.current_revision, 1);
        }

        #[test]
        fn invalid_buffer_edit_ranges_leave_stream_unchanged(
            prefix in any::<String>(),
            character in any::<char>().prop_filter(
                "character must use multiple UTF-8 bytes",
                |character| 1 < character.len_utf8(),
            ),
        ) {
            let original = format!("{prefix}{character}");
            let split_index = prefix.len() + 1;
            let mut stream = TextByteStream::new(original.clone());

            let result = BufferEdit::delete_unchecked(split_index..split_index,).apply(&mut stream);

            prop_assert!(result.is_err());
            prop_assert_eq!(stream.as_str(), original.as_str());
            prop_assert_eq!(stream.revision(), 0);
        }
    }
}