r3bl_tui 0.7.2

TUI library to build modern apps inspired by React, Elm, with Flexbox, CSS, editor component, emoji support, and more
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
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
/*
 *   Copyright (c) 2022-2025 R3BL LLC
 *   All rights reserved.
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */
use std::fmt::{Debug, Display, Formatter, Result};

use smallvec::smallvec;

use super::{SelectionList, history::EditorHistory, render_cache::RenderCache, sizing};
use crate::{CachedMemorySize, CaretRaw, CaretScrAdj, ColWidth, DEBUG_TUI_COPY_PASTE,
            DEBUG_TUI_MOD, DEFAULT_SYN_HI_FILE_EXT, GCString, GCStringExt, InlineString,
            MemoizedMemorySize, MemorySize, RowHeight, RowIndex, ScrOfs, SegString,
            Size, TinyInlineString, caret_locate, format_as_kilobytes_with_commas,
            glyphs, height, inline_string, ok, row,
            validate_buffer_mut::{EditorBufferMutNoDrop, EditorBufferMutWithDrop},
            width, with_mut};

/// Stores the data for a single editor buffer. Please do not construct this struct
/// directly and use [`new_empty`](EditorBuffer::new_empty) instead.
///
/// 1. This struct is stored in the app's state.
/// 2. And it is paired w/ [`crate::EditorEngine`] at runtime; which is responsible for
///    rendering it to TUI, and handling user input.
///
/// # Change state during render
///
/// This struct is not mutable during render phase. If you need to make changes during
/// the render phase, then you should use the [`crate::EditorEngine`] struct, which is
/// mutable during render phase.
///
/// # Modifying the buffer
///
/// [`crate::InputEvent`] is converted into an [`crate::EditorEvent`] (by
/// [`crate::engine_public_api::apply_event`], which is then used to modify the
/// [`EditorBuffer`] via:
/// 1. [`crate::EditorEvent::apply_editor_event`]
/// 2. [`crate::EditorEvent::apply_editor_events`]
///
/// In order for the commands to be executed, the functions in
/// [`mod@crate::editor_engine::engine_internal_api`] are used.
///
/// These functions take any one of the following args:
/// 1. [`crate::EditorArgsMut`]
/// 3. [`EditorBuffer`] and [`crate::EditorEngine`]
///
/// # Accessing and mutating the fields (w/ validation)
///
/// All the fields in this struct are private. In order to access them you have to use the
/// accessor associated functions. To mutate them, you have to use the
/// [`get_mut`](EditorBuffer::get_mut) method, which returns a struct of mutable
/// references to the fields. This struct [`crate::EditorBufferMut`] implements the [Drop]
/// trait, which allows for validation
/// [`crate::validate_buffer_mut::perform_validation_checks_after_mutation`] operations to
/// be applied post mutation.
///
/// # Kinds of caret positions
///
/// There are two variants for the caret position value:
/// 1. [`CaretRaw`] - this is the position of the caret (unadjusted for `scr_ofs`) and
///    this represents the position of the caret in the viewport.
/// 2. [`CaretScrAdj`] - this is the position of the caret (adjusted for `scr_ofs`) and
///    represents the position of the caret in the buffer (not the viewport).
///
/// # Fields
///
/// Please don't mutate these fields directly, they are not marked `pub` to guard from
/// unintentional mutation. To mutate or access it, use
/// [`get_mut`](EditorBuffer::get_mut).
///
/// ## `lines`
///
/// A list of lines representing the document being edited.
///
/// ## `caret_raw`
///
/// This is the "display" col index (grapheme-cluster-based) and not "logical" col index
/// (byte-based) position (both are defined in [`crate::graphemes`]).
///
/// > Please review [crate::graphemes::GCString], specifically the
/// > methods in [mod@crate::graphemes::gc_string] for more details on how
/// > the conversion between "display" and "logical" indices is done.
/// >
/// > This results from the fact that `UTF-8` is a variable width text encoding scheme,
/// > that can use between 1 and 4 bytes to represent a single character. So the width a
/// > human perceives, and it's byte size in RAM can be different.
/// >
/// > Videos:
/// >
/// > - [Live coding video on Rust String](https://youtu.be/7I11degAElQ?)
/// > - [UTF-8 encoding video](https://youtu.be/wIVmDPc16wA)
///
/// 1. It represents the current caret position (relative to the
///    [`style_adjusted_origin_pos`](crate::FlexBox::style_adjusted_origin_pos) of the
///    enclosing [`crate::FlexBox`]).
/// 2. It works w/ [`crate::RenderOp::MoveCursorPositionRelTo`] as well.
///
/// > 💡 For the diagrams below, the caret is where `⮬` and `❱` intersects.
///
/// Start of line:
/// ```text
/// R ┌──────────┐
/// 0 ❱abcab     │
///   └⮬─────────┘
///   C0123456789
/// ```
///
/// Middle of line:
/// ```text
/// R ┌──────────┐
/// 0 ❱abcab     │
///   └───⮬──────┘
///   C0123456789
/// ```
///
/// End of line:
/// ```text
/// R ┌──────────┐
/// 0 ❱abcab     │
///   └─────⮬────┘
///   C0123456789
/// ```
///
/// ## `scr_ofs`
///
/// The col and row offset for scrolling if active. This is not marked pub to guard
/// against unintentional mutation. To access it, use [`get_mut`](EditorBuffer::get_mut).
///
/// # Vertical scrolling and viewport
///
/// ```text
///                    ╭0────────────────────╮
///                    0                     │
///                    │        above        │ <- caret_row_adj
///                    │                     │
///                    ├─── scroll_offset ───┤
///              ->    │         ↑           │      ↑
///              │     │                     │      │
///   caret.row_index  │      within vp      │  vp height
///              │     │                     │      │
///              ->    │         ↓           │      ↓
///                    ├─── scroll_offset ───┤
///                    │    + vp height      │
///                    │                     │
///                    │        below        │ <- caret_row_adj
///                    │                     │
///                    ╰─────────────────────╯
/// ```
///
/// # Horizontal scrolling and viewport
///
/// ```text
///           <-   vp width   ->
/// ╭0────────┼────────────────┼─────────>
/// 0         │                │
/// │ left of │<-  within vp ->│ right of
/// │         │                │
/// ╰─────────┼────────────────┼─────────>
///       scroll_offset    scroll_offset
///                        + vp width
/// ```
///
/// ## `file_extension`
///
/// This is used for syntax highlighting. It is a 2-character string, eg: `rs` or `md`
/// that is used to look up the syntax highlighting rules for the language in
/// [`find_syntax_by_extension`[`syntect::parsing::SyntaxSet::find_syntax_by_extension`].
///
/// ## `selection_map`
///
/// The [`SelectionList`] is used to keep track of the selections in the buffer. Each
/// entry in the list represents a row of text in the buffer.
/// - The row index is the key [`crate::RowIndex`].
/// - The value is the [`crate::SelectionRange`].
#[derive(Clone, PartialEq, Default)]
pub struct EditorBuffer {
    pub content: EditorContent,
    pub history: EditorHistory,
    pub render_cache: RenderCache,
    /// Memoized memory size calculation for [`std::fmt::Display`] trait performance.
    pub memory_size_calc_cache: MemoizedMemorySize,
}

#[derive(Clone, PartialEq, Default)]
pub struct EditorContent {
    pub lines: sizing::VecEditorContentLines,
    /// The caret is stored as a "raw" [`EditorContent::caret_raw`].
    /// - This is the col and row index that is relative to the viewport.
    /// - In order to get the "scroll adjusted" caret position, use
    ///   [`EditorBuffer::get_caret_scr_adj`], which incorporates the
    ///   [`EditorContent::scr_ofs`].
    pub caret_raw: CaretRaw,
    pub scr_ofs: ScrOfs,
    pub maybe_file_extension: Option<TinyInlineString>,
    pub maybe_file_path: Option<InlineString>,
    pub sel_list: SelectionList,
}

mod construct {
    use super::{DEBUG_TUI_MOD, EditorBuffer, EditorContent, GCStringExt, glyphs,
                inline_string, smallvec};

    impl EditorBuffer {
        /// Marker method to make it easy to search for where an empty instance is
        /// created.
        #[must_use]
        pub fn new_empty(
            maybe_file_extension: Option<&str>,
            maybe_file_path: Option<&str>,
        ) -> Self {
            let it = Self {
                content: EditorContent {
                    lines: { smallvec!["".grapheme_string()] },
                    maybe_file_extension: maybe_file_extension.map(Into::into),
                    maybe_file_path: maybe_file_path.map(Into::into),
                    ..Default::default()
                },
                ..Default::default()
            };

            DEBUG_TUI_MOD.then(|| {
                // % is Display, ? is Debug.
                tracing::info!(
                    message = %inline_string!("Construct EditorBuffer {ch}", ch = glyphs::CONSTRUCT_GLYPH),
                    file_extension = ?maybe_file_extension,
                    file_path = ?maybe_file_path
                );
            });

            it
        }
    }
}

pub mod versions {
    use super::{DEBUG_TUI_COPY_PASTE, EditorBuffer};

    impl EditorBuffer {
        pub fn add(&mut self) {
            // Invalidate the content cache, since the content just changed.
            self.render_cache.clear();

            // Invalidate memory size cache.
            self.invalidate_memory_size_calc_cache();

            // Normal history insertion.
            let content_copy = self.content.clone();
            self.history.add(content_copy);

            DEBUG_TUI_COPY_PASTE.then(|| {
                // % is Display, ? is Debug.
                tracing::debug!(
                    message = "🍎🍎🍎 add_content_to_undo_stack buffer",
                    buffer = ?self
                );
            });
        }

        pub fn undo(&mut self) {
            // Invalidate the content cache, since the content just changed.
            self.render_cache.clear();

            // Invalidate memory size cache.
            self.invalidate_memory_size_calc_cache();

            if let Some(content) = self.history.undo() {
                self.content = content;
            }

            DEBUG_TUI_COPY_PASTE.then(|| {
                // % is Display, ? is Debug.
                tracing::debug!(
                    message = "🍎🍎🍎 undo buffer",
                    buffer = ?self
                );
            });
        }

        pub fn redo(&mut self) {
            // Invalidate the content cache, since the content just changed.
            self.render_cache.clear();

            // Invalidate memory size cache.
            self.invalidate_memory_size_calc_cache();

            if let Some(content) = self.history.redo() {
                self.content = content;
            }

            DEBUG_TUI_COPY_PASTE.then(|| {
                // % is Display, ? is Debug.
                tracing::debug!(message = "🍎🍎🍎 redo buffer",
                    buffer = ?self
                );
            });
        }
    }
}

/// Relating to line display width at caret row or given row index (scroll adjusted).
pub mod content_display_width {
    use super::{CaretRaw, ColWidth, EditorBuffer, RowIndex, ScrOfs, height, sizing,
                width};

    impl EditorBuffer {
        #[must_use]
        pub fn get_max_row_index(&self) -> RowIndex {
            // Subtract 1 from the height to get the last row index.
            height(self.get_lines().len()).convert_to_row_index()
        }

        /// Get line display with at caret's scroll adjusted row index.
        #[must_use]
        pub fn get_line_display_width_at_caret_scr_adj(&self) -> ColWidth {
            Self::impl_get_line_display_width_at_caret_scr_adj(
                self.get_caret_raw(),
                self.get_scr_ofs(),
                self.get_lines(),
            )
        }

        /// Get line display with at caret's scroll adjusted row index. Use this when you
        /// don't have access to this struct. Eg: in [`crate::EditorBufferMut`].
        #[must_use]
        pub fn impl_get_line_display_width_at_caret_scr_adj(
            caret_raw: CaretRaw,
            scr_ofs: ScrOfs,
            lines: &sizing::VecEditorContentLines,
        ) -> ColWidth {
            let caret_scr_adj = caret_raw + scr_ofs;
            let row_index = caret_scr_adj.row_index;
            let maybe_line_gcs = lines.get(row_index.as_usize());
            if let Some(line_gcs) = maybe_line_gcs {
                line_gcs.display_width
            } else {
                width(0)
            }
        }

        /// Get line display with at given scroll adjusted row index.
        #[must_use]
        pub fn get_line_display_width_at_row_index(
            &self,
            row_index: RowIndex,
        ) -> ColWidth {
            Self::impl_get_line_display_width_at_row_index(row_index, self.get_lines())
        }

        /// Get line display with at given scroll adjusted row index. Use this when you
        /// don't have access to this struct.
        #[must_use]
        pub fn impl_get_line_display_width_at_row_index(
            row_index: RowIndex,
            lines: &sizing::VecEditorContentLines,
        ) -> ColWidth {
            let maybe_line_gcs = lines.get(row_index.as_usize());
            if let Some(line_gcs) = maybe_line_gcs {
                line_gcs.display_width
            } else {
                width(0)
            }
        }
    }
}

/// Relating to content around the caret.
pub mod content_near_caret {
    use super::{EditorBuffer, GCString, SegString, caret_locate, row, width};

    impl EditorBuffer {
        #[must_use]
        pub fn line_at_caret_is_empty(&self) -> bool {
            self.get_line_display_width_at_caret_scr_adj() == width(0)
        }

        #[must_use]
        pub fn line_at_caret_scr_adj(&self) -> Option<&GCString> {
            if self.is_empty() {
                return None;
            }
            let row_index_scr_adj = self.get_caret_scr_adj().row_index;
            let line = self.get_lines().get(row_index_scr_adj.as_usize())?;
            Some(line)
        }

        #[must_use]
        pub fn string_at_end_of_line_at_caret_scr_adj(&self) -> Option<SegString> {
            if self.is_empty() {
                return None;
            }
            let line = self.line_at_caret_scr_adj()?;
            if let caret_locate::CaretColLocationInLine::AtEnd =
                caret_locate::locate_col(self)
            {
                let maybe_last_seg_string = line.get_string_at_end();
                return maybe_last_seg_string;
            }
            None
        }

        #[must_use]
        pub fn string_to_right_of_caret(&self) -> Option<SegString> {
            if self.is_empty() {
                return None;
            }
            let line = self.line_at_caret_scr_adj()?;
            match caret_locate::locate_col(self) {
                // Caret is at end of line, past the last character.
                caret_locate::CaretColLocationInLine::AtEnd => line.get_string_at_end(),
                // Caret is not at end of line.
                _ => line.get_string_at_right_of(self.get_caret_scr_adj().col_index),
            }
        }

        #[must_use]
        pub fn string_to_left_of_caret(&self) -> Option<SegString> {
            if self.is_empty() {
                return None;
            }
            let line = self.line_at_caret_scr_adj()?;
            match caret_locate::locate_col(self) {
                // Caret is at end of line, past the last character.
                caret_locate::CaretColLocationInLine::AtEnd => line.get_string_at_end(),
                // Caret is not at end of line.
                _ => line.get_string_at_left_of(self.get_caret_scr_adj().col_index),
            }
        }

        #[must_use]
        pub fn prev_line_above_caret(&self) -> Option<&GCString> {
            if self.is_empty() {
                return None;
            }
            let row_index_scr_adj = self.get_caret_scr_adj().row_index;
            if row_index_scr_adj == row(0) {
                return None;
            }
            let line = self
                .get_lines()
                .get((row_index_scr_adj - row(1)).as_usize())?;
            Some(line)
        }

        #[must_use]
        pub fn string_at_caret(&self) -> Option<SegString> {
            if self.is_empty() {
                return None;
            }
            let line = self.line_at_caret_scr_adj()?;
            let caret_str_adj_col_index = self.get_caret_scr_adj().col_index;
            let seg_string = line.get_string_at(caret_str_adj_col_index)?;
            Some(seg_string)
        }

        #[must_use]
        pub fn next_line_below_caret_to_string(&self) -> Option<&GCString> {
            if self.is_empty() {
                return None;
            }
            let caret_scr_adj_row_index = self.get_caret_scr_adj().row_index;
            let next_line_row_index = caret_scr_adj_row_index + row(1);
            let line = self.get_lines().get(next_line_row_index.as_usize())?;
            Some(line)
        }
    }
}

pub mod access_and_mutate {
    use super::{CaretRaw, CaretScrAdj, DEFAULT_SYN_HI_FILE_EXT, EditorBuffer,
                EditorBufferMutNoDrop, EditorBufferMutWithDrop, GCString, GCStringExt,
                InlineString, RowHeight, RowIndex, ScrOfs, SelectionList, Size, height,
                sizing, with_mut};

    impl EditorBuffer {
        #[must_use]
        pub fn is_file_extension_default(&self) -> bool {
            match self.content.maybe_file_extension {
                Some(ref ext) => ext == DEFAULT_SYN_HI_FILE_EXT,
                None => false,
            }
        }

        #[must_use]
        pub fn has_file_extension(&self) -> bool {
            self.content.maybe_file_extension.is_some()
        }

        #[must_use]
        pub fn get_maybe_file_extension(&self) -> Option<&str> {
            match self.content.maybe_file_extension {
                Some(ref s) => Some(s.as_str()),
                None => None,
            }
        }

        #[must_use]
        pub fn is_empty(&self) -> bool { self.content.lines.is_empty() }

        #[must_use]
        pub fn line_at_row_index(&self, row_index: RowIndex) -> Option<&GCString> {
            self.content.lines.get(row_index.as_usize())
        }

        #[must_use]
        pub fn len(&self) -> RowHeight { height(self.content.lines.len()) }

        #[must_use]
        pub fn get_lines(&self) -> &sizing::VecEditorContentLines { &self.content.lines }

        #[must_use]
        pub fn get_as_string_with_comma_instead_of_newlines(&self) -> InlineString {
            self.get_as_string_with_separator(", ")
        }

        #[must_use]
        pub fn get_as_string_with_newlines(&self) -> InlineString {
            self.get_as_string_with_separator("\n")
        }

        /// Helper function to format the [`EditorBuffer`] as a delimited string.
        #[must_use]
        pub fn get_as_string_with_separator(&self, separator: &str) -> InlineString {
            with_mut!(
                InlineString::new(),
                as acc,
                run {
                    let lines = &self.content.lines;
                    for (index, line) in lines.iter().enumerate() {
                        // Add separator if it's not the first line.
                        if index > 0 {
                            acc.push_str(separator);
                        }
                        // Append the current line to the accumulator.
                        acc.push_str(&line.string);
                    }
                }
            )
        }

        // XMARK: Clever Rust, use `IntoIterator` to efficiently & flexibly load data.

        /// You can load a file into the editor buffer using this method. Since this is a
        /// text editor and not binary editor, it operates on UTF-8 encoded text files and
        /// not binary files (which just contain `u8`s).
        ///
        /// You can convert a `&[u8]` to a `&str` using [`std::str::from_utf8`].
        /// Initializes the buffer with the given lines, clearing all state including
        /// history. This is meant to be used when loading a new file or
        /// completely replacing buffer content.
        ///
        /// For normal editing operations that preserve history, use [`Self::get_mut()`]
        /// and the mutation API [`mod@crate::content_mut`].
        ///
        /// - A [`Vec<u8>`] can be converted into a `&[u8]` using `&vec[..]` or
        ///   `vec.as_slice()` or `vec.as_bytes()`.
        /// - Then you can convert the `&[u8]` to a `&str` using [`std::str::from_utf8`].
        /// - And then call [`str::lines()`] on the `&str` to get an iterator over the
        ///   lines which can be passed to this method.
        pub fn init_with<I>(&mut self, arg_lines: I)
        where
            I: IntoIterator,
            I::Item: AsRef<str>,
        {
            // Clear existing lines.
            self.content.lines.clear();

            // Populate lines with the new data.
            for line in arg_lines {
                self.content.lines.push(line.as_ref().grapheme_string());
            }

            // Reset caret.
            self.content.caret_raw = CaretRaw::default();

            // Reset scroll_offset.
            self.content.scr_ofs = ScrOfs::default();

            // Empty the content render cache.
            self.render_cache.clear();

            // Invalidate and recalculate memory size cache.
            self.invalidate_memory_size_calc_cache();

            // Reset undo/redo history since this is a complete re-initialization
            self.history.clear();
        }

        #[must_use]
        pub fn get_caret_raw(&self) -> CaretRaw { self.content.caret_raw }

        #[must_use]
        pub fn get_caret_scr_adj(&self) -> CaretScrAdj {
            self.content.caret_raw + self.content.scr_ofs
        }

        #[must_use]
        pub fn get_scr_ofs(&self) -> ScrOfs { self.content.scr_ofs }

        /// Even though this struct is mutable by `editor_ops.rs`, this method is provided
        /// to mark when mutable access is made to this struct.
        ///
        /// This makes it easy to determine what code mutates this struct, since it is
        /// necessary to validate things after mutation quite a bit in `editor_ops.rs`.
        ///
        /// [`crate::EditorBufferMut`] implements the [Drop] trait, which ensures that any
        /// validation changes are applied after making changes to the [`EditorBuffer`].
        ///
        /// Note that if `vp` is [`crate::dummy_viewport()`] that means that the viewport
        /// argument was not passed in from a [`crate::EditorEngine`], since this method
        /// can be called without having an instance of that type.
        pub fn get_mut(&mut self, vp: Size) -> EditorBufferMutWithDrop<'_> {
            EditorBufferMutWithDrop::new(
                &mut self.content.lines,
                &mut self.content.caret_raw,
                &mut self.content.scr_ofs,
                &mut self.content.sel_list,
                vp,
                &mut self.memory_size_calc_cache,
            )
        }

        /// This is a special case of [`EditorBuffer::get_mut`] where the [Drop] trait is
        /// not used to perform validation checks after mutation. This is useful when you
        /// don't want to run validation checks after mutation, which happens when the
        /// window is resized using [`mod@crate::validate_scroll_on_resize`].
        pub fn get_mut_no_drop(&mut self, vp: Size) -> EditorBufferMutNoDrop<'_> {
            EditorBufferMutNoDrop::new(
                &mut self.content.lines,
                &mut self.content.caret_raw,
                &mut self.content.scr_ofs,
                &mut self.content.sel_list,
                vp,
                &mut self.memory_size_calc_cache,
            )
        }

        #[must_use]
        pub fn has_selection(&self) -> bool { !self.content.sel_list.is_empty() }

        /// Clears the text selection that the user has made in the editor.
        ///
        /// Large selections can occupy a significant amount of memory, so this method
        /// also invalidates the memory size cache to ensure accurate telemetry reporting.
        pub fn clear_selection(&mut self) {
            self.content.sel_list.clear();
            self.invalidate_memory_size_calc_cache();
        }

        #[must_use]
        pub fn get_selection_list(&self) -> &SelectionList { &self.content.sel_list }
    }
}

/// Memory size caching for performance optimization.
mod memory_size_calc_cache {
    use super::{CachedMemorySize, EditorBuffer, MemorySize};
    use crate::{GetMemSize, MemoizedMemorySize};

    impl GetMemSize for EditorBuffer {
        fn get_mem_size(&self) -> usize {
            self.content.get_mem_size() + self.history.get_mem_size()
        }
    }

    impl CachedMemorySize for EditorBuffer {
        fn memory_size_cache(&self) -> &MemoizedMemorySize {
            &self.memory_size_calc_cache
        }

        fn memory_size_cache_mut(&mut self) -> &mut MemoizedMemorySize {
            &mut self.memory_size_calc_cache
        }
    }

    impl EditorBuffer {
        /// Invalidates and immediately recalculates the memory size cache.
        /// Call this when buffer content changes to ensure the cache is always valid.
        pub fn invalidate_memory_size_calc_cache(&mut self) {
            self.invalidate_memory_size_cache();
            self.update_memory_size_cache(); // Immediately recalculate
        }

        /// Updates cache if dirty or not present.
        /// The closure is only called if recalculation is needed.
        pub fn upsert_memory_size_calc_cache(&mut self) {
            self.update_memory_size_cache();
        }

        /// Gets the cached memory size value, recalculating if necessary.
        /// This is used by external code to access buffer memory size efficiently.
        /// The expensive memory calculation is only performed if the cache is invalid or
        /// empty. Returns a `MemorySize` that displays "?" if the cache is not
        /// available.
        #[must_use]
        pub fn get_memory_size_calc_cached(&mut self) -> MemorySize {
            self.get_cached_memory_size()
        }
    }
}

/// Efficient Display implementation for telemetry logging.
mod display_impl {
    use super::{Display, EditorBuffer, Formatter, MemorySize, Result, ok};

    impl Display for EditorBuffer {
        /// This must be a fast implementation, so we avoid deep traversal of the
        /// editor buffer. This is used for telemetry reporting, and it is expected
        /// to be fast, since it is called in a hot loop, on every render.
        fn fmt(&self, f: &mut Formatter<'_>) -> Result {
            // Note: Display requires &self not &mut self, so we access the cache
            // directly. The cache is populated elsewhere in the buffer's lifecycle
            // via invalidate_memory_size_calc_cache(). Use MemorySize's Display impl
            // which handles the "?" case automatically.
            let memory_size = self
                .memory_size_calc_cache
                .get_cached()
                .cloned()
                .unwrap_or_else(MemorySize::unknown);

            // Format basic info.
            let line_count = self.content.lines.len();
            let has_selection = self.has_selection();

            // Get active line/column info.
            let caret = self.get_caret_scr_adj();
            let line = caret.row_index.as_usize() + 1; // 1-indexed for display.
            let col = caret.col_index.as_usize() + 1; // 1-indexed for display.

            // Get file info and format output.
            let ext = self
                .content
                .maybe_file_extension
                .as_ref()
                .map_or("txt", |e| e.as_str());

            // Format editor identifier: extract filename from path for named buffers,
            // or use placeholder for new/unnamed buffers.
            match self.content.maybe_file_path.as_ref() {
                Some(path) => {
                    let file_name = path.rsplit('/').next().unwrap_or("<unnamed>");
                    write!(f, "editor:{file_name}.{ext}:L{line}:C{col}")?;
                }
                None => {
                    write!(f, "editor:<new-buffer>.{ext}:L{line}:C{col}")?;
                }
            }

            // Add selection info if present.
            if has_selection {
                let sel_count = self.content.sel_list.len();
                write!(f, ":sel({sel_count}L)")?;
            }

            // Add summary info.
            write!(f, "[lines={line_count}, size={memory_size}]")?;

            ok!()
        }
    }
}

mod debug_impl {
    use super::{Debug, EditorBuffer, EditorContent, Formatter, Result,
                format_as_kilobytes_with_commas};

    impl Debug for EditorBuffer {
        fn fmt(&self, f: &mut Formatter<'_>) -> Result {
            write!(
                f,
                "EditorBuffer [
  - content: {content:?}
  - history: {history:?}
]",
                content = self.content,
                history = self.history,
            )
        }
    }

    impl Debug for EditorContent {
        fn fmt(&self, f: &mut Formatter<'_>) -> Result {
            use crate::GetMemSize;
            let mem_size = self.get_mem_size();
            let mem_size_fmt = format_as_kilobytes_with_commas(mem_size);

            write! {
                f,
                "EditorContent [
    - lines: {lines}, size: {size}
    - selection_map: {map}
    - ext: {ext:?}, path:{path:?}, caret: {caret:?}, scroll_offset: {scroll:?}
    ]",
                lines = self.lines.len(),
                size = mem_size_fmt,
                ext = self.maybe_file_extension,
                caret = self.caret_raw,
                map = self.sel_list.to_formatted_string(),
                scroll = self.scr_ofs,
                path = self.maybe_file_path,
            }
        }
    }
}

#[cfg(test)]
mod test_memory_cache_invalidation {
    use super::*;
    use crate::{CaretMovementDirection, EditorEngine, RingBuffer, assert_eq2,
                caret_scr_adj, col};

    #[test]
    fn test_cache_invalidated_on_get_mut() {
        let mut buffer = EditorBuffer::new_empty(Some("md"), None);
        let engine = EditorEngine::default();

        // Set initial content and cache the memory size.
        buffer.init_with(["Hello", "World"]);
        buffer.upsert_memory_size_calc_cache(); // Populate cache
        let initial_memory = buffer
            .memory_size_calc_cache
            .get_cached()
            .cloned()
            .expect("Cache should have value");
        let initial_size = initial_memory.size().expect("Cache should have value");
        assert!(initial_size > 0);

        // Modify content through get_mut.
        {
            let buffer_mut = buffer.get_mut(engine.viewport());
            buffer_mut
                .inner
                .lines
                .push("More content with lots of text".grapheme_string());
        }
        // When buffer_mut goes out of scope, Drop should invalidate the cache.

        // Verify cache was invalidated and new size is calculated.
        buffer.upsert_memory_size_calc_cache(); // Populate cache
        let new_memory = buffer
            .memory_size_calc_cache
            .get_cached()
            .cloned()
            .expect("Cache should have value");
        let new_size = new_memory.size().expect("Cache should have value");
        assert!(
            new_size > initial_size,
            "Memory size should increase after adding content"
        );

        // Test that cache is not invalidated with get_mut_no_drop.
        let cached_size = new_size;
        {
            let buffer_mut_no_drop = buffer.get_mut_no_drop(engine.viewport());
            buffer_mut_no_drop
                .inner
                .lines
                .push("Even more content".grapheme_string());
        }
        // Cache should still have old value since we used no_drop variant.
        let cached_memory = buffer
            .memory_size_calc_cache
            .get_cached()
            .cloned()
            .unwrap_or_else(MemorySize::unknown);
        assert_eq!(cached_memory.size(), Some(cached_size));

        // Force recalculation to verify content actually changed.
        buffer.invalidate_memory_size_calc_cache();
        buffer.upsert_memory_size_calc_cache(); // Populate cache with new value
        let final_memory = buffer
            .memory_size_calc_cache
            .get_cached()
            .cloned()
            .expect("Cache should have value");
        let final_size = final_memory.size().expect("Cache should have value");
        assert!(
            final_size > new_size,
            "Memory size should increase after adding more content"
        );
    }

    #[test]
    fn test_editor_empty_state() {
        let buffer = EditorBuffer::new_empty(Some(DEFAULT_SYN_HI_FILE_EXT), None);
        assert_eq2!(buffer.get_lines().len(), 1);
        assert!(!buffer.is_empty());
    }

    #[test]
    fn test_is_empty_and_len() {
        let mut buffer = EditorBuffer::new_empty(None, None);

        // New buffer has one empty line, so it's not considered empty
        assert!(!buffer.is_empty());
        assert_eq2!(buffer.len(), height(1));

        // Add some content
        buffer.init_with(vec!["line 1", "line 2", "line 3"]);
        assert!(!buffer.is_empty());
        assert_eq2!(buffer.len(), height(3));

        // Clear all lines
        buffer.init_with::<Vec<&str>>(vec![]);
        assert!(buffer.is_empty());
        assert_eq2!(buffer.len(), height(0));
    }

    #[test]
    fn test_file_extension_functions() {
        // Test with no extension
        let buffer = EditorBuffer::new_empty(None, None);
        assert!(!buffer.has_file_extension());
        assert!(!buffer.is_file_extension_default());
        assert_eq2!(buffer.get_maybe_file_extension(), None);

        // Test with default extension
        let buffer = EditorBuffer::new_empty(Some(DEFAULT_SYN_HI_FILE_EXT), None);
        assert!(buffer.has_file_extension());
        assert!(buffer.is_file_extension_default());
        assert_eq2!(
            buffer.get_maybe_file_extension(),
            Some(DEFAULT_SYN_HI_FILE_EXT)
        );

        // Test with custom extension
        let buffer = EditorBuffer::new_empty(Some("rs"), None);
        assert!(buffer.has_file_extension());
        assert!(!buffer.is_file_extension_default());
        assert_eq2!(buffer.get_maybe_file_extension(), Some("rs"));
    }

    #[test]
    fn test_memory_cache_functions() {
        let mut buffer = EditorBuffer::new_empty(None, None);

        // Initially, cache should be empty (dirty)
        assert!(buffer.memory_size_calc_cache.get_cached().is_none());

        // Populate the cache
        buffer.upsert_memory_size_calc_cache();
        let initial_cache = buffer
            .memory_size_calc_cache
            .get_cached()
            .cloned()
            .expect("Cache should be populated");
        assert!(initial_cache.size().is_some());

        // Note: invalidate_memory_size_calc_cache() actually invalidates AND recalculates
        // So the cache will never be None after calling it
        let size_before_invalidate = initial_cache.size().unwrap();
        buffer.invalidate_memory_size_calc_cache();
        let cache_after_invalidate = buffer
            .memory_size_calc_cache
            .get_cached()
            .cloned()
            .expect("Cache should be recalculated after invalidate");
        assert_eq!(
            cache_after_invalidate.size().unwrap(),
            size_before_invalidate
        );

        // When accessed through get_memory_size_calc_cached(), it auto-populates
        let auto_populated = buffer.get_memory_size_calc_cached();
        assert!(auto_populated.size().is_some());

        // Verify cache is now populated
        assert!(buffer.memory_size_calc_cache.get_cached().is_some());
    }

    #[test]
    fn test_get_mut_invalidates_cache() {
        let mut buffer = EditorBuffer::new_empty(None, None);
        let engine = EditorEngine::default();

        // Populate the cache
        buffer.upsert_memory_size_calc_cache();
        assert!(buffer.memory_size_calc_cache.get_cached().is_some());

        // get_mut should invalidate the cache when dropped
        {
            let _buffer_mut = buffer.get_mut(engine.viewport());
        }

        // Cache should be invalidated
        assert!(buffer.memory_size_calc_cache.get_cached().is_none());
    }

    #[test]
    fn test_get_mut_no_drop_preserves_cache() {
        let mut buffer = EditorBuffer::new_empty(None, None);
        let engine = EditorEngine::default();

        // Populate the cache
        buffer.upsert_memory_size_calc_cache();
        assert!(buffer.get_memory_size_calc_cached().size().is_some());

        // get_mut_no_drop should NOT invalidate the cache
        {
            let _buffer_mut_no_drop = buffer.get_mut_no_drop(engine.viewport());
        }

        // Cache should still be valid
        assert!(buffer.get_memory_size_calc_cached().size().is_some());
    }

    #[test]
    fn test_clear_selection() {
        let mut buffer = EditorBuffer::new_empty(None, None);
        let engine = EditorEngine::default();

        // Add some content and create a selection
        buffer.init_with(vec!["line 1", "line 2"]);

        // Manually add a selection
        let buffer_mut = buffer.get_mut(engine.viewport());
        buffer_mut.inner.sel_list.insert(
            row(0),
            (
                caret_scr_adj(col(0) + row(0)),
                caret_scr_adj(col(4) + row(0)),
            )
                .into(),
            CaretMovementDirection::Right,
        );
        drop(buffer_mut);

        // Verify selection exists
        assert!(!buffer.get_selection_list().is_empty());
        assert_eq2!(buffer.get_selection_list().len(), 1);

        // Clear selection
        buffer.clear_selection();

        // Verify selection is cleared
        assert!(buffer.get_selection_list().is_empty());
        assert_eq2!(buffer.get_selection_list().len(), 0);
    }

    #[test]
    fn test_history_functions() {
        let mut buffer = EditorBuffer::new_empty(None, None);
        let engine = EditorEngine::default();

        // Initialize with some content
        buffer.init_with(vec!["initial"]);
        buffer.add(); // Add initial state to history

        // Make a change using the proper mutation API
        {
            let buffer_mut = buffer.get_mut(engine.viewport());
            buffer_mut.inner.lines.clear();
            buffer_mut.inner.lines.push("changed".grapheme_string());
        }
        buffer.add(); // Add changed state to history

        // Now history should have 2 versions
        assert_eq2!(buffer.history.versions.len(), 2.into());
        assert_eq2!(buffer.get_lines()[0], "changed".grapheme_string());

        // Undo should go back to "initial"
        buffer.undo();
        assert_eq2!(buffer.get_lines()[0], "initial".grapheme_string());

        // Redo should go forward to "changed"
        buffer.redo();
        assert_eq2!(buffer.get_lines()[0], "changed".grapheme_string());

        // Another undo
        buffer.undo();
        assert_eq2!(buffer.get_lines()[0], "initial".grapheme_string());
    }
}