standout-render 7.1.0

Styled terminal rendering with templates, themes, and adaptive color support
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
//! Utility functions for ANSI-aware text measurement, truncation, and padding.
//!
//! All functions in this module correctly handle ANSI escape codes: they are
//! preserved in output but don't count toward display width calculations.

use console::{measure_text_width, pad_str, Alignment};
use standout_bbparser::strip_tags;

/// Returns the display width of a string, ignoring ANSI escape codes.
///
/// **Warning:** This only strips ANSI escape codes, not BBCode tags like
/// `[bold]...[/bold]`. For user-facing content that may contain BBCode markup,
/// use [`visible_width`] instead.
///
/// # Example
///
/// ```rust
/// use standout_render::tabular::display_width;
///
/// assert_eq!(display_width("hello"), 5);
/// assert_eq!(display_width("\x1b[31mred\x1b[0m"), 3);  // ANSI codes ignored
/// assert_eq!(display_width("日本"), 4);  // CJK characters are 2 columns each
/// ```
pub fn display_width(s: &str) -> usize {
    measure_text_width(s)
}

/// Returns the visible display width of a string, stripping both BBCode tags
/// and ANSI escape codes before measurement.
///
/// Use this for any text that may contain markup. For strings known to be
/// tag-free (e.g., separator literals), [`display_width`] avoids the overhead.
///
/// # Example
///
/// ```rust
/// use standout_render::tabular::visible_width;
///
/// assert_eq!(visible_width("hello"), 5);
/// assert_eq!(visible_width("[bold]hello[/bold]"), 5);
/// assert_eq!(visible_width("\x1b[31m[red]hi[/red]\x1b[0m"), 2);
/// ```
pub fn visible_width(s: &str) -> usize {
    display_width(&strip_tags(s))
}

/// Truncates a string from the end to fit within a maximum display width.
///
/// If the string already fits, it is returned unchanged. Otherwise, characters
/// are removed from the end and the ellipsis is appended.
///
/// ANSI escape codes are preserved but don't count toward display width.
///
/// # Arguments
///
/// * `s` - The string to truncate
/// * `max_width` - Maximum display width in terminal columns
/// * `ellipsis` - String to append when truncation occurs (e.g., "…" or "...")
///
/// # Example
///
/// ```rust
/// use standout_render::tabular::truncate_end;
///
/// assert_eq!(truncate_end("Hello World", 8, "…"), "Hello W…");
/// assert_eq!(truncate_end("Short", 10, "…"), "Short");
/// ```
pub fn truncate_end(s: &str, max_width: usize, ellipsis: &str) -> String {
    let width = measure_text_width(s);
    if width <= max_width {
        return s.to_string();
    }

    let ellipsis_width = measure_text_width(ellipsis);
    if max_width < ellipsis_width {
        // Not enough room even for ellipsis - truncate ellipsis itself
        return truncate_to_display_width(ellipsis, max_width);
    }
    if max_width == ellipsis_width {
        // Exactly enough room for ellipsis only
        return ellipsis.to_string();
    }

    let target_width = max_width - ellipsis_width;
    let mut result = truncate_to_display_width(s, target_width);
    result.push_str(ellipsis);
    result
}

/// Truncates a string from the start to fit within a maximum display width.
///
/// Characters are removed from the beginning, and the ellipsis is prepended.
/// Useful for paths where the filename at the end is more important than
/// the directory prefix.
///
/// ANSI escape codes are preserved but don't count toward display width.
///
/// # Example
///
/// ```rust
/// use standout_render::tabular::truncate_start;
///
/// assert_eq!(truncate_start("Hello World", 8, "…"), "…o World");
/// assert_eq!(truncate_start("/path/to/file.rs", 12, "…"), "…/to/file.rs");
/// ```
pub fn truncate_start(s: &str, max_width: usize, ellipsis: &str) -> String {
    let width = measure_text_width(s);
    if width <= max_width {
        return s.to_string();
    }

    let ellipsis_width = measure_text_width(ellipsis);
    if max_width < ellipsis_width {
        // Not enough room even for ellipsis - truncate ellipsis itself
        return truncate_to_display_width(ellipsis, max_width);
    }
    if max_width == ellipsis_width {
        // Exactly enough room for ellipsis only
        return ellipsis.to_string();
    }

    let target_width = max_width - ellipsis_width;
    let truncated = find_suffix_with_width(s, target_width);
    format!("{}{}", ellipsis, truncated)
}

/// Truncates a string from the middle to fit within a maximum display width.
///
/// Characters are removed from the middle, preserving both start and end.
/// The ellipsis is placed in the middle. Useful for identifiers or filenames
/// where both prefix and suffix are meaningful.
///
/// ANSI escape codes are preserved but don't count toward display width.
///
/// # Example
///
/// ```rust
/// use standout_render::tabular::truncate_middle;
///
/// assert_eq!(truncate_middle("Hello World", 8, "…"), "Hel…orld");
/// assert_eq!(truncate_middle("abcdefghij", 7, "..."), "ab...ij");
/// ```
pub fn truncate_middle(s: &str, max_width: usize, ellipsis: &str) -> String {
    let width = measure_text_width(s);
    if width <= max_width {
        return s.to_string();
    }

    let ellipsis_width = measure_text_width(ellipsis);
    if max_width < ellipsis_width {
        // Not enough room even for ellipsis - truncate ellipsis itself
        return truncate_to_display_width(ellipsis, max_width);
    }
    if max_width == ellipsis_width {
        // Exactly enough room for ellipsis only
        return ellipsis.to_string();
    }

    let available = max_width - ellipsis_width;
    let right_width = available.div_ceil(2); // Bias toward end (more useful info usually)
    let left_width = available - right_width;

    let left = truncate_to_display_width(s, left_width);
    let right = find_suffix_with_width(s, right_width);

    format!("{}{}{}", left, ellipsis, right)
}

/// Pads a string on the left (right-aligns) to reach the target width.
///
/// ANSI escape codes are preserved and don't count toward width calculations.
///
/// **Warning:** This does not strip BBCode tags—they will be counted toward
/// the display width. For tagged content, compute padding manually using
/// [`visible_width`] and `" ".repeat(padding)`.
///
/// # Example
///
/// ```rust
/// use standout_render::tabular::pad_left;
///
/// assert_eq!(pad_left("42", 5), "   42");
/// assert_eq!(pad_left("hello", 3), "hello");  // No truncation
/// ```
pub fn pad_left(s: &str, width: usize) -> String {
    pad_str(s, width, Alignment::Right, None).into_owned()
}

/// Pads a string on the right (left-aligns) to reach the target width.
///
/// ANSI escape codes are preserved and don't count toward width calculations.
///
/// **Warning:** This does not strip BBCode tags—they will be counted toward
/// the display width. For tagged content, compute padding manually using
/// [`visible_width`] and `" ".repeat(padding)`.
///
/// # Example
///
/// ```rust
/// use standout_render::tabular::pad_right;
///
/// assert_eq!(pad_right("42", 5), "42   ");
/// assert_eq!(pad_right("hello", 3), "hello");  // No truncation
/// ```
pub fn pad_right(s: &str, width: usize) -> String {
    pad_str(s, width, Alignment::Left, None).into_owned()
}

/// Pads a string on both sides (centers) to reach the target width.
///
/// When the remaining space is odd, the extra space goes on the right.
/// ANSI escape codes are preserved and don't count toward width calculations.
///
/// **Warning:** This does not strip BBCode tags—they will be counted toward
/// the display width. For tagged content, compute padding manually using
/// [`visible_width`] and `" ".repeat(padding)`.
///
/// # Example
///
/// ```rust
/// use standout_render::tabular::pad_center;
///
/// assert_eq!(pad_center("hi", 6), "  hi  ");
/// assert_eq!(pad_center("hi", 5), " hi  ");  // Extra space on right
/// ```
pub fn pad_center(s: &str, width: usize) -> String {
    pad_str(s, width, Alignment::Center, None).into_owned()
}

/// Wraps text to fit within a maximum display width, breaking at word boundaries.
///
/// Returns a vector of lines, each fitting within the specified width.
/// Words longer than the width are force-broken to fit.
///
/// ANSI escape codes are preserved and don't count toward width calculations.
///
/// # Arguments
///
/// * `s` - The string to wrap
/// * `width` - Maximum display width for each line
///
/// # Example
///
/// ```rust
/// use standout_render::tabular::wrap;
///
/// let lines = wrap("hello world foo", 11);
/// assert_eq!(lines, vec!["hello world", "foo"]);
///
/// let lines = wrap("short", 20);
/// assert_eq!(lines, vec!["short"]);
///
/// // Long words are force-broken with ellipsis markers
/// let lines = wrap("supercalifragilistic", 10);
/// assert!(lines.len() >= 2);
/// for line in &lines {
///     assert!(standout_render::tabular::display_width(line) <= 10);
/// }
/// ```
pub fn wrap(s: &str, width: usize) -> Vec<String> {
    wrap_indent(s, width, 0)
}

/// Wraps text with a continuation indent on subsequent lines.
///
/// The first line uses the full width. Subsequent lines are indented by the
/// specified amount, reducing their effective width.
///
/// ANSI escape codes are preserved and don't count toward width calculations.
///
/// # Arguments
///
/// * `s` - The string to wrap
/// * `width` - Maximum display width for each line
/// * `indent` - Number of spaces to indent continuation lines
///
/// # Example
///
/// ```rust
/// use standout_render::tabular::wrap_indent;
///
/// let lines = wrap_indent("hello world foo bar", 12, 2);
/// assert_eq!(lines, vec!["hello world", "  foo bar"]);
/// ```
pub fn wrap_indent(s: &str, width: usize, indent: usize) -> Vec<String> {
    if width == 0 {
        return vec![];
    }

    let s = s.trim();
    if s.is_empty() {
        return vec![];
    }

    // If the whole string fits, return it directly
    if measure_text_width(s) <= width {
        return vec![s.to_string()];
    }

    let mut lines = Vec::new();
    let mut current_line = String::new();
    let mut current_width = 0;
    let mut is_first_line = true;

    // Split on whitespace, preserving the structure
    for word in s.split_whitespace() {
        let word_width = measure_text_width(word);
        let effective_width = if is_first_line {
            width
        } else {
            width.saturating_sub(indent)
        };

        // Handle words longer than available width
        if word_width > effective_width {
            // Finish current line if it has content
            if !current_line.is_empty() {
                lines.push(current_line);
                current_line = String::new();
                current_width = 0;
                is_first_line = false;
            }

            // Force-break the long word
            let broken = break_long_word(word, effective_width, indent, is_first_line);
            let broken_len = broken.len();
            for (i, part) in broken.into_iter().enumerate() {
                if i == 0 && is_first_line {
                    lines.push(part);
                    is_first_line = false;
                } else if i < broken_len - 1 {
                    // Not the last part - push as complete line
                    lines.push(part);
                } else {
                    // Last part - becomes the start of the next line
                    current_line = part;
                    current_width = measure_text_width(&current_line);
                }
            }
            continue;
        }

        // Check if word fits on current line
        let needed_width = if current_line.is_empty() {
            word_width
        } else {
            current_width + 1 + word_width // +1 for space
        };

        if needed_width <= effective_width {
            // Word fits - add to current line
            if !current_line.is_empty() {
                current_line.push(' ');
                current_width += 1;
            }
            current_line.push_str(word);
            current_width += word_width;
        } else {
            // Word doesn't fit - start new line
            if !current_line.is_empty() {
                lines.push(current_line);
            }
            is_first_line = false;

            // Start new line with indent
            let indent_str: String = " ".repeat(indent);
            current_line = format!("{}{}", indent_str, word);
            current_width = indent + word_width;
        }
    }

    // Don't forget the last line
    if !current_line.is_empty() {
        lines.push(current_line);
    }

    // Handle edge case where we produced no lines (shouldn't happen with non-empty input)
    if lines.is_empty() && !s.is_empty() {
        lines.push(truncate_to_display_width(s, width));
    }

    lines
}

/// Break a word that's longer than the available width into multiple parts.
fn break_long_word(word: &str, width: usize, indent: usize, is_first: bool) -> Vec<String> {
    let mut parts = Vec::new();
    let mut remaining = word;
    let mut first_part = is_first;

    while !remaining.is_empty() {
        let effective_width = if first_part {
            width
        } else {
            width.saturating_sub(indent)
        };

        if effective_width == 0 {
            // Can't fit anything - just return what we have
            break;
        }

        let remaining_width = measure_text_width(remaining);
        if remaining_width <= effective_width {
            // Rest fits
            let prefix = if first_part {
                String::new()
            } else {
                " ".repeat(indent)
            };
            parts.push(format!("{}{}", prefix, remaining));
            break;
        }

        // Need to break - leave room for ellipsis to indicate continuation
        let break_width = effective_width.saturating_sub(1); // -1 for "…"
        if break_width == 0 {
            // Not enough room even for one char + ellipsis
            let prefix = if first_part {
                String::new()
            } else {
                " ".repeat(indent)
            };
            parts.push(format!("{}", prefix));
            break;
        }

        let prefix = if first_part {
            String::new()
        } else {
            " ".repeat(indent)
        };
        let truncated = truncate_to_display_width(remaining, break_width);
        parts.push(format!("{}{}", prefix, truncated));

        // Find where we actually cut in the original string
        let truncated_len = truncated.chars().count();
        remaining = &remaining[remaining
            .char_indices()
            .nth(truncated_len)
            .map(|(i, _)| i)
            .unwrap_or(remaining.len())..];
        first_part = false;
    }

    parts
}

// --- Internal helpers ---

/// Truncate string to fit display width, keeping characters from the start.
/// Handles ANSI escape codes properly.
fn truncate_to_display_width(s: &str, max_width: usize) -> String {
    if max_width == 0 {
        return String::new();
    }

    // Fast path: if string fits, return as-is
    if measure_text_width(s) <= max_width {
        return s.to_string();
    }

    // We need to walk through the string carefully, tracking both
    // printable width and ANSI escape sequences
    let mut result = String::new();
    let mut current_width = 0;
    let chars = s.chars().peekable();
    let mut in_escape = false;

    for c in chars {
        if c == '\x1b' {
            // Start of ANSI escape sequence - include it all
            result.push(c);
            in_escape = true;
            continue;
        }

        if in_escape {
            result.push(c);
            // ANSI CSI sequences end with a letter (@ through ~)
            if c.is_ascii_alphabetic() || c == '~' {
                in_escape = false;
            }
            continue;
        }

        // Regular character - check width
        let char_width = unicode_width::UnicodeWidthChar::width(c).unwrap_or(0);
        if current_width + char_width > max_width {
            break;
        }
        result.push(c);
        current_width += char_width;
    }

    result
}

/// Find the longest suffix of s that has display width <= max_width.
fn find_suffix_with_width(s: &str, max_width: usize) -> String {
    if max_width == 0 {
        return String::new();
    }

    let total_width = measure_text_width(s);
    if total_width <= max_width {
        return s.to_string();
    }

    // Linear scan from the start to find where to cut.
    // We need to skip (total_width - max_width) display columns.
    let skip_width = total_width - max_width;

    let mut current_width = 0;
    let mut byte_offset = 0;
    let mut in_escape = false;

    for (i, c) in s.char_indices() {
        if c == '\x1b' {
            in_escape = true;
            byte_offset = i + c.len_utf8();
            continue;
        }

        if in_escape {
            byte_offset = i + c.len_utf8();
            if c.is_ascii_alphabetic() || c == '~' {
                in_escape = false;
            }
            continue;
        }

        let char_width = unicode_width::UnicodeWidthChar::width(c).unwrap_or(0);
        current_width += char_width;
        byte_offset = i + c.len_utf8();

        if current_width >= skip_width {
            break;
        }
    }

    s[byte_offset..].to_string()
}

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

    // --- display_width tests ---

    #[test]
    fn display_width_ascii() {
        assert_eq!(display_width("hello"), 5);
        assert_eq!(display_width(""), 0);
        assert_eq!(display_width(" "), 1);
    }

    #[test]
    fn display_width_ansi() {
        assert_eq!(display_width("\x1b[31mred\x1b[0m"), 3);
        assert_eq!(display_width("\x1b[1;32mbold green\x1b[0m"), 10);
        assert_eq!(display_width("\x1b[38;5;196mcolor\x1b[0m"), 5);
    }

    #[test]
    fn display_width_unicode() {
        assert_eq!(display_width("日本語"), 6); // 3 chars, 2 columns each
        assert_eq!(display_width("café"), 4);
        assert_eq!(display_width("🎉"), 2); // Emoji typically 2 columns
    }

    // --- truncate_end tests ---

    #[test]
    fn truncate_end_no_truncation() {
        assert_eq!(truncate_end("hello", 10, ""), "hello");
        assert_eq!(truncate_end("hello", 5, ""), "hello");
    }

    #[test]
    fn truncate_end_basic() {
        assert_eq!(truncate_end("hello world", 8, ""), "hello w…");
        assert_eq!(truncate_end("hello world", 6, ""), "hello…");
    }

    #[test]
    fn truncate_end_multi_char_ellipsis() {
        assert_eq!(truncate_end("hello world", 8, "..."), "hello...");
    }

    #[test]
    fn truncate_end_exact_fit() {
        assert_eq!(truncate_end("hello", 5, ""), "hello");
    }

    #[test]
    fn truncate_end_tiny_width() {
        assert_eq!(truncate_end("hello", 1, ""), "");
        assert_eq!(truncate_end("hello", 0, ""), "");
    }

    #[test]
    fn truncate_end_ansi() {
        let styled = "\x1b[31mhello world\x1b[0m";
        let result = truncate_end(styled, 8, "");
        assert_eq!(display_width(&result), 8);
        assert!(result.contains("\x1b[31m")); // ANSI preserved
    }

    #[test]
    fn truncate_end_cjk() {
        assert_eq!(truncate_end("日本語テスト", 7, ""), "日本語…"); // 3 chars (6 cols) + ellipsis
    }

    // --- truncate_start tests ---

    #[test]
    fn truncate_start_no_truncation() {
        assert_eq!(truncate_start("hello", 10, ""), "hello");
    }

    #[test]
    fn truncate_start_basic() {
        assert_eq!(truncate_start("hello world", 8, ""), "…o world");
    }

    #[test]
    fn truncate_start_path() {
        assert_eq!(truncate_start("/path/to/file.rs", 12, ""), "…/to/file.rs");
    }

    #[test]
    fn truncate_start_tiny_width() {
        assert_eq!(truncate_start("hello", 1, ""), "");
        assert_eq!(truncate_start("hello", 0, ""), "");
    }

    // --- truncate_middle tests ---

    #[test]
    fn truncate_middle_no_truncation() {
        assert_eq!(truncate_middle("hello", 10, ""), "hello");
    }

    #[test]
    fn truncate_middle_basic() {
        assert_eq!(truncate_middle("hello world", 8, ""), "hel…orld");
    }

    #[test]
    fn truncate_middle_multi_char_ellipsis() {
        assert_eq!(truncate_middle("abcdefghij", 7, "..."), "ab...ij");
    }

    #[test]
    fn truncate_middle_tiny_width() {
        assert_eq!(truncate_middle("hello", 1, ""), "");
        assert_eq!(truncate_middle("hello", 0, ""), "");
    }

    #[test]
    fn truncate_middle_even_split() {
        // 10 chars, max 6, ellipsis 1 = 5 available, split 2/3 (bias toward end)
        assert_eq!(truncate_middle("abcdefghij", 6, ""), "ab…hij");
    }

    // --- pad_left tests ---

    #[test]
    fn pad_left_basic() {
        assert_eq!(pad_left("42", 5), "   42");
        assert_eq!(pad_left("hello", 10), "     hello");
    }

    #[test]
    fn pad_left_no_padding_needed() {
        assert_eq!(pad_left("hello", 5), "hello");
        assert_eq!(pad_left("hello", 3), "hello"); // No truncation
    }

    #[test]
    fn pad_left_empty() {
        assert_eq!(pad_left("", 5), "     ");
    }

    #[test]
    fn pad_left_ansi() {
        let styled = "\x1b[31mhi\x1b[0m";
        let result = pad_left(styled, 5);
        assert!(result.ends_with("\x1b[0m"));
        assert_eq!(display_width(&result), 5);
    }

    // --- pad_right tests ---

    #[test]
    fn pad_right_basic() {
        assert_eq!(pad_right("42", 5), "42   ");
        assert_eq!(pad_right("hello", 10), "hello     ");
    }

    #[test]
    fn pad_right_no_padding_needed() {
        assert_eq!(pad_right("hello", 5), "hello");
        assert_eq!(pad_right("hello", 3), "hello");
    }

    #[test]
    fn pad_right_empty() {
        assert_eq!(pad_right("", 5), "     ");
    }

    // --- pad_center tests ---

    #[test]
    fn pad_center_basic() {
        assert_eq!(pad_center("hi", 6), "  hi  ");
    }

    #[test]
    fn pad_center_odd_space() {
        assert_eq!(pad_center("hi", 5), " hi  "); // Extra space on right
    }

    #[test]
    fn pad_center_no_padding() {
        assert_eq!(pad_center("hello", 5), "hello");
        assert_eq!(pad_center("hello", 3), "hello");
    }

    #[test]
    fn pad_center_empty() {
        assert_eq!(pad_center("", 4), "    ");
    }

    // --- Edge cases ---

    #[test]
    fn empty_string_operations() {
        assert_eq!(display_width(""), 0);
        assert_eq!(truncate_end("", 5, ""), "");
        assert_eq!(truncate_start("", 5, ""), "");
        assert_eq!(truncate_middle("", 5, ""), "");
        assert_eq!(pad_left("", 0), "");
        assert_eq!(pad_right("", 0), "");
    }

    #[test]
    fn zero_width_target() {
        assert_eq!(truncate_end("hello", 0, ""), "");
        assert_eq!(truncate_start("hello", 0, ""), "");
        assert_eq!(truncate_middle("hello", 0, ""), "");
    }

    // --- wrap tests ---

    #[test]
    fn wrap_single_line_fits() {
        assert_eq!(wrap("hello world", 20), vec!["hello world"]);
        assert_eq!(wrap("short", 10), vec!["short"]);
    }

    #[test]
    fn wrap_basic_multiline() {
        assert_eq!(wrap("hello world foo", 11), vec!["hello world", "foo"]);
        assert_eq!(
            wrap("one two three four", 10),
            vec!["one two", "three four"]
        );
    }

    #[test]
    fn wrap_exact_fit() {
        assert_eq!(wrap("hello", 5), vec!["hello"]);
        assert_eq!(wrap("hello world", 11), vec!["hello world"]);
    }

    #[test]
    fn wrap_empty_string() {
        let result: Vec<String> = wrap("", 10);
        assert!(result.is_empty());
    }

    #[test]
    fn wrap_whitespace_only() {
        let result: Vec<String> = wrap("   ", 10);
        assert!(result.is_empty());
    }

    #[test]
    fn wrap_zero_width() {
        let result: Vec<String> = wrap("hello", 0);
        assert!(result.is_empty());
    }

    #[test]
    fn wrap_single_word_per_line() {
        assert_eq!(wrap("a b c d", 1), vec!["a", "b", "c", "d"]);
    }

    #[test]
    fn wrap_long_word_force_break() {
        // "supercalifragilistic" is 20 chars, width 10
        // With ellipsis breaks: "supercali…" (10), "fragilis…" (10), "tic" (3)
        let result = wrap("supercalifragilistic", 10);
        assert!(result.len() >= 2, "should produce multiple lines");
        for line in &result {
            assert!(display_width(line) <= 10, "line '{}' exceeds width", line);
        }
    }

    #[test]
    fn wrap_preserves_word_boundaries() {
        let result = wrap("hello world test", 10);
        // Should not break "hello" or "world" in the middle
        assert_eq!(result[0], "hello");
        assert_eq!(result[1], "world test");
    }

    #[test]
    fn wrap_multiple_spaces_normalized_when_wrapping() {
        // When wrapping occurs, multiple spaces between words get normalized
        // because we split_whitespace and rejoin with single spaces
        let result = wrap("hello    world    foo", 12);
        // "hello world" (11) fits, "foo" goes to next line
        assert_eq!(result, vec!["hello world", "foo"]);
    }

    // --- wrap_indent tests ---

    #[test]
    fn wrap_indent_basic() {
        let result = wrap_indent("hello world foo bar", 12, 2);
        assert_eq!(result.len(), 2);
        assert_eq!(result[0], "hello world");
        assert!(result[1].starts_with("  ")); // 2-space indent
    }

    #[test]
    fn wrap_indent_no_wrap_needed() {
        assert_eq!(wrap_indent("short", 20, 4), vec!["short"]);
    }

    #[test]
    fn wrap_indent_multiple_lines() {
        let result = wrap_indent("one two three four five six", 10, 2);
        // First line: no indent, up to 10 chars
        // Subsequent: 2-char indent, effective width 8
        assert!(!result[0].starts_with(' '));
        for line in result.iter().skip(1) {
            assert!(line.starts_with("  "), "continuation should be indented");
        }
    }

    #[test]
    fn wrap_indent_zero_indent() {
        // Same as regular wrap
        let result = wrap_indent("hello world foo", 11, 0);
        assert_eq!(result, vec!["hello world", "foo"]);
    }

    #[test]
    fn wrap_cjk_characters() {
        // CJK characters are 2 columns each
        // "日本語" is 6 columns
        let result = wrap("日本語 テスト", 8);
        assert_eq!(result.len(), 2);
        for line in &result {
            assert!(display_width(line) <= 8);
        }
    }
}

#[cfg(test)]
mod proptests {
    use super::*;
    use proptest::prelude::*;

    proptest! {
        #[test]
        fn truncate_end_respects_max_width(
            s in "[a-zA-Z0-9 ]{0,100}",
            max_width in 0usize..50,
        ) {
            let result = truncate_end(&s, max_width, "");
            let result_width = display_width(&result);
            prop_assert!(
                result_width <= max_width,
                "truncate_end exceeded max_width: result '{}' has width {}, max was {}",
                result, result_width, max_width
            );
        }

        #[test]
        fn truncate_start_respects_max_width(
            s in "[a-zA-Z0-9 ]{0,100}",
            max_width in 0usize..50,
        ) {
            let result = truncate_start(&s, max_width, "");
            let result_width = display_width(&result);
            prop_assert!(
                result_width <= max_width,
                "truncate_start exceeded max_width: result '{}' has width {}, max was {}",
                result, result_width, max_width
            );
        }

        #[test]
        fn truncate_middle_respects_max_width(
            s in "[a-zA-Z0-9 ]{0,100}",
            max_width in 0usize..50,
        ) {
            let result = truncate_middle(&s, max_width, "");
            let result_width = display_width(&result);
            prop_assert!(
                result_width <= max_width,
                "truncate_middle exceeded max_width: result '{}' has width {}, max was {}",
                result, result_width, max_width
            );
        }

        #[test]
        fn truncate_preserves_short_strings(
            s in "[a-zA-Z0-9]{0,20}",
            extra_width in 0usize..30,
        ) {
            let width = display_width(&s);
            let max_width = width + extra_width;

            // If string fits, it should be unchanged
            prop_assert_eq!(truncate_end(&s, max_width, ""), s.clone());
            prop_assert_eq!(truncate_start(&s, max_width, ""), s.clone());
            prop_assert_eq!(truncate_middle(&s, max_width, ""), s);
        }

        #[test]
        fn pad_produces_exact_width_when_larger(
            s in "[a-zA-Z0-9]{0,20}",
            extra in 1usize..30,
        ) {
            let original_width = display_width(&s);
            let target_width = original_width + extra;

            prop_assert_eq!(display_width(&pad_left(&s, target_width)), target_width);
            prop_assert_eq!(display_width(&pad_right(&s, target_width)), target_width);
            prop_assert_eq!(display_width(&pad_center(&s, target_width)), target_width);
        }

        #[test]
        fn pad_preserves_content_when_smaller(
            s in "[a-zA-Z0-9]{1,30}",
        ) {
            let original_width = display_width(&s);
            let target_width = original_width.saturating_sub(5);

            // When target is smaller, string should be unchanged
            prop_assert_eq!(pad_left(&s, target_width), s.clone());
            prop_assert_eq!(pad_right(&s, target_width), s.clone());
            prop_assert_eq!(pad_center(&s, target_width), s);
        }

        #[test]
        fn truncate_end_contains_ellipsis_when_truncated(
            s in "[a-zA-Z0-9]{10,50}",
            max_width in 3usize..9,
        ) {
            let result = truncate_end(&s, max_width, "");
            if display_width(&s) > max_width {
                prop_assert!(
                    result.contains(""),
                    "truncated string should contain ellipsis"
                );
            }
        }

        #[test]
        fn truncate_start_contains_ellipsis_when_truncated(
            s in "[a-zA-Z0-9]{10,50}",
            max_width in 3usize..9,
        ) {
            let result = truncate_start(&s, max_width, "");
            if display_width(&s) > max_width {
                prop_assert!(
                    result.contains(""),
                    "truncated string should contain ellipsis"
                );
            }
        }

        #[test]
        fn truncate_middle_contains_ellipsis_when_truncated(
            s in "[a-zA-Z0-9]{10,50}",
            max_width in 3usize..9,
        ) {
            let result = truncate_middle(&s, max_width, "");
            if display_width(&s) > max_width {
                prop_assert!(
                    result.contains(""),
                    "truncated string should contain ellipsis"
                );
            }
        }

        #[test]
        fn wrap_all_lines_respect_width(
            s in "[a-zA-Z]{1,10}( [a-zA-Z]{1,10}){0,10}",
            width in 5usize..30,
        ) {
            let lines = wrap(&s, width);
            for line in &lines {
                let line_width = display_width(line);
                prop_assert!(
                    line_width <= width,
                    "wrap produced line '{}' with width {}, max was {}",
                    line, line_width, width
                );
            }
        }

        #[test]
        fn wrap_preserves_all_words(
            words in prop::collection::vec("[a-zA-Z]{1,8}", 1..10),
            width in 10usize..40,
        ) {
            let input = words.join(" ");
            let lines = wrap(&input, width);
            let rejoined = lines.join(" ");

            // All original words should appear in the output
            for word in &words {
                prop_assert!(
                    rejoined.contains(word),
                    "word '{}' missing from wrapped output",
                    word
                );
            }
        }

        #[test]
        fn wrap_indent_continuation_lines_are_indented(
            s in "[a-zA-Z]{1,5}( [a-zA-Z]{1,5}){3,8}",
            width in 10usize..20,
            indent in 1usize..4,
        ) {
            let lines = wrap_indent(&s, width, indent);
            if lines.len() > 1 {
                let indent_str: String = " ".repeat(indent);
                for line in lines.iter().skip(1) {
                    prop_assert!(
                        line.starts_with(&indent_str),
                        "continuation line '{}' should start with {} spaces",
                        line, indent
                    );
                }
            }
        }

        #[test]
        fn wrap_nonempty_input_produces_nonempty_output(
            s in "[a-zA-Z]{1,20}",
            width in 1usize..30,
        ) {
            let lines = wrap(&s, width);
            prop_assert!(
                !lines.is_empty(),
                "non-empty input '{}' should produce non-empty output",
                s
            );
        }
    }
}