rnk 0.17.3

A React-like declarative terminal UI framework for Rust, inspired by Ink
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
//! Output buffer for terminal rendering

use crate::core::{Color, Style};
use std::fmt::Write as FmtWrite;
use unicode_width::UnicodeWidthChar;

/// A styled character in the output grid
#[derive(Debug, Clone, Default)]
pub struct StyledChar {
    pub ch: char,
    pub fg: Option<Color>,
    pub bg: Option<Color>,
    pub bold: bool,
    pub italic: bool,
    pub underline: bool,
    pub strikethrough: bool,
    pub dim: bool,
    pub inverse: bool,
}

impl StyledChar {
    pub fn new(ch: char) -> Self {
        Self {
            ch,
            ..Default::default()
        }
    }

    pub fn with_style(ch: char, style: &Style) -> Self {
        Self {
            ch,
            fg: style.color,
            bg: style.background_color,
            bold: style.bold,
            italic: style.italic,
            underline: style.underline,
            strikethrough: style.strikethrough,
            dim: style.dim,
            inverse: style.inverse,
        }
    }

    /// Check if this char has any styling
    pub fn has_style(&self) -> bool {
        self.fg.is_some()
            || self.bg.is_some()
            || self.bold
            || self.italic
            || self.underline
            || self.strikethrough
            || self.dim
            || self.inverse
    }

    /// Check if two styled chars have the same style
    pub fn same_style(&self, other: &Self) -> bool {
        self.fg == other.fg
            && self.bg == other.bg
            && self.bold == other.bold
            && self.italic == other.italic
            && self.underline == other.underline
            && self.strikethrough == other.strikethrough
            && self.dim == other.dim
            && self.inverse == other.inverse
    }
}

/// Clip region for overflow handling
#[derive(Debug, Clone)]
pub struct ClipRegion {
    pub x1: u16,
    pub y1: u16,
    pub x2: u16,
    pub y2: u16,
}

impl ClipRegion {
    pub fn contains(&self, x: u16, y: u16) -> bool {
        x >= self.x1 && x < self.x2 && y >= self.y1 && y < self.y2
    }
}

/// Output buffer that collects rendered content
pub struct Output {
    pub width: u16,
    pub height: u16,
    /// Flat grid storage for better cache locality (row-major order)
    grid: Vec<StyledChar>,
    clip_stack: Vec<ClipRegion>,
    /// Tracks which rows have been modified since last clear_dirty()
    dirty_rows: Vec<bool>,
    /// Quick check if any row is dirty
    any_dirty: bool,
}

impl Output {
    /// Create a new output buffer
    pub fn new(width: u16, height: u16) -> Self {
        let size = (width as usize) * (height as usize);
        let grid = vec![StyledChar::new(' '); size];
        Self {
            width,
            height,
            grid,
            clip_stack: Vec::new(),
            dirty_rows: vec![false; height as usize],
            any_dirty: false,
        }
    }

    /// Calculate flat index from (col, row) coordinates
    #[inline]
    fn index(&self, col: usize, row: usize) -> usize {
        row * (self.width as usize) + col
    }

    /// Get a reference to a cell at (col, row)
    #[inline]
    fn get(&self, col: usize, row: usize) -> Option<&StyledChar> {
        if col < self.width as usize && row < self.height as usize {
            Some(&self.grid[self.index(col, row)])
        } else {
            None
        }
    }

    /// Set a cell at (col, row)
    #[inline]
    fn set(&mut self, col: usize, row: usize, value: StyledChar) {
        if col < self.width as usize && row < self.height as usize {
            let idx = self.index(col, row);
            self.grid[idx] = value;
        }
    }

    /// Get an iterator over a row
    fn row_iter(&self, row: usize) -> impl Iterator<Item = &StyledChar> {
        let start = row * (self.width as usize);
        let end = start + (self.width as usize);
        self.grid[start..end].iter()
    }

    /// Get a reference to a cell at (col, row) - public for testing
    #[cfg(test)]
    pub fn cell_at(&self, col: usize, row: usize) -> Option<&StyledChar> {
        self.get(col, row)
    }

    /// Check if any row has been modified
    pub fn is_dirty(&self) -> bool {
        self.any_dirty
    }

    /// Check if a specific row has been modified
    pub fn is_row_dirty(&self, row: usize) -> bool {
        self.dirty_rows.get(row).copied().unwrap_or(false)
    }

    /// Clear all dirty flags
    pub fn clear_dirty(&mut self) {
        self.dirty_rows.fill(false);
        self.any_dirty = false;
    }

    /// Get indices of all dirty rows
    pub fn dirty_row_indices(&self) -> impl Iterator<Item = usize> + '_ {
        self.dirty_rows
            .iter()
            .enumerate()
            .filter_map(|(i, &dirty)| if dirty { Some(i) } else { None })
    }

    /// Render only the dirty rows, returning (row_index, rendered_line) pairs
    pub fn render_dirty_rows(&self) -> Vec<(usize, String)> {
        self.assert_no_active_clips("render_dirty_rows");
        self.dirty_row_indices()
            .map(|row_idx| {
                let line = self.render_row(row_idx);
                (row_idx, line)
            })
            .collect()
    }

    /// Render a single row to a string with ANSI codes
    fn render_row(&self, row_idx: usize) -> String {
        if row_idx >= self.height as usize {
            return String::new();
        }

        let mut last_content_idx = 0;
        for (i, cell) in self.row_iter(row_idx).enumerate() {
            if cell.ch != '\0' && (cell.ch != ' ' || cell.has_style()) {
                last_content_idx = i + 1;
            }
        }

        let mut line = String::new();
        let mut current_style: Option<StyledChar> = None;

        for (i, cell) in self.row_iter(row_idx).enumerate() {
            if i >= last_content_idx {
                break;
            }

            if cell.ch == '\0' {
                continue;
            }

            let need_style_change = match &current_style {
                None => cell.has_style(),
                Some(prev) => !cell.same_style(prev),
            };

            if need_style_change {
                if current_style.is_some() {
                    line.push_str("\x1b[0m");
                }
                self.apply_style(&mut line, cell);
                current_style = Some(cell.clone());
            }

            line.push(cell.ch);
        }

        if current_style.is_some() {
            line.push_str("\x1b[0m");
        }

        line
    }

    /// Mark a row as dirty
    #[inline]
    fn mark_dirty(&mut self, row: usize) {
        if row < self.dirty_rows.len() {
            self.dirty_rows[row] = true;
            self.any_dirty = true;
        }
    }

    /// Write text at position with style
    pub fn write(&mut self, x: u16, y: u16, text: &str, style: &Style) {
        let mut col = x as usize;
        let row = y as usize;

        if row >= self.height as usize {
            return;
        }

        // Mark row as dirty before any modifications
        self.mark_dirty(row);

        let width = self.width as usize;

        for ch in text.chars() {
            if ch == '\n' {
                break;
            }

            if col >= width {
                break;
            }

            let char_width = ch.width().unwrap_or(1);

            // Handle wide character at buffer boundary - skip if it won't fit
            if char_width == 2 && col + 1 >= width {
                // Wide char would extend past buffer, write a space instead
                self.set(col, row, StyledChar::with_style(' ', style));
                col += 1;
                continue;
            }

            // Check clip region
            if let Some(clip) = self.clip_stack.last()
                && !clip.contains(col as u16, row as u16)
            {
                col += char_width;
                continue;
            }

            // Handle overwriting wide character's second half (placeholder)
            // If current position is a placeholder '\0', we're breaking a wide char
            if let Some(cell) = self.get(col, row) {
                if cell.ch == '\0' && col > 0 {
                    // Clear the first half of the broken wide char
                    self.set(col - 1, row, StyledChar::new(' '));
                }
            }

            // Handle overwriting wide character's first half
            // If current position has a wide char, its placeholder will be orphaned
            if let Some(cell) = self.get(col, row) {
                let old_char_width = cell.ch.width().unwrap_or(1);
                if old_char_width == 2 && col + 1 < width {
                    // Clear the orphaned placeholder
                    self.set(col + 1, row, StyledChar::new(' '));
                }
            }

            self.set(col, row, StyledChar::with_style(ch, style));

            // For wide characters (width=2), mark the next cell as a placeholder
            if char_width == 2 && col + 1 < width {
                // Check if we're about to overwrite another wide char's first half
                if let Some(next_cell) = self.get(col + 1, row) {
                    if next_cell.ch != '\0' {
                        let next_char_width = next_cell.ch.width().unwrap_or(1);
                        if next_char_width == 2 && col + 2 < width {
                            // Clear the placeholder of the wide char we're overwriting
                            self.set(col + 2, row, StyledChar::new(' '));
                        }
                    }
                }
                // Use a special marker for wide char continuation
                self.set(col + 1, row, StyledChar::new('\0'));
            }

            col += char_width;
        }
    }

    /// Write a single character at position
    pub fn write_char(&mut self, x: u16, y: u16, ch: char, style: &Style) {
        let col = x as usize;
        let row = y as usize;
        let width = self.width as usize;

        if row >= self.height as usize || col >= width {
            return;
        }

        // Mark row as dirty before any modifications
        self.mark_dirty(row);

        let char_width = ch.width().unwrap_or(1);

        // Handle wide character at buffer boundary - skip if it won't fit
        if char_width == 2 && col + 1 >= width {
            // Wide char would extend past buffer, write a space instead
            self.set(col, row, StyledChar::with_style(' ', style));
            return;
        }

        // Check clip region
        if let Some(clip) = self.clip_stack.last()
            && !clip.contains(x, y)
        {
            return;
        }

        // Handle overwriting wide character's second half (placeholder)
        if let Some(cell) = self.get(col, row) {
            if cell.ch == '\0' && col > 0 {
                self.set(col - 1, row, StyledChar::new(' '));
            }
        }

        // Handle overwriting wide character's first half
        if let Some(cell) = self.get(col, row) {
            let old_char_width = cell.ch.width().unwrap_or(1);
            if old_char_width == 2 && col + 1 < width {
                self.set(col + 1, row, StyledChar::new(' '));
            }
        }

        self.set(col, row, StyledChar::with_style(ch, style));

        // For wide characters (width=2), mark the next cell as a placeholder
        if char_width == 2 && col + 1 < width {
            // Handle overwriting the next position's wide char if any
            if let Some(next_cell) = self.get(col + 1, row) {
                let next_char_width = next_cell.ch.width().unwrap_or(1);
                if next_char_width == 2 && col + 2 < width {
                    self.set(col + 2, row, StyledChar::new(' '));
                }
            }
            self.set(col + 1, row, StyledChar::new('\0'));
        }
    }

    /// Fill a rectangle with a character
    pub fn fill_rect(&mut self, x: u16, y: u16, width: u16, height: u16, ch: char, style: &Style) {
        for row in y..(y + height).min(self.height) {
            for col in x..(x + width).min(self.width) {
                self.write_char(col, row, ch, style);
            }
        }
    }

    /// Push a clip region
    pub fn clip(&mut self, region: ClipRegion) {
        assert!(
            region.x1 <= region.x2 && region.y1 <= region.y2,
            "Invalid clip region: min > max"
        );
        self.clip_stack.push(region);
    }

    /// Pop the current clip region
    pub fn unclip(&mut self) {
        assert!(
            self.clip_stack.pop().is_some(),
            "Output::unclip called with an empty clip stack"
        );
    }

    /// Return current clip stack depth.
    ///
    /// A non-zero depth after a render pass usually means clip push/pop calls
    /// are unbalanced in the renderer.
    pub(crate) fn clip_depth(&self) -> usize {
        self.clip_stack.len()
    }

    fn assert_no_active_clips(&self, method: &str) {
        assert!(
            self.clip_stack.is_empty(),
            "Output::{} called with an unbalanced clip stack (depth={})",
            method,
            self.clip_stack.len()
        );
    }

    /// Convert the buffer to a string with ANSI codes
    pub fn render(&self) -> String {
        self.assert_no_active_clips("render");
        let mut lines: Vec<String> = Vec::new();

        for row_idx in 0..self.height as usize {
            // First, find the last non-space, non-placeholder character
            // This determines where meaningful content ends
            let mut last_content_idx = 0;
            for (i, cell) in self.row_iter(row_idx).enumerate() {
                // Consider any non-default-space character as content
                // A space with styling (color, bg, etc) is still content
                if cell.ch != '\0' && (cell.ch != ' ' || cell.has_style()) {
                    last_content_idx = i + 1;
                }
            }

            let mut line = String::new();
            let mut current_style: Option<StyledChar> = None;

            for (i, cell) in self.row_iter(row_idx).enumerate() {
                // Stop at trailing whitespace (unstyled spaces at the end)
                if i >= last_content_idx {
                    break;
                }

                // Skip wide character continuation placeholders
                if cell.ch == '\0' {
                    continue;
                }

                // Check if we need to change style
                let need_style_change = match &current_style {
                    None => cell.has_style(),
                    Some(prev) => !cell.same_style(prev),
                };

                if need_style_change {
                    // Only reset if we had a previous style (not for first styled char)
                    if current_style.is_some() {
                        line.push_str("\x1b[0m");
                    }
                    self.apply_style(&mut line, cell);
                    current_style = Some(cell.clone());
                }

                line.push(cell.ch);
            }

            // Reset at end of line
            if current_style.is_some() {
                line.push_str("\x1b[0m");
            }

            lines.push(line);
        }

        // Remove trailing empty lines
        while lines.last().map(|l| l.is_empty()).unwrap_or(false) {
            lines.pop();
        }

        lines.join("\r\n")
    }

    /// Convert the buffer to a string, preserving all lines (including empty trailing lines)
    ///
    /// This is useful for inline mode rendering where cursor positioning depends on
    /// consistent line counts between frames. Use `render()` for normal rendering
    /// that strips trailing empty lines.
    pub fn render_fixed_height(&self) -> String {
        self.assert_no_active_clips("render_fixed_height");
        let mut lines: Vec<String> = Vec::new();

        for row_idx in 0..self.height as usize {
            let mut last_content_idx = 0;
            for (i, cell) in self.row_iter(row_idx).enumerate() {
                if cell.ch != '\0' && (cell.ch != ' ' || cell.has_style()) {
                    last_content_idx = i + 1;
                }
            }

            let mut line = String::new();
            let mut current_style: Option<StyledChar> = None;

            for (i, cell) in self.row_iter(row_idx).enumerate() {
                if i >= last_content_idx {
                    break;
                }

                if cell.ch == '\0' {
                    continue;
                }

                let need_style_change = match &current_style {
                    None => cell.has_style(),
                    Some(prev) => !cell.same_style(prev),
                };

                if need_style_change {
                    if current_style.is_some() {
                        line.push_str("\x1b[0m");
                    }
                    self.apply_style(&mut line, cell);
                    current_style = Some(cell.clone());
                }

                line.push(cell.ch);
            }

            if current_style.is_some() {
                line.push_str("\x1b[0m");
            }

            lines.push(line);
        }

        // NOTE: Unlike render(), we do NOT strip trailing empty lines here
        // This preserves the exact line count for fixed-height layouts

        lines.join("\r\n")
    }

    fn apply_style(&self, result: &mut String, cell: &StyledChar) {
        let mut codes: Vec<u8> = Vec::new();

        if cell.bold {
            codes.push(1);
        }
        if cell.dim {
            codes.push(2);
        }
        if cell.italic {
            codes.push(3);
        }
        if cell.underline {
            codes.push(4);
        }
        if cell.inverse {
            codes.push(7);
        }
        if cell.strikethrough {
            codes.push(9);
        }

        if let Some(fg) = cell.fg {
            self.color_to_ansi(fg, false, &mut codes);
        }

        if let Some(bg) = cell.bg {
            self.color_to_ansi(bg, true, &mut codes);
        }

        if !codes.is_empty() {
            result.push_str("\x1b[");
            for (i, code) in codes.iter().enumerate() {
                if i > 0 {
                    result.push(';');
                }
                let _ = write!(result, "{}", code);
            }
            result.push('m');
        }
    }

    fn color_to_ansi(&self, color: Color, background: bool, codes: &mut Vec<u8>) {
        let base = if background { 40 } else { 30 };

        match color {
            Color::Reset => {}
            Color::Black => codes.push(base),
            Color::Red => codes.push(base + 1),
            Color::Green => codes.push(base + 2),
            Color::Yellow => codes.push(base + 3),
            Color::Blue => codes.push(base + 4),
            Color::Magenta => codes.push(base + 5),
            Color::Cyan => codes.push(base + 6),
            Color::White => codes.push(base + 7),
            Color::BrightBlack => codes.push(base + 60),
            Color::BrightRed => codes.push(base + 61),
            Color::BrightGreen => codes.push(base + 62),
            Color::BrightYellow => codes.push(base + 63),
            Color::BrightBlue => codes.push(base + 64),
            Color::BrightMagenta => codes.push(base + 65),
            Color::BrightCyan => codes.push(base + 66),
            Color::BrightWhite => codes.push(base + 67),
            Color::Ansi256(n) => {
                codes.push(if background { 48 } else { 38 });
                codes.push(5);
                codes.push(n);
            }
            Color::Rgb(r, g, b) => {
                codes.push(if background { 48 } else { 38 });
                codes.push(2);
                codes.push(r);
                codes.push(g);
                codes.push(b);
            }
        }
    }
}

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

    #[test]
    fn test_output_creation() {
        let output = Output::new(80, 24);
        assert_eq!(output.width, 80);
        assert_eq!(output.height, 24);
    }

    #[test]
    fn test_write_text() {
        let mut output = Output::new(80, 24);
        output.write(0, 0, "Hello", &Style::default());

        assert_eq!(output.cell_at(0, 0).unwrap().ch, 'H');
        assert_eq!(output.cell_at(4, 0).unwrap().ch, 'o');
    }

    #[test]
    fn test_styled_output() {
        let mut output = Output::new(80, 24);
        let mut style = Style::default();
        style.color = Some(Color::Green);
        style.bold = true;

        output.write(0, 0, "Test", &style);

        let rendered = output.render();
        assert!(rendered.contains("\x1b["));
    }

    #[test]
    fn test_wide_char_placeholder() {
        let mut output = Output::new(80, 24);
        output.write(0, 0, "你好", &Style::default());

        // 'ä½ ' at position 0, placeholder at position 1
        assert_eq!(output.cell_at(0, 0).unwrap().ch, 'ä½ ');
        assert_eq!(output.cell_at(1, 0).unwrap().ch, '\0');
        // '好' at position 2, placeholder at position 3
        assert_eq!(output.cell_at(2, 0).unwrap().ch, '好');
        assert_eq!(output.cell_at(3, 0).unwrap().ch, '\0');
    }

    #[test]
    fn test_overwrite_wide_char_placeholder() {
        let mut output = Output::new(80, 24);
        // Write a wide char first
        output.write(0, 0, "ä½ ", &Style::default());
        assert_eq!(output.cell_at(0, 0).unwrap().ch, 'ä½ ');
        assert_eq!(output.cell_at(1, 0).unwrap().ch, '\0');

        // Overwrite the placeholder with a narrow char
        output.write_char(1, 0, 'X', &Style::default());

        // The wide char should be replaced with space (broken)
        assert_eq!(output.cell_at(0, 0).unwrap().ch, ' ');
        assert_eq!(output.cell_at(1, 0).unwrap().ch, 'X');
    }

    #[test]
    fn test_overwrite_wide_char_first_half() {
        let mut output = Output::new(80, 24);
        // Write a wide char first
        output.write(0, 0, "ä½ ", &Style::default());
        assert_eq!(output.cell_at(0, 0).unwrap().ch, 'ä½ ');
        assert_eq!(output.cell_at(1, 0).unwrap().ch, '\0');

        // Overwrite the first half with a narrow char
        output.write_char(0, 0, 'X', &Style::default());

        // The wide char's placeholder should be cleared
        assert_eq!(output.cell_at(0, 0).unwrap().ch, 'X');
        assert_eq!(output.cell_at(1, 0).unwrap().ch, ' ');
    }

    #[test]
    fn test_wide_char_render_no_duplicate() {
        let mut output = Output::new(80, 24);
        output.write(0, 0, "你好世界", &Style::default());

        let rendered = output.render();
        // Should contain exactly these 4 chars, no placeholders visible
        assert_eq!(rendered, "你好世界");
    }

    #[test]
    fn test_raw_mode_line_endings() {
        // Raw mode requires CRLF line endings, not just LF
        let mut output = Output::new(40, 5);
        output.write(0, 0, "Line 1", &Style::default());
        output.write(0, 1, "Line 2", &Style::default());
        output.write(0, 2, "Line 3", &Style::default());

        let rendered = output.render();

        // Must use CRLF for raw mode compatibility
        assert!(
            rendered.contains("\r\n"),
            "Output must use CRLF line endings for raw mode"
        );

        // Count that we don't have standalone LF (without CR before it)
        let lines: Vec<&str> = rendered.split("\r\n").collect();
        assert!(lines.len() >= 3, "Should have at least 3 lines");

        // Verify no standalone LF within lines
        for line in &lines {
            assert!(
                !line.contains('\n'),
                "Should not have standalone LF within lines"
            );
        }
    }

    #[test]
    fn test_line_alignment_in_output() {
        // Test that multi-line output will render with correct alignment
        let mut output = Output::new(20, 3);
        output.write(0, 0, "AAAA", &Style::default());
        output.write(0, 1, "BBBB", &Style::default());
        output.write(0, 2, "CCCC", &Style::default());

        let rendered = output.render();
        let lines: Vec<&str> = rendered.split("\r\n").collect();

        assert_eq!(lines[0], "AAAA");
        assert_eq!(lines[1], "BBBB");
        assert_eq!(lines[2], "CCCC");
    }

    #[test]
    fn test_wide_char_at_boundary() {
        // Wide char at end of buffer should be replaced with space
        let mut output = Output::new(5, 1);
        output.write(3, 0, "ä½ ", &Style::default());

        // Position 3 should be a space, position 4 is at boundary
        assert_eq!(output.cell_at(3, 0).unwrap().ch, 'ä½ ');
        assert_eq!(output.cell_at(4, 0).unwrap().ch, '\0');

        // Now test when wide char would extend past buffer
        let mut output2 = Output::new(5, 1);
        output2.write(4, 0, "ä½ ", &Style::default());

        // Should write a space instead since wide char won't fit
        assert_eq!(output2.cell_at(4, 0).unwrap().ch, ' ');
    }

    #[test]
    fn test_wide_char_at_exact_boundary() {
        // Test when wide char is at the last valid position
        let mut output = Output::new(4, 1);
        output.write(2, 0, "ä½ ", &Style::default());

        // Wide char at position 2-3 should fit exactly
        assert_eq!(output.cell_at(2, 0).unwrap().ch, 'ä½ ');
        assert_eq!(output.cell_at(3, 0).unwrap().ch, '\0');
    }

    #[test]
    fn test_dirty_tracking_initial_state() {
        let output = Output::new(80, 24);
        assert!(!output.is_dirty());
        assert!(!output.is_row_dirty(0));
    }

    #[test]
    fn test_dirty_tracking_after_write() {
        let mut output = Output::new(80, 24);
        output.write(0, 5, "Hello", &Style::default());

        assert!(output.is_dirty());
        assert!(output.is_row_dirty(5));
        assert!(!output.is_row_dirty(0));
        assert!(!output.is_row_dirty(6));
    }

    #[test]
    fn test_dirty_tracking_after_write_char() {
        let mut output = Output::new(80, 24);
        output.write_char(10, 3, 'X', &Style::default());

        assert!(output.is_dirty());
        assert!(output.is_row_dirty(3));
        assert!(!output.is_row_dirty(2));
    }

    #[test]
    fn test_dirty_tracking_clear() {
        let mut output = Output::new(80, 24);
        output.write(0, 0, "Test", &Style::default());
        output.write(0, 5, "Test", &Style::default());

        assert!(output.is_dirty());
        assert!(output.is_row_dirty(0));
        assert!(output.is_row_dirty(5));

        output.clear_dirty();

        assert!(!output.is_dirty());
        assert!(!output.is_row_dirty(0));
        assert!(!output.is_row_dirty(5));
    }

    #[test]
    fn test_dirty_row_indices() {
        let mut output = Output::new(80, 24);
        output.write(0, 1, "A", &Style::default());
        output.write(0, 3, "B", &Style::default());
        output.write(0, 7, "C", &Style::default());

        let dirty: Vec<usize> = output.dirty_row_indices().collect();
        assert_eq!(dirty, vec![1, 3, 7]);
    }

    #[test]
    fn test_render_dirty_rows() {
        let mut output = Output::new(80, 24);
        output.write(0, 0, "Line 0", &Style::default());
        output.write(0, 2, "Line 2", &Style::default());

        let dirty_rows = output.render_dirty_rows();
        assert_eq!(dirty_rows.len(), 2);
        assert_eq!(dirty_rows[0].0, 0);
        assert_eq!(dirty_rows[0].1, "Line 0");
        assert_eq!(dirty_rows[1].0, 2);
        assert_eq!(dirty_rows[1].1, "Line 2");
    }

    #[test]
    #[cfg(debug_assertions)]
    #[should_panic(expected = "Output::unclip called with an empty clip stack")]
    fn test_unclip_panics_when_stack_is_empty_in_debug() {
        let mut output = Output::new(10, 5);
        output.unclip();
    }

    #[test]
    fn test_clip_depth_tracks_push_and_pop() {
        let mut output = Output::new(10, 5);
        assert_eq!(output.clip_depth(), 0);

        output.clip(ClipRegion {
            x1: 0,
            y1: 0,
            x2: 5,
            y2: 5,
        });
        assert_eq!(output.clip_depth(), 1);

        output.unclip();
        assert_eq!(output.clip_depth(), 0);
    }

    #[test]
    #[should_panic(expected = "Output::render called with an unbalanced clip stack")]
    fn test_render_panics_with_active_clip_stack() {
        let mut output = Output::new(10, 5);
        output.clip(ClipRegion {
            x1: 0,
            y1: 0,
            x2: 5,
            y2: 5,
        });
        let _ = output.render();
    }
}