gpuikit 0.9.0

A UI toolkit for GPUI applications
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
//! Gap buffer implementation for efficient text editing.
//!
//! This module provides a gap buffer data structure that efficiently handles
//! text insertions and deletions at arbitrary positions. The gap buffer maintains
//! a gap (unused space) at the cursor position, making insertions and deletions
//! at that position O(1) operations.
//!
//! # Design
//!
//! The gap buffer uses a single contiguous array with a "gap" of unused space.
//! When text is inserted or deleted, the gap moves to that position first,
//! then the operation is performed by adjusting the gap boundaries.
//!
//! # Trade-offs
//!
//! - Insertions/deletions at cursor position: O(1)
//! - Moving the gap: O(n) where n is the distance moved
//! - Memory overhead: The gap size (typically grows as needed)
//! - Line-based operations: Currently O(n) as they require string conversion

use std::cmp::{max, min};

/// A minimal text buffer trait that supports the features we have so far
pub trait TextBuffer {
    /// Get the total number of lines in the buffer
    fn line_count(&self) -> usize;

    /// Get a specific line by index (0-based)
    fn get_line(&self, line_idx: usize) -> Option<String>;

    /// Get the length of a specific line in characters
    fn line_len(&self, line_idx: usize) -> usize {
        self.get_line(line_idx)
            .map(|s| s.chars().count())
            .unwrap_or(0)
    }

    /// Get all lines (for now, while we're simple)
    fn all_lines(&self) -> Vec<String>;

    /// Insert text at a specific position (row, col)
    fn insert_at(&mut self, row: usize, col: usize, text: &str);

    /// Delete a character at a specific position (row, col)
    fn delete_at(&mut self, row: usize, col: usize);

    /// Delete backwards from a specific position (row, col)
    fn backspace_at(&mut self, row: usize, col: usize);
}

/// Gap buffer implementation for efficient text editing.
///
/// The buffer maintains text as a vector of characters with a gap at the
/// current editing position. This makes insertions and deletions at the
/// cursor position very efficient (O(1)), at the cost of having to move
/// the gap when editing at different positions.
///
/// # Example Structure
///
/// For text "Hello World" with gap after "Hello":
/// ```text
/// ['H', 'e', 'l', 'l', 'o', '\0', '\0', '\0', ' ', 'W', 'o', 'r', 'l', 'd']
///                           ^gap_start      ^gap_end
/// ```
#[derive(Clone)]
pub struct GapBuffer {
    /// The buffer containing the text with a gap for efficient insertion
    buffer: Vec<char>,
    /// Start position of the gap (inclusive)
    gap_start: usize,
    /// End position of the gap (exclusive)
    gap_end: usize,
}

impl GapBuffer {
    /// Create a new empty gap buffer
    pub fn new() -> Self {
        let initial_capacity = 1024;
        let buffer = vec!['\0'; initial_capacity];
        Self {
            buffer,
            gap_start: 0,
            gap_end: initial_capacity,
        }
    }

    /// Create a gap buffer from text
    pub fn from_text(text: &str) -> Self {
        let chars: Vec<char> = text.chars().collect();
        let text_len = chars.len();

        // Add extra capacity for the gap
        let capacity = max(1024, text_len * 2);
        let mut buffer = vec!['\0'; capacity];

        // Copy text to the beginning
        for (i, &ch) in chars.iter().enumerate() {
            buffer[i] = ch;
        }

        Self {
            buffer,
            gap_start: text_len,
            gap_end: capacity,
        }
    }

    /// Create a gap buffer from lines
    pub fn from_lines(lines: Vec<String>) -> Self {
        Self::from_text(&lines.join("\n"))
    }

    /// Get the length of the content (excluding the gap)
    pub fn len(&self) -> usize {
        self.buffer.len() - self.gap_size()
    }

    /// Whether the buffer holds no content β€” the gap spans the whole allocation
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Get the size of the gap
    fn gap_size(&self) -> usize {
        self.gap_end - self.gap_start
    }

    /// Move the gap to a specific position in the text.
    ///
    /// This is the core operation that enables efficient editing. When the gap
    /// is at the cursor position, insertions and deletions become O(1) operations.
    ///
    /// # Complexity
    /// O(n) where n is the distance between the current gap position and the target position
    pub fn move_gap_to(&mut self, position: usize) {
        let position = min(position, self.len());

        if position < self.gap_start {
            // Move gap backward - move characters from before gap to after gap
            let move_count = self.gap_start - position;

            // Move characters right-to-left to avoid overwriting
            for i in (0..move_count).rev() {
                self.buffer[self.gap_end - 1 - i] = self.buffer[self.gap_start - 1 - i];
            }

            self.gap_end -= move_count;
            self.gap_start -= move_count;
        } else if position > self.gap_start {
            // Move gap forward - move characters from after gap to before gap
            let move_count = position - self.gap_start;

            // Move characters left-to-right
            for i in 0..move_count {
                if self.gap_end + i < self.buffer.len() {
                    self.buffer[self.gap_start + i] = self.buffer[self.gap_end + i];
                }
            }

            self.gap_start += move_count;
            self.gap_end += move_count;
        }
    }

    /// Insert a character at the specified position.
    ///
    /// Moves the gap to the position first, then inserts the character
    /// by placing it at gap_start and incrementing gap_start.
    pub fn insert_char(&mut self, position: usize, ch: char) {
        self.move_gap_to(position);
        if self.gap_start >= self.gap_end {
            self.grow_gap();
        }
        self.buffer[self.gap_start] = ch;
        self.gap_start += 1;
    }

    /// Insert text at the specified position
    pub fn insert(&mut self, position: usize, text: &str) {
        self.move_gap_to(position);
        for ch in text.chars() {
            if self.gap_start >= self.gap_end {
                self.grow_gap();
            }
            self.buffer[self.gap_start] = ch;
            self.gap_start += 1;
        }
    }

    /// Delete backward from the specified position
    pub fn delete_backward(&mut self, position: usize) {
        if position > 0 {
            self.move_gap_to(position);
            self.gap_start -= 1;
        }
    }

    /// Delete forward from the specified position
    pub fn delete_forward(&mut self, position: usize) {
        self.move_gap_to(position);
        if self.gap_end < self.buffer.len() {
            self.gap_end += 1;
        }
    }

    /// Delete a range of text
    pub fn delete_range(&mut self, start: usize, end: usize) {
        if start >= end {
            return;
        }

        let start = min(start, self.len());
        let end = min(end, self.len());

        self.move_gap_to(start);
        let delete_count = end - start;
        self.gap_end = min(self.gap_end + delete_count, self.buffer.len());
    }

    /// Grow the gap when it becomes too small
    fn grow_gap(&mut self) {
        let old_capacity = self.buffer.len();
        let new_capacity = old_capacity * 2;
        let additional_capacity = new_capacity - old_capacity;

        let mut new_buffer = vec!['\0'; new_capacity];

        // Copy content before the gap
        new_buffer[..self.gap_start].copy_from_slice(&self.buffer[..self.gap_start]);

        // Copy content after the gap
        let after_gap_start = self.gap_end;
        let after_gap_count = old_capacity - self.gap_end;
        let new_gap_end = self.gap_start + self.gap_size() + additional_capacity;

        new_buffer[new_gap_end..new_gap_end + after_gap_count]
            .copy_from_slice(&self.buffer[after_gap_start..after_gap_start + after_gap_count]);

        self.buffer = new_buffer;
        self.gap_end = new_gap_end;
    }

    /// Convert the buffer to lines, with the `\n` separators stripped.
    ///
    /// This is the *display* view: it is what `get_line`, `line_len`,
    /// `all_lines` and the editor element's layout read, so a row index here
    /// means the same thing everywhere on screen.
    ///
    /// It is **not** what a syntax highlighter should be fed β€” the syntax set
    /// is `load_defaults_newlines`, whose grammars anchor rules to end of line.
    /// Use [`to_lines_with_endings`](Self::to_lines_with_endings) for that.
    pub fn to_lines(&self) -> Vec<String> {
        let text = self.to_string();
        if text.is_empty() {
            vec![String::new()]
        } else {
            let lines: Vec<String> = text.split('\n').map(|s| s.to_string()).collect();
            if lines.is_empty() {
                vec![String::new()]
            } else {
                lines
            }
        }
    }

    /// Convert the buffer to lines that still carry their `\n` separator.
    ///
    /// This is the view a syntax highlighter wants: the crate parses against
    /// `SyntaxSet::load_defaults_newlines()`, whose grammars contain rules
    /// anchored to end of line, so a `//` comment or an unterminated string
    /// only closes if the parser is shown the newline that closes it.
    ///
    /// Two invariants hold by construction, and are tested:
    ///
    /// - The line *count* is identical to [`to_lines`](Self::to_lines), so a
    ///   row index means the same thing in both.
    /// - Concatenating the result reproduces `to_string` (via [`std::fmt::Display`])
    ///   byte for byte, so a line-by-line pass sees exactly the document a
    ///   whole-text pass would.
    ///
    /// The last line is the one line that legitimately has no separator: text
    /// ending in `\n` keeps `to_lines`'s trailing empty string, so no phantom
    /// line is added here either.
    pub fn to_lines_with_endings(&self) -> Vec<String> {
        let mut lines = self.to_lines();
        let last = lines.len().saturating_sub(1);
        for line in lines.iter_mut().take(last) {
            line.push('\n');
        }
        lines
    }

    /// Convert cursor position (row, col) to buffer position.
    ///
    /// Translates a 2D cursor position (line and column) to a linear
    /// position in the buffer. This is used to map editor cursor positions
    /// to buffer positions for editing operations.
    ///
    /// # Returns
    /// The character index in the buffer corresponding to the cursor position
    pub fn cursor_to_position(&self, row: usize, col: usize) -> usize {
        let text = self.to_string();
        let mut current_row = 0;
        let mut current_col = 0;
        let mut char_index = 0;

        for ch in text.chars() {
            if current_row == row && current_col == col {
                return char_index;
            }

            if ch == '\n' {
                if current_row == row {
                    return char_index; // Return position at end of line if col is beyond line end
                }
                current_row += 1;
                current_col = 0;
            } else {
                current_col += 1;
            }
            char_index += 1;
        }

        // Return character count if position is beyond
        char_index
    }

    /// Convert buffer position to cursor position (row, col).
    ///
    /// Translates a linear buffer position to a 2D cursor position
    /// (line and column). This is the inverse of `cursor_to_position`.
    ///
    /// # Returns
    /// A tuple of (row, column) representing the cursor position
    pub fn position_to_cursor(&self, position: usize) -> (usize, usize) {
        let text = self.to_string();
        let char_count = text.chars().count();
        let position = min(position, char_count);

        let mut row = 0;
        let mut col = 0;

        for (char_index, ch) in text.chars().enumerate() {
            if char_index >= position {
                break;
            }
            if ch == '\n' {
                row += 1;
                col = 0;
            } else {
                col += 1;
            }
        }

        (row, col)
    }
}

/// Reconstructs the text by concatenating the content before the gap with the
/// content after the gap, skipping the gap itself. `GapBuffer::to_string`
/// (via `ToString`) goes through here. O(n) in the length of the text.
impl std::fmt::Display for GapBuffer {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        use std::fmt::Write as _;

        // Content before the gap
        for &ch in &self.buffer[..self.gap_start] {
            f.write_char(ch)?;
        }

        // Content after the gap
        for &ch in &self.buffer[self.gap_end..] {
            if ch != '\0' {
                f.write_char(ch)?;
            }
        }

        Ok(())
    }
}

impl Default for GapBuffer {
    fn default() -> Self {
        Self::new()
    }
}

impl TextBuffer for GapBuffer {
    fn line_count(&self) -> usize {
        let text = self.to_string();
        if text.is_empty() {
            1
        } else {
            text.chars().filter(|&c| c == '\n').count() + 1
        }
    }

    fn get_line(&self, line_idx: usize) -> Option<String> {
        let lines = self.to_lines();
        lines.get(line_idx).cloned()
    }

    fn all_lines(&self) -> Vec<String> {
        self.to_lines()
    }

    fn line_len(&self, line_idx: usize) -> usize {
        let lines = self.to_lines();
        lines.get(line_idx).map(|s| s.chars().count()).unwrap_or(0)
    }

    fn insert_at(&mut self, row: usize, col: usize, text: &str) {
        let position = self.cursor_to_position(row, col);
        self.insert(position, text);
    }

    fn delete_at(&mut self, row: usize, col: usize) {
        let position = self.cursor_to_position(row, col);
        self.delete_forward(position);
    }

    fn backspace_at(&mut self, row: usize, col: usize) {
        let position = self.cursor_to_position(row, col);
        if position > 0 {
            self.delete_backward(position);
        }
    }
}

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

    #[test]
    fn test_line_splitting_with_newlines() {
        let buffer = GapBuffer::from_text("Hello\nWorld\nTest");
        let lines = buffer.to_lines();

        assert_eq!(lines.len(), 3);
        assert_eq!(lines[0], "Hello");
        assert_eq!(lines[1], "World");
        assert_eq!(lines[2], "Test");
    }

    #[test]
    fn test_cursor_position_conversion() {
        let buffer = GapBuffer::from_text("Hello\nWorld");

        // Test cursor to position
        assert_eq!(buffer.cursor_to_position(0, 0), 0);
        assert_eq!(buffer.cursor_to_position(0, 5), 5);
        assert_eq!(buffer.cursor_to_position(1, 0), 6);
        assert_eq!(buffer.cursor_to_position(1, 5), 11);

        // Test position to cursor
        assert_eq!(buffer.position_to_cursor(0), (0, 0));
        assert_eq!(buffer.position_to_cursor(5), (0, 5));
        assert_eq!(buffer.position_to_cursor(6), (1, 0));
    }

    #[test]
    fn test_newline_insertion() {
        let mut buffer = GapBuffer::from_text("HelloWorld");
        buffer.insert(5, "\n");

        let lines = buffer.to_lines();
        assert_eq!(lines.len(), 2);
        assert_eq!(lines[0], "Hello");
        assert_eq!(lines[1], "World");

        assert_eq!(buffer.to_string(), "Hello\nWorld");
    }

    #[test]
    fn test_new_empty_buffer() {
        let buffer = GapBuffer::new();
        assert_eq!(buffer.len(), 0);
        assert_eq!(buffer.to_string(), "");
    }

    #[test]
    fn test_from_text() {
        let buffer = GapBuffer::from_text("Hello, World!");
        assert_eq!(buffer.len(), 13);
        assert_eq!(buffer.to_string(), "Hello, World!");
    }

    #[test]
    fn test_from_lines() {
        let lines = vec!["Hello".to_string(), "World".to_string()];
        let buffer = GapBuffer::from_lines(lines);
        assert_eq!(buffer.to_string(), "Hello\nWorld");
    }

    #[test]
    fn test_insert_char() {
        let mut buffer = GapBuffer::from_text("Hello");
        buffer.insert_char(5, '!');
        assert_eq!(buffer.to_string(), "Hello!");

        buffer.insert_char(0, '>');
        assert_eq!(buffer.to_string(), ">Hello!");

        buffer.insert_char(3, '<');
        assert_eq!(buffer.to_string(), ">He<llo!");
    }

    #[test]
    fn test_insert_text_various_positions() {
        let mut buffer = GapBuffer::from_text("Hello");

        // Insert at end
        buffer.insert(5, " World");
        assert_eq!(buffer.to_string(), "Hello World");

        // Insert at beginning
        buffer.insert(0, "Say ");
        assert_eq!(buffer.to_string(), "Say Hello World");

        // Insert in middle
        buffer.insert(9, " Beautiful");
        assert_eq!(buffer.to_string(), "Say Hello Beautiful World");
    }

    #[test]
    fn test_insert_multiline() {
        let mut buffer = GapBuffer::from_text("Line1");
        buffer.insert(5, "\nLine2\nLine3");
        assert_eq!(buffer.to_string(), "Line1\nLine2\nLine3");

        let lines = buffer.to_lines();
        assert_eq!(lines.len(), 3);
        assert_eq!(lines[0], "Line1");
        assert_eq!(lines[1], "Line2");
        assert_eq!(lines[2], "Line3");
    }

    #[test]
    fn test_delete_backward() {
        let mut buffer = GapBuffer::from_text("Hello World");

        buffer.delete_backward(11);
        assert_eq!(buffer.to_string(), "Hello Worl");

        buffer.delete_backward(6);
        assert_eq!(buffer.to_string(), "HelloWorl");

        buffer.delete_backward(1);
        assert_eq!(buffer.to_string(), "elloWorl");
    }

    #[test]
    fn test_delete_forward() {
        let mut buffer = GapBuffer::from_text("Hello World");

        buffer.delete_forward(0);
        assert_eq!(buffer.to_string(), "ello World");

        buffer.delete_forward(4);
        assert_eq!(buffer.to_string(), "elloWorld");

        buffer.delete_forward(8);
        assert_eq!(buffer.to_string(), "elloWorl");
    }

    #[test]
    fn test_delete_range() {
        let mut buffer = GapBuffer::from_text("Hello World");

        buffer.delete_range(5, 11);
        assert_eq!(buffer.to_string(), "Hello");

        let mut buffer = GapBuffer::from_text("Hello World");
        buffer.delete_range(0, 6);
        assert_eq!(buffer.to_string(), "World");

        let mut buffer = GapBuffer::from_text("Hello World");
        buffer.delete_range(2, 8);
        assert_eq!(buffer.to_string(), "Herld");
    }

    #[test]
    fn test_delete_range_edge_cases() {
        let mut buffer = GapBuffer::from_text("Hello");

        // Delete everything
        buffer.delete_range(0, 5);
        assert_eq!(buffer.to_string(), "");

        // Delete with inverted range (should do nothing)
        let mut buffer = GapBuffer::from_text("Hello");
        buffer.delete_range(3, 2);
        assert_eq!(buffer.to_string(), "Hello");
    }

    #[test]
    fn test_move_gap_to() {
        let mut buffer = GapBuffer::from_text("Hello World");
        let initial_text = buffer.to_string();

        // Moving gap shouldn't change the text
        buffer.move_gap_to(5);
        assert_eq!(buffer.to_string(), initial_text);

        buffer.move_gap_to(0);
        assert_eq!(buffer.to_string(), initial_text);

        buffer.move_gap_to(11);
        assert_eq!(buffer.to_string(), initial_text);
    }

    #[test]
    fn test_gap_movement_with_operations() {
        let mut buffer = GapBuffer::from_text("ABC");

        // Insert at beginning
        buffer.insert(0, "1");
        assert_eq!(buffer.to_string(), "1ABC");

        // Insert at end
        buffer.insert(4, "2");
        assert_eq!(buffer.to_string(), "1ABC2");

        // Insert in middle
        buffer.insert(2, "X");
        assert_eq!(buffer.to_string(), "1AXBC2");
    }

    #[test]
    fn test_cursor_to_position() {
        let buffer = GapBuffer::from_text("Line1\nLine2\nLine3");

        assert_eq!(buffer.cursor_to_position(0, 0), 0);
        assert_eq!(buffer.cursor_to_position(0, 5), 5);
        assert_eq!(buffer.cursor_to_position(1, 0), 6);
        assert_eq!(buffer.cursor_to_position(1, 5), 11);
        assert_eq!(buffer.cursor_to_position(2, 0), 12);

        // Out of bounds column
        assert_eq!(buffer.cursor_to_position(0, 100), 5);
    }

    #[test]
    fn test_position_to_cursor() {
        let buffer = GapBuffer::from_text("Line1\nLine2\nLine3");

        assert_eq!(buffer.position_to_cursor(0), (0, 0));
        assert_eq!(buffer.position_to_cursor(5), (0, 5));
        assert_eq!(buffer.position_to_cursor(6), (1, 0));
        assert_eq!(buffer.position_to_cursor(11), (1, 5));
        assert_eq!(buffer.position_to_cursor(12), (2, 0));

        // Out of bounds position
        assert_eq!(buffer.position_to_cursor(100), (2, 5));
    }

    #[test]
    fn test_cursor_position_roundtrip() {
        let buffer = GapBuffer::from_text("Hello\nWorld\n!");

        for row in 0..3 {
            for col in 0..6 {
                let pos = buffer.cursor_to_position(row, col);
                let (r, c) = buffer.position_to_cursor(pos);
                if col <= buffer.line_len(row) {
                    assert_eq!((r, c), (row, col.min(buffer.line_len(row))));
                }
            }
        }
    }

    #[test]
    fn test_to_lines() {
        let buffer = GapBuffer::from_text("Line1\nLine2\nLine3");
        let lines = buffer.to_lines();
        assert_eq!(lines, vec!["Line1", "Line2", "Line3"]);

        let empty_buffer = GapBuffer::new();
        let empty_lines = empty_buffer.to_lines();
        assert_eq!(empty_lines, vec![""]);
    }

    #[test]
    fn test_to_lines_with_endings() {
        let buffer = GapBuffer::from_text("Line1\nLine2\nLine3");
        assert_eq!(
            buffer.to_lines_with_endings(),
            vec!["Line1\n", "Line2\n", "Line3"]
        );

        // Text that ends in a newline keeps `to_lines`'s trailing empty line,
        // and that line gets no separator of its own.
        let buffer = GapBuffer::from_text("Line1\nLine2\n");
        assert_eq!(
            buffer.to_lines_with_endings(),
            vec!["Line1\n", "Line2\n", ""]
        );

        let buffer = GapBuffer::from_text("no newline at all");
        assert_eq!(buffer.to_lines_with_endings(), vec!["no newline at all"]);

        let buffer = GapBuffer::new();
        assert_eq!(buffer.to_lines_with_endings(), vec![""]);
    }

    #[test]
    fn test_to_lines_with_endings_reproduces_the_buffer() {
        for text in [
            "",
            "one line",
            "Line1\nLine2\nLine3",
            "Line1\nLine2\n",
            "\n\n\n",
            "Hello δΈ–η•Œ\n🌍 emoji\n",
        ] {
            let buffer = GapBuffer::from_text(text);
            let with_endings = buffer.to_lines_with_endings();

            // Same number of rows as the display view.
            assert_eq!(
                with_endings.len(),
                buffer.to_lines().len(),
                "row count diverged for {text:?}"
            );

            // And concatenating them is the document, byte for byte.
            assert_eq!(
                with_endings.concat(),
                buffer.to_string(),
                "round trip failed for {text:?}"
            );
        }
    }

    #[test]
    fn test_line_count() {
        let buffer = GapBuffer::from_text("");
        assert_eq!(buffer.line_count(), 1);

        let buffer = GapBuffer::from_text("Hello");
        assert_eq!(buffer.line_count(), 1);

        let buffer = GapBuffer::from_text("Hello\nWorld");
        assert_eq!(buffer.line_count(), 2);

        let buffer = GapBuffer::from_text("Line1\nLine2\nLine3");
        assert_eq!(buffer.line_count(), 3);

        let buffer = GapBuffer::from_text("Line1\nLine2\n");
        assert_eq!(buffer.line_count(), 3);
    }

    #[test]
    fn test_line_len() {
        let buffer = GapBuffer::from_text("Hello\nWorld!\n");
        assert_eq!(buffer.line_len(0), 5);
        assert_eq!(buffer.line_len(1), 6);
        assert_eq!(buffer.line_len(2), 0);
    }

    #[test]
    fn test_insert_at() {
        let mut buffer = GapBuffer::from_text("Hello\nWorld");

        buffer.insert_at(0, 5, "!");
        assert_eq!(buffer.to_string(), "Hello!\nWorld");

        buffer.insert_at(1, 5, "!");
        assert_eq!(buffer.to_string(), "Hello!\nWorld!");

        buffer.insert_at(1, 0, "> ");
        assert_eq!(buffer.to_string(), "Hello!\n> World!");
    }

    #[test]
    fn test_delete_at() {
        let mut buffer = GapBuffer::from_text("Hello\nWorld");

        buffer.delete_at(0, 4);
        assert_eq!(buffer.to_string(), "Hell\nWorld");

        buffer.delete_at(1, 0);
        assert_eq!(buffer.to_string(), "Hell\norld");
    }

    #[test]
    fn test_backspace_at() {
        let mut buffer = GapBuffer::from_text("Hello\nWorld");

        buffer.backspace_at(0, 5);
        assert_eq!(buffer.to_string(), "Hell\nWorld");

        buffer.backspace_at(1, 1);
        assert_eq!(buffer.to_string(), "Hell\norld");

        // Backspace at beginning of line merges with previous
        buffer.backspace_at(1, 0);
        assert_eq!(buffer.to_string(), "Hellorld");
    }

    #[test]
    fn test_grow_gap() {
        let mut buffer = GapBuffer::from_text("Hi");
        let mut long_text = String::new();
        for _ in 0..1000 {
            long_text.push('x');
        }
        buffer.insert(2, &long_text);
        assert_eq!(buffer.to_string(), format!("Hi{}", long_text));
    }

    #[test]
    fn test_gap_movement_preserves_text() {
        let mut buffer = GapBuffer::from_text("The quick brown fox jumps over the lazy dog");
        let original = buffer.to_string();

        // Move gap to various positions
        for i in 0..original.len() {
            buffer.move_gap_to(i);
            assert_eq!(buffer.to_string(), original);
        }

        // Perform operations at different positions
        buffer.insert(10, "[INSERT]");
        assert_eq!(
            buffer.to_string(),
            "The quick [INSERT]brown fox jumps over the lazy dog"
        );

        buffer.delete_range(10, 18);
        assert_eq!(buffer.to_string(), original);
    }

    #[test]
    fn test_large_buffer_with_gap_movement() {
        let mut text = String::new();
        for i in 0..100 {
            text.push_str(&format!("Line {}\n", i));
        }

        let mut buffer = GapBuffer::from_text(&text);

        // Insert at various positions
        buffer.insert(0, "START\n");
        buffer.insert(buffer.len(), "\nEND");
        buffer.insert(buffer.len() / 2, "\nMIDDLE\n");

        let result = buffer.to_string();
        assert!(result.starts_with("START\n"));
        assert!(result.ends_with("\nEND"));
        assert!(result.contains("\nMIDDLE\n"));
    }

    #[test]
    fn test_empty_buffer_operations() {
        let mut buffer = GapBuffer::new();

        buffer.insert(0, "Hello");
        assert_eq!(buffer.to_string(), "Hello");

        buffer.delete_range(0, 5);
        assert_eq!(buffer.to_string(), "");

        buffer.insert(0, "World");
        assert_eq!(buffer.to_string(), "World");

        buffer.delete_backward(5);
        assert_eq!(buffer.to_string(), "Worl");
    }

    #[test]
    fn test_newline_handling() {
        let mut buffer = GapBuffer::new();

        buffer.insert(0, "Line1");
        buffer.insert(5, "\n");
        buffer.insert(6, "Line2");
        buffer.insert(11, "\n");
        buffer.insert(12, "Line3");

        let lines = buffer.to_lines();
        assert_eq!(lines.len(), 3);
        assert_eq!(lines[0], "Line1");
        assert_eq!(lines[1], "Line2");
        assert_eq!(lines[2], "Line3");

        // Test deleting newlines
        buffer.delete_at(0, 5); // Delete newline after Line1
        assert_eq!(buffer.to_string(), "Line1Line2\nLine3");

        buffer.delete_forward(10); // Delete newline before Line3
        assert_eq!(buffer.to_string(), "Line1Line2Line3");
    }

    #[test]
    fn test_stress_random_operations() {
        let mut buffer = GapBuffer::from_text("Initial");

        // Perform many random operations
        for i in 0..50 {
            let pos = i % (buffer.len() + 1);
            buffer.insert(pos, &format!("{}", i % 10));

            if buffer.len() > 10 && i % 3 == 0 {
                let del_pos = (i * 7) % buffer.len();
                buffer.delete_forward(del_pos);
            }

            if buffer.len() > 5 && i % 5 == 0 {
                let del_pos = (i * 3) % buffer.len();
                buffer.delete_backward(del_pos);
            }
        }

        // Verify buffer integrity
        let text = buffer.to_string();
        let reconstructed = GapBuffer::from_text(&text);
        assert_eq!(reconstructed.to_string(), text);
    }

    #[test]
    fn test_large_text() {
        let mut large_text = String::new();
        for i in 0..1000 {
            large_text.push_str(&format!(
                "Line {}: This is a test line with some content.\n",
                i
            ));
        }

        let buffer = GapBuffer::from_text(&large_text);
        assert_eq!(buffer.to_string(), large_text);

        let lines = buffer.to_lines();
        assert_eq!(lines.len(), 1001); // 1000 lines + 1 empty line at end

        // Verify line operations
        assert_eq!(buffer.line_count(), 1001);
        assert!(buffer.get_line(500).is_some());
    }

    #[test]
    fn test_unicode_characters() {
        let mut buffer = GapBuffer::from_text("Hello δΈ–η•Œ");
        assert_eq!(buffer.to_string(), "Hello δΈ–η•Œ");

        buffer.insert(6, "🌍 ");
        assert_eq!(buffer.to_string(), "Hello 🌍 δΈ–η•Œ");

        buffer.insert_char(0, 'πŸ‘‹');
        assert_eq!(buffer.to_string(), "πŸ‘‹Hello 🌍 δΈ–η•Œ");

        // Test with emoji and complex unicode
        let mut buffer = GapBuffer::from_text("🎨🎭πŸŽͺ");
        buffer.delete_forward(0);
        assert_eq!(buffer.to_string(), "🎭πŸŽͺ");
    }

    #[test]
    fn test_sequential_edits() {
        let mut buffer = GapBuffer::new();

        // Simulate typing
        let text = "The quick brown fox";
        for ch in text.chars() {
            buffer.insert_char(buffer.len(), ch);
        }
        assert_eq!(buffer.to_string(), text);

        // Simulate corrections
        buffer.delete_backward(19); // Delete 'x'
        buffer.delete_backward(18); // Delete 'o'
        buffer.delete_backward(17); // Delete 'f'
        buffer.insert(16, "cat");
        assert_eq!(buffer.to_string(), "The quick brown cat");

        // Add more text
        buffer.insert(buffer.len(), " jumped over the lazy dog");
        assert_eq!(
            buffer.to_string(),
            "The quick brown cat jumped over the lazy dog"
        );
    }
}