rich-rs 1.2.2

Rich text and beautiful formatting for the terminal
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
//! Segment: the atomic unit of terminal output.
//!
//! Everything in Rich ultimately becomes a sequence of Segments.

use smallvec::SmallVec;
use std::borrow::Cow;

use crate::cells::{cell_len, char_width, set_cell_size};
use crate::style::{Style, StyleMeta};
use std::sync::Arc;

/// Control codes that can be embedded in output.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ControlType {
    /// Ring the terminal bell.
    Bell,
    /// Carriage return.
    CarriageReturn,
    /// Move cursor to home position.
    Home,
    /// Clear the screen.
    Clear,
    /// Show the cursor.
    ShowCursor,
    /// Hide the cursor.
    HideCursor,
    /// Enable alternate screen buffer.
    EnableAltScreen,
    /// Disable alternate screen buffer.
    DisableAltScreen,
    /// Set window title.
    SetTitle,
    /// Move cursor up N lines.
    CursorUp(u16),
    /// Move cursor down N lines.
    CursorDown(u16),
    /// Move cursor forward N columns.
    CursorForward(u16),
    /// Move cursor backward N columns.
    CursorBackward(u16),
    /// Erase in line (0=cursor to end, 1=start to cursor, 2=entire line).
    EraseInLine(u8),
    /// Start an OSC 8 hyperlink.
    HyperlinkStart { url: Arc<str>, id: Option<Arc<str>> },
    /// End an OSC 8 hyperlink.
    HyperlinkEnd,
    /// Move the cursor to an absolute position (x, y), 0-based.
    MoveTo { x: u16, y: u16 },
}

/// A segment of text with optional style and control codes.
///
/// This is the fundamental unit of output in Rich. All renderables
/// produce sequences of Segments.
///
/// Uses `Cow<'static, str>` for text to allow both owned and static strings
/// without lifetime complexity in the API. This is a deliberate tradeoff
/// favoring API simplicity over zero-copy for borrowed non-static input.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Segment {
    /// The text content.
    pub text: Cow<'static, str>,
    /// Optional style to apply.
    pub style: Option<Style>,
    /// Optional style metadata (hyperlinks, Textual handlers, etc.).
    pub meta: Option<StyleMeta>,
    /// Optional control code (if set, text is typically empty).
    pub control: Option<ControlType>,
}

impl Segment {
    /// Create a new text segment.
    pub fn new(text: impl Into<Cow<'static, str>>) -> Self {
        Segment {
            text: text.into(),
            style: None,
            meta: None,
            control: None,
        }
    }

    /// Create a new styled segment.
    pub fn styled(text: impl Into<Cow<'static, str>>, style: Style) -> Self {
        Segment {
            text: text.into(),
            style: Some(style),
            meta: None,
            control: None,
        }
    }

    /// Create a new styled segment with metadata.
    pub fn styled_with_meta(
        text: impl Into<Cow<'static, str>>,
        style: Style,
        meta: StyleMeta,
    ) -> Self {
        Segment {
            text: text.into(),
            style: Some(style),
            meta: if meta.is_empty() { None } else { Some(meta) },
            control: None,
        }
    }

    /// Create a new segment with metadata and no style.
    pub fn new_with_meta(text: impl Into<Cow<'static, str>>, meta: StyleMeta) -> Self {
        Segment {
            text: text.into(),
            style: None,
            meta: if meta.is_empty() { None } else { Some(meta) },
            control: None,
        }
    }

    /// Create a control segment.
    pub fn control(control: ControlType) -> Self {
        Segment {
            text: Cow::Borrowed(""),
            style: None,
            meta: None,
            control: Some(control),
        }
    }

    /// Create a newline segment.
    pub fn line() -> Self {
        Segment::new("\n")
    }

    /// Check if this segment is a control segment.
    pub fn is_control(&self) -> bool {
        self.control.is_some()
    }

    /// Get the cell width of this segment's text.
    pub fn cell_len(&self) -> usize {
        crate::cells::cell_len(&self.text)
    }

    /// Apply a style to this segment, combining with any existing style.
    pub fn apply_style(&self, style: &Style) -> Self {
        Segment {
            text: self.text.clone(),
            style: Some(match &self.style {
                Some(existing) => existing.combine(style),
                None => *style,
            }),
            meta: self.meta.clone(),
            control: self.control.clone(),
        }
    }

    /// Split segment into two segments at the specified cell position.
    ///
    /// If the cut point falls in the middle of a 2-cell wide character then it is replaced
    /// by two spaces, to preserve the display width of the parent segment.
    ///
    /// # Arguments
    ///
    /// * `cut` - Cell offset within the segment to cut at.
    ///
    /// # Returns
    ///
    /// A tuple of two segments: (before, after).
    ///
    /// # Example
    ///
    /// ```
    /// use rich_rs::Segment;
    ///
    /// let seg = Segment::new("hello");
    /// let (before, after) = seg.split_cells(3);
    /// assert_eq!(&*before.text, "hel");
    /// assert_eq!(&*after.text, "lo");
    /// ```
    pub fn split_cells(&self, cut: usize) -> (Segment, Segment) {
        let text = &self.text;
        let style = self.style;
        let meta = self.meta.clone();
        let control = self.control.clone();

        // Control segments have no visual width
        if control.is_some() {
            return (
                self.clone(),
                Segment::new_with_style_control("", style, meta, control),
            );
        }

        let segment_cell_len = cell_len(text);

        // If cut is at or beyond the end, return original and empty
        if cut >= segment_cell_len {
            return (
                self.clone(),
                Segment::new_with_style_control("", style, meta, control),
            );
        }

        // If cut is at the start, return empty and original
        if cut == 0 {
            return (
                Segment::new_with_style_control("", style, meta, control),
                self.clone(),
            );
        }

        // Fast path: check if all characters are single-width ASCII
        if text.is_ascii() {
            // ASCII characters are all single-cell width
            let before = &text[..cut];
            let after = &text[cut..];
            return (
                Segment::new_with_style_control(
                    before.to_string(),
                    style,
                    meta.clone(),
                    control.clone(),
                ),
                Segment::new_with_style_control(after.to_string(), style, meta, control),
            );
        }

        // Slow path: iterate through characters tracking cell position
        let mut current_cell_pos = 0;

        for (byte_idx, c) in text.char_indices() {
            let c_width = char_width(c);

            if current_cell_pos == cut {
                // Exact cut point
                let before = &text[..byte_idx];
                let after = &text[byte_idx..];
                return (
                    Segment::new_with_style_control(
                        before.to_string(),
                        style,
                        meta.clone(),
                        control.clone(),
                    ),
                    Segment::new_with_style_control(
                        after.to_string(),
                        style,
                        meta.clone(),
                        control,
                    ),
                );
            }

            if current_cell_pos + c_width > cut {
                // Cut falls in the middle of a double-width character
                // Replace with spaces to preserve total width
                let before = &text[..byte_idx];
                let after_start_byte = byte_idx + c.len_utf8();
                let after = &text[after_start_byte..];

                // We need to add spaces: one at the end of `before`, one at the start of `after`
                let before_with_space = format!("{} ", before);
                let after_with_space = format!(" {}", after);

                return (
                    Segment::new_with_style_control(
                        before_with_space,
                        style,
                        meta.clone(),
                        control.clone(),
                    ),
                    Segment::new_with_style_control(after_with_space, style, meta.clone(), control),
                );
            }

            current_cell_pos += c_width;
        }

        // Shouldn't reach here, but return original and empty as fallback
        (
            self.clone(),
            Segment::new_with_style_control("", style, meta, control),
        )
    }

    /// Internal helper to create a segment with optional style and control.
    fn new_with_style_control(
        text: impl Into<Cow<'static, str>>,
        style: Option<Style>,
        meta: Option<StyleMeta>,
        control: Option<ControlType>,
    ) -> Self {
        Segment {
            text: text.into(),
            style,
            meta,
            control,
        }
    }

    // ========================================================================
    // Associated functions (class methods in Python)
    // ========================================================================

    /// Split a sequence of segments into lines on newline characters.
    ///
    /// # Arguments
    ///
    /// * `segments` - Segments potentially containing newlines.
    ///
    /// # Returns
    ///
    /// A vector of lines, where each line is a vector of segments.
    pub fn split_lines(segments: impl IntoIterator<Item = Segment>) -> Vec<Vec<Segment>> {
        let mut lines: Vec<Vec<Segment>> = Vec::new();
        let mut current_line: Vec<Segment> = Vec::new();

        for segment in segments {
            if segment.text.contains('\n') && segment.control.is_none() {
                let text = segment.text.to_string();
                let style = segment.style;
                let meta = segment.meta.clone();
                let mut remaining = text.as_str();

                while !remaining.is_empty() {
                    if let Some(newline_pos) = remaining.find('\n') {
                        let before = &remaining[..newline_pos];
                        if !before.is_empty() {
                            current_line.push(Segment::new_with_style_control(
                                before.to_string(),
                                style,
                                meta.clone(),
                                None,
                            ));
                        }
                        lines.push(std::mem::take(&mut current_line));
                        remaining = &remaining[newline_pos + 1..];
                    } else {
                        // No more newlines
                        if !remaining.is_empty() {
                            current_line.push(Segment::new_with_style_control(
                                remaining.to_string(),
                                style,
                                meta.clone(),
                                None,
                            ));
                        }
                        break;
                    }
                }
            } else {
                current_line.push(segment);
            }
        }

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

        lines
    }

    /// Split segments into lines and crop/pad each line to a specific length.
    ///
    /// # Arguments
    ///
    /// * `segments` - An iterable of segments to process.
    /// * `length` - Desired line length in cells.
    /// * `style` - Style to use for padding.
    /// * `pad` - Whether to pad lines shorter than `length`.
    /// * `include_new_lines` - Whether to append newline segments to each line.
    ///
    /// # Returns
    ///
    /// A vector of lines, each cropped/padded to the desired length.
    pub fn split_and_crop_lines(
        segments: impl IntoIterator<Item = Segment>,
        length: usize,
        style: Option<Style>,
        pad: bool,
        include_new_lines: bool,
    ) -> Vec<Vec<Segment>> {
        let mut lines: Vec<Vec<Segment>> = Vec::new();
        let mut current_line: Vec<Segment> = Vec::new();
        let new_line_segment = Segment::line();

        for segment in segments {
            if segment.text.contains('\n') && segment.control.is_none() {
                let text = segment.text.to_string();
                let segment_style = segment.style;
                let segment_meta = segment.meta.clone();
                let mut remaining = text.as_str();

                while !remaining.is_empty() {
                    if let Some(newline_pos) = remaining.find('\n') {
                        let before = &remaining[..newline_pos];
                        if !before.is_empty() {
                            current_line.push(Segment::new_with_style_control(
                                before.to_string(),
                                segment_style,
                                segment_meta.clone(),
                                None,
                            ));
                        }
                        let mut cropped =
                            Self::adjust_line_length(&current_line, length, style, pad);
                        if include_new_lines {
                            cropped.push(new_line_segment.clone());
                        }
                        lines.push(cropped);
                        current_line.clear();
                        remaining = &remaining[newline_pos + 1..];
                    } else {
                        if !remaining.is_empty() {
                            current_line.push(Segment::new_with_style_control(
                                remaining.to_string(),
                                segment_style,
                                segment_meta.clone(),
                                None,
                            ));
                        }
                        break;
                    }
                }
            } else {
                current_line.push(segment);
            }
        }

        // Handle the last line
        if !current_line.is_empty() {
            lines.push(Self::adjust_line_length(&current_line, length, style, pad));
        }

        lines
    }

    /// Adjust a line to a given width by cropping or padding.
    ///
    /// # Arguments
    ///
    /// * `line` - A slice of segments representing a single line.
    /// * `length` - Desired width in cells.
    /// * `style` - Style to use for padding.
    /// * `pad` - Whether to pad lines shorter than `length`.
    ///
    /// # Returns
    ///
    /// A new vector of segments with the desired length.
    pub fn adjust_line_length(
        line: &[Segment],
        length: usize,
        style: Option<Style>,
        pad: bool,
    ) -> Vec<Segment> {
        let line_length = Self::get_line_length(line);

        if line_length < length {
            // Line is shorter than desired
            if pad {
                let mut new_line = line.to_vec();
                let padding = " ".repeat(length - line_length);
                let end_style = line.iter().rev().find_map(|seg| {
                    if seg.control.is_some() {
                        return None;
                    }
                    seg.style
                });
                // Padding should extend *background* colors to avoid hairlines, but should not
                // inherit decoration attributes like underline/bold/dim from the preceding text.
                let padding_style = match (style, end_style) {
                    (Some(mut base), Some(end)) => {
                        if base.bgcolor.is_none() {
                            if let Some(bg) = end.bgcolor {
                                base.bgcolor = Some(bg);
                            }
                        }
                        Some(base)
                    }
                    (Some(base), None) => Some(base),
                    (None, Some(end)) => end.bgcolor.map(|bg| Style::new().with_bgcolor(bg)),
                    (None, None) => None,
                };
                new_line.push(Segment::new_with_style_control(
                    padding,
                    padding_style,
                    None,
                    None,
                ));
                new_line
            } else {
                line.to_vec()
            }
        } else if line_length > length {
            // Line is longer than desired - crop it
            let mut new_line = Vec::new();
            let mut current_length = 0;

            for segment in line {
                let segment_length = segment.cell_len();

                if segment.control.is_some() {
                    // Control segments don't contribute to visual length
                    new_line.push(segment.clone());
                    continue;
                }

                if current_length + segment_length <= length {
                    // Segment fits entirely
                    new_line.push(segment.clone());
                    current_length += segment_length;
                } else {
                    // Segment needs to be cropped
                    let remaining_space = length - current_length;
                    if remaining_space > 0 {
                        let cropped_text = set_cell_size(&segment.text, remaining_space);
                        new_line.push(Segment::new_with_style_control(
                            cropped_text,
                            segment.style,
                            segment.meta.clone(),
                            None,
                        ));
                    }
                    break;
                }
            }

            new_line
        } else {
            // Line is exactly the right length
            line.to_vec()
        }
    }

    /// Get the last non-control style in a line.
    ///
    /// This is useful for determining the "end of line" style when padding with spaces,
    /// so background colors extend to the full width.
    pub fn get_last_style(line: &[Segment]) -> Option<Style> {
        line.iter().rev().find_map(|seg| {
            if seg.control.is_some() {
                None
            } else {
                seg.style
            }
        })
    }

    /// Simplify segments by merging adjacent segments with the same style.
    ///
    /// # Arguments
    ///
    /// * `segments` - An iterable of segments to simplify.
    ///
    /// # Returns
    ///
    /// A `Segments` collection with adjacent same-style segments merged.
    pub fn simplify(segments: impl IntoIterator<Item = Segment>) -> Segments {
        let mut result = Segments::new();
        let mut iter = segments.into_iter();

        let Some(mut last_segment) = iter.next() else {
            return result;
        };

        for segment in iter {
            // Only merge non-control segments with same style
            if last_segment.style == segment.style
                && last_segment.meta == segment.meta
                && last_segment.control.is_none()
                && segment.control.is_none()
            {
                // Merge text
                let merged_text = format!("{}{}", last_segment.text, segment.text);
                last_segment = Segment::new_with_style_control(
                    merged_text,
                    last_segment.style,
                    last_segment.meta.clone(),
                    None,
                );
            } else {
                result.push(last_segment);
                last_segment = segment;
            }
        }

        result.push(last_segment);
        result
    }

    /// Divide segments at multiple cell positions.
    ///
    /// # Arguments
    ///
    /// * `segments` - Segments to divide.
    /// * `cuts` - Cell positions where to divide (must be sorted in ascending order).
    ///
    /// # Returns
    ///
    /// A vector of segment vectors, one for each division. Always includes a trailing
    /// partition containing any remaining content after the last cut.
    ///
    /// # Panics (debug mode only)
    ///
    /// Debug-asserts that cuts are sorted in ascending order.
    pub fn divide(
        segments: impl IntoIterator<Item = Segment>,
        cuts: &[usize],
    ) -> Vec<Vec<Segment>> {
        // Precondition: cuts must be sorted ascending
        debug_assert!(
            cuts.windows(2).all(|w| w[0] <= w[1]),
            "cuts must be sorted in ascending order"
        );

        if cuts.is_empty() {
            return Vec::new();
        }

        let mut result: Vec<Vec<Segment>> = Vec::new();
        let mut split_segments: Vec<Segment> = Vec::new();
        let mut cut_iter = cuts.iter().copied();

        // Handle leading zeros
        let mut current_cut;
        loop {
            match cut_iter.next() {
                None => return result,
                Some(0) => result.push(Vec::new()),
                Some(c) => {
                    current_cut = c;
                    break;
                }
            }
        }

        let mut pos: usize = 0;
        let mut cuts_exhausted = false;

        for segment in segments {
            // Control segments don't contribute to position
            if segment.control.is_some() {
                split_segments.push(segment);
                continue;
            }

            // If cuts are exhausted, just accumulate remaining segments
            if cuts_exhausted {
                split_segments.push(segment);
                continue;
            }

            let mut current_segment = segment;

            loop {
                let text = &current_segment.text;
                if text.is_empty() {
                    break;
                }

                let seg_len = cell_len(text);
                let end_pos = pos + seg_len;

                if end_pos < current_cut {
                    // Entire segment fits before cut
                    split_segments.push(current_segment);
                    pos = end_pos;
                    break;
                } else if end_pos == current_cut {
                    // Segment ends exactly at cut
                    split_segments.push(current_segment);
                    result.push(std::mem::take(&mut split_segments));
                    pos = end_pos;

                    // Move to next cut
                    match cut_iter.next() {
                        None => {
                            // No more cuts - set flag and continue accumulating
                            cuts_exhausted = true;
                        }
                        Some(next_cut) => current_cut = next_cut,
                    }
                    break;
                } else {
                    // Segment crosses the cut boundary - split it
                    let split_point = current_cut - pos;
                    let (before, after) = current_segment.split_cells(split_point);

                    if !before.text.is_empty() {
                        split_segments.push(before);
                    }
                    result.push(std::mem::take(&mut split_segments));
                    pos = current_cut;

                    // Continue processing with the remaining part
                    current_segment = after;

                    // Move to next cut
                    match cut_iter.next() {
                        None => {
                            // No more cuts - add remaining segment and set flag
                            if !current_segment.text.is_empty() {
                                split_segments.push(current_segment);
                            }
                            cuts_exhausted = true;
                            break;
                        }
                        Some(next_cut) => current_cut = next_cut,
                    }
                    // Continue the inner loop to process remaining segment
                }
            }
        }

        // Always yield the trailing partition (matches Python Rich's `yield segments_copy()`)
        result.push(split_segments);
        result
    }

    /// Apply style to all segments.
    ///
    /// Returns segments where the style is replaced by `style + segment.style + post_style`.
    ///
    /// # Arguments
    ///
    /// * `segments` - Segments to process.
    /// * `style` - Base style to apply first.
    /// * `post_style` - Style to apply after segment's own style.
    ///
    /// # Returns
    ///
    /// A new `Segments` collection with styles applied.
    pub fn apply_style_to_segments(
        segments: impl IntoIterator<Item = Segment>,
        style: Option<Style>,
        post_style: Option<Style>,
    ) -> Segments {
        let mut result = Segments::new();

        for segment in segments {
            if segment.control.is_some() {
                // Don't apply style to control segments
                result.push(segment);
                continue;
            }

            let mut new_style = segment.style;

            // Apply base style first
            if let Some(base) = style {
                new_style = Some(match new_style {
                    Some(existing) => base.combine(&existing),
                    None => base,
                });
            }

            // Apply post style
            if let Some(post) = post_style {
                new_style = Some(match new_style {
                    Some(existing) => existing.combine(&post),
                    None => post,
                });
            }

            result.push(Segment {
                text: segment.text,
                style: new_style,
                meta: segment.meta,
                control: None,
            });
        }

        result
    }

    /// Filter segments by control status.
    ///
    /// # Arguments
    ///
    /// * `segments` - Segments to filter.
    /// * `is_control` - If true, keep only control segments; if false, keep only non-control segments.
    ///
    /// # Returns
    ///
    /// A new `Segments` collection with only matching segments.
    pub fn filter_control(
        segments: impl IntoIterator<Item = Segment>,
        is_control: bool,
    ) -> Segments {
        segments
            .into_iter()
            .filter(|s| s.is_control() == is_control)
            .collect()
    }

    /// Remove all styles from segments.
    ///
    /// # Arguments
    ///
    /// * `segments` - Segments to process.
    ///
    /// # Returns
    ///
    /// A new `Segments` collection with all styles removed.
    pub fn strip_styles(segments: impl IntoIterator<Item = Segment>) -> Segments {
        segments
            .into_iter()
            .map(|s| Segment {
                text: s.text,
                style: None,
                meta: None,
                control: s.control,
            })
            .collect()
    }

    /// Get the total cell width of a line of segments.
    ///
    /// # Arguments
    ///
    /// * `line` - A slice of segments representing a single line (no newlines).
    ///
    /// # Returns
    ///
    /// The total cell width of all non-control segments.
    pub fn get_line_length(line: &[Segment]) -> usize {
        line.iter()
            .filter(|s| s.control.is_none())
            .map(|s| cell_len(&s.text))
            .sum()
    }

    /// Get the shape (enclosing rectangle) of a list of lines.
    ///
    /// # Arguments
    ///
    /// * `lines` - A list of lines (no newline characters).
    ///
    /// # Returns
    ///
    /// A tuple of (width, height) representing the enclosing rectangle.
    pub fn get_shape(lines: &[Vec<Segment>]) -> (usize, usize) {
        if lines.is_empty() {
            return (0, 0);
        }

        let max_width = lines
            .iter()
            .map(|line| Self::get_line_length(line))
            .max()
            .unwrap_or(0);
        (max_width, lines.len())
    }

    /// Set the shape of a list of lines to a specific rectangle.
    ///
    /// # Arguments
    ///
    /// * `lines` - A list of lines.
    /// * `width` - Desired width.
    /// * `height` - Desired height (if None, uses current height).
    /// * `style` - Style for padding.
    /// * `new_lines` - Whether padded lines should include newline characters.
    ///
    /// # Returns
    ///
    /// A new list of lines with the specified shape.
    pub fn set_shape(
        lines: &[Vec<Segment>],
        width: usize,
        height: Option<usize>,
        style: Option<Style>,
        new_lines: bool,
    ) -> Vec<Vec<Segment>> {
        let target_height = height.unwrap_or(lines.len());

        // Create blank line for padding
        let blank_text = if new_lines {
            format!("{}\n", " ".repeat(width))
        } else {
            " ".repeat(width)
        };
        let blank = vec![Segment::new_with_style_control(
            blank_text, style, None, None,
        )];

        let mut result: Vec<Vec<Segment>> = lines
            .iter()
            .take(target_height)
            .map(|line| Self::adjust_line_length(line, width, style, true))
            .collect();

        // Add blank lines if needed
        while result.len() < target_height {
            result.push(blank.clone());
        }

        result
    }

    // ========================================================================
    // Vertical alignment functions
    // ========================================================================

    /// Align lines to the top by padding the bottom with blank lines.
    ///
    /// # Arguments
    ///
    /// * `lines` - A list of lines.
    /// * `width` - Desired width of blank lines in cells.
    /// * `height` - Desired total height.
    /// * `style` - Style for padding.
    /// * `new_lines` - Whether blank lines should include "\n".
    pub fn align_top(
        lines: &[Vec<Segment>],
        width: usize,
        height: usize,
        style: Option<Style>,
        new_lines: bool,
    ) -> Vec<Vec<Segment>> {
        let extra_lines = height.saturating_sub(lines.len());
        if extra_lines == 0 {
            return lines[..height.min(lines.len())].to_vec();
        }
        let mut result: Vec<Vec<Segment>> = lines[..height.min(lines.len())].to_vec();
        let blank_text = if new_lines {
            format!("{}\n", " ".repeat(width))
        } else {
            " ".repeat(width)
        };
        let blank = vec![Segment::new_with_style_control(
            blank_text, style, None, None,
        )];
        for _ in 0..extra_lines {
            result.push(blank.clone());
        }
        result
    }

    /// Align lines to the bottom by padding the top with blank lines.
    pub fn align_bottom(
        lines: &[Vec<Segment>],
        width: usize,
        height: usize,
        style: Option<Style>,
        new_lines: bool,
    ) -> Vec<Vec<Segment>> {
        let extra_lines = height.saturating_sub(lines.len());
        if extra_lines == 0 {
            return lines[..height.min(lines.len())].to_vec();
        }
        let blank_text = if new_lines {
            format!("{}\n", " ".repeat(width))
        } else {
            " ".repeat(width)
        };
        let blank = vec![Segment::new_with_style_control(
            blank_text, style, None, None,
        )];
        let mut result: Vec<Vec<Segment>> = Vec::with_capacity(height);
        for _ in 0..extra_lines {
            result.push(blank.clone());
        }
        result.extend_from_slice(&lines[..height.min(lines.len())]);
        result
    }

    /// Align lines to the middle by padding top and bottom with blank lines.
    pub fn align_middle(
        lines: &[Vec<Segment>],
        width: usize,
        height: usize,
        style: Option<Style>,
        new_lines: bool,
    ) -> Vec<Vec<Segment>> {
        let extra_lines = height.saturating_sub(lines.len());
        if extra_lines == 0 {
            return lines[..height.min(lines.len())].to_vec();
        }
        let blank_text = if new_lines {
            format!("{}\n", " ".repeat(width))
        } else {
            " ".repeat(width)
        };
        let blank = vec![Segment::new_with_style_control(
            blank_text, style, None, None,
        )];
        let top_lines = extra_lines / 2;
        let bottom_lines = extra_lines - top_lines;
        let mut result: Vec<Vec<Segment>> = Vec::with_capacity(height);
        for _ in 0..top_lines {
            result.push(blank.clone());
        }
        result.extend_from_slice(&lines[..height.min(lines.len())]);
        for _ in 0..bottom_lines {
            result.push(blank.clone());
        }
        result
    }

    /// Split segments into lines, preserving a boolean flag indicating whether
    /// a newline character was encountered (true) or end of content (false).
    ///
    /// This is equivalent to Python Rich's `Segment.split_lines_terminator`.
    pub fn split_lines_terminator(
        segments: impl IntoIterator<Item = Segment>,
    ) -> Vec<(Vec<Segment>, bool)> {
        let mut result: Vec<(Vec<Segment>, bool)> = Vec::new();
        let mut current_line: Vec<Segment> = Vec::new();

        for segment in segments {
            if segment.text.contains('\n') && segment.control.is_none() {
                let text = segment.text.to_string();
                let style = segment.style;
                let meta = segment.meta.clone();
                let mut remaining = text.as_str();

                while !remaining.is_empty() {
                    if let Some(newline_pos) = remaining.find('\n') {
                        let before = &remaining[..newline_pos];
                        if !before.is_empty() {
                            current_line.push(Segment::new_with_style_control(
                                before.to_string(),
                                style,
                                meta.clone(),
                                None,
                            ));
                        }
                        result.push((std::mem::take(&mut current_line), true));
                        remaining = &remaining[newline_pos + 1..];
                    } else {
                        if !remaining.is_empty() {
                            current_line.push(Segment::new_with_style_control(
                                remaining.to_string(),
                                style,
                                meta.clone(),
                                None,
                            ));
                        }
                        break;
                    }
                }
            } else {
                current_line.push(segment);
            }
        }

        if !current_line.is_empty() {
            result.push((current_line, false));
        }

        result
    }

    /// Remove link metadata from segments.
    ///
    /// This is equivalent to Python Rich's `Segment.strip_links`.
    pub fn strip_links(segments: impl IntoIterator<Item = Segment>) -> Segments {
        segments
            .into_iter()
            .map(|s| Segment {
                text: s.text,
                style: s.style,
                meta: None,
                control: s.control,
            })
            .collect()
    }

    /// Remove color information from segments, keeping text and attributes.
    ///
    /// This is equivalent to Python Rich's `Segment.remove_color`.
    pub fn remove_color(segments: impl IntoIterator<Item = Segment>) -> Segments {
        segments
            .into_iter()
            .map(|s| {
                let new_style = s.style.map(|style| style.without_color());
                Segment {
                    text: s.text,
                    style: new_style,
                    meta: s.meta,
                    control: s.control,
                }
            })
            .collect()
    }
}

/// A simple renderable wrapping pre-rendered lines of segments.
///
/// This allows pre-rendered content to be passed through the rendering pipeline.
/// Equivalent to Python Rich's `SegmentLines`.
#[derive(Debug, Clone)]
pub struct SegmentLines {
    /// The pre-rendered lines.
    pub lines: Vec<Vec<Segment>>,
    /// Whether to insert newlines after each line.
    pub new_lines: bool,
}

impl SegmentLines {
    /// Create a new SegmentLines.
    pub fn new(lines: Vec<Vec<Segment>>, new_lines: bool) -> Self {
        SegmentLines { lines, new_lines }
    }

    /// Convert to a flat Segments collection for rendering.
    pub fn to_segments(&self) -> Segments {
        let mut result = Segments::new();
        let new_line = Segment::line();
        for line in &self.lines {
            for seg in line {
                result.push(seg.clone());
            }
            if self.new_lines {
                result.push(new_line.clone());
            }
        }
        result
    }
}

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

impl From<&'static str> for Segment {
    fn from(s: &'static str) -> Self {
        Segment::new(s)
    }
}

impl From<String> for Segment {
    fn from(s: String) -> Self {
        Segment::new(s)
    }
}

/// A collection of segments, backed by SmallVec for efficiency.
///
/// This newtype abstracts over the underlying storage, allowing future
/// optimization (e.g., streaming) without breaking the API.
#[derive(Debug, Clone, Default)]
pub struct Segments(SmallVec<[Segment; 8]>);

impl Segments {
    /// Create an empty Segments collection.
    pub fn new() -> Self {
        Segments(SmallVec::new())
    }

    /// Create a Segments collection with a single segment.
    pub fn one(segment: Segment) -> Self {
        let mut sv = SmallVec::new();
        sv.push(segment);
        Segments(sv)
    }

    /// Add a segment to the collection.
    pub fn push(&mut self, segment: Segment) {
        self.0.push(segment);
    }

    /// Extend with segments from an iterator.
    pub fn extend(&mut self, iter: impl IntoIterator<Item = Segment>) {
        self.0.extend(iter);
    }

    /// Get the number of segments.
    pub fn len(&self) -> usize {
        self.0.len()
    }

    /// Check if empty.
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    /// Iterate over segments.
    pub fn iter(&self) -> impl Iterator<Item = &Segment> {
        self.0.iter()
    }

    /// Get the total cell width of all segments.
    pub fn cell_len(&self) -> usize {
        self.0.iter().map(|s| s.cell_len()).sum()
    }

    /// Convert to a Vec (consumes self).
    pub fn into_vec(self) -> Vec<Segment> {
        self.0.into_vec()
    }
}

impl From<Segment> for Segments {
    fn from(segment: Segment) -> Self {
        Segments::one(segment)
    }
}

impl From<Vec<Segment>> for Segments {
    fn from(vec: Vec<Segment>) -> Self {
        Segments(SmallVec::from_vec(vec))
    }
}

impl FromIterator<Segment> for Segments {
    fn from_iter<I: IntoIterator<Item = Segment>>(iter: I) -> Self {
        Segments(iter.into_iter().collect())
    }
}

impl IntoIterator for Segments {
    type Item = Segment;
    type IntoIter = smallvec::IntoIter<[Segment; 8]>;

    fn into_iter(self) -> Self::IntoIter {
        self.0.into_iter()
    }
}

impl<'a> IntoIterator for &'a Segments {
    type Item = &'a Segment;
    type IntoIter = std::slice::Iter<'a, Segment>;

    fn into_iter(self) -> Self::IntoIter {
        self.0.iter()
    }
}

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

    #[test]
    fn test_new_segment() {
        let seg = Segment::new("hello");
        assert_eq!(&*seg.text, "hello");
        assert!(seg.style.is_none());
        assert!(seg.control.is_none());
    }

    #[test]
    fn test_cell_len() {
        let seg = Segment::new("hello");
        assert_eq!(seg.cell_len(), 5);
    }

    #[test]
    fn test_segments_collection() {
        let mut segs = Segments::new();
        segs.push(Segment::new("hello"));
        segs.push(Segment::new(" "));
        segs.push(Segment::new("world"));
        assert_eq!(segs.len(), 3);
        assert_eq!(segs.cell_len(), 11);
    }

    #[test]
    fn test_segments_from_iter() {
        let segs: Segments = vec![Segment::new("a"), Segment::new("b"), Segment::new("c")]
            .into_iter()
            .collect();
        assert_eq!(segs.len(), 3);
    }

    // ==================== split_cells tests ====================

    #[test]
    fn test_split_cells_ascii() {
        let seg = Segment::new("hello");
        let (before, after) = seg.split_cells(3);
        assert_eq!(&*before.text, "hel");
        assert_eq!(&*after.text, "lo");
    }

    #[test]
    fn test_split_cells_at_start() {
        let seg = Segment::new("hello");
        let (before, after) = seg.split_cells(0);
        assert_eq!(&*before.text, "");
        assert_eq!(&*after.text, "hello");
    }

    #[test]
    fn test_split_cells_at_end() {
        let seg = Segment::new("hello");
        let (before, after) = seg.split_cells(5);
        assert_eq!(&*before.text, "hello");
        assert_eq!(&*after.text, "");
    }

    #[test]
    fn test_split_cells_beyond_end() {
        let seg = Segment::new("hello");
        let (before, after) = seg.split_cells(10);
        assert_eq!(&*before.text, "hello");
        assert_eq!(&*after.text, "");
    }

    #[test]
    fn test_split_cells_cjk_exact() {
        // CJK characters are 2 cells wide
        let seg = Segment::new("你好");
        let (before, after) = seg.split_cells(2);
        assert_eq!(&*before.text, "ä½ ");
        assert_eq!(&*after.text, "好");
    }

    #[test]
    fn test_split_cells_cjk_middle() {
        // Splitting in the middle of a double-width char should replace with spaces
        let seg = Segment::new("你好");
        let (before, after) = seg.split_cells(1);
        assert_eq!(&*before.text, " "); // Space replaces first half of ä½ 
        assert_eq!(&*after.text, " 好"); // Space + remaining chars
    }

    #[test]
    fn test_split_cells_cjk_middle_complex() {
        // "你好世界" = 8 cells total
        let seg = Segment::new("你好世界");
        let (before, after) = seg.split_cells(3);
        // Cut at 3 is in the middle of 好 (which spans cells 2-3)
        assert_eq!(&*before.text, "ä½  "); // ä½  + space
        assert_eq!(&*after.text, " 世界"); // space + 世界
    }

    #[test]
    fn test_split_cells_mixed_content() {
        // "aä½ b" = 1 + 2 + 1 = 4 cells
        let seg = Segment::new("aä½ b");
        let (before, after) = seg.split_cells(3);
        assert_eq!(&*before.text, "aä½ ");
        assert_eq!(&*after.text, "b");
    }

    #[test]
    fn test_split_cells_preserves_style() {
        let style = Style::new().with_bold(true);
        let seg = Segment::styled("hello", style);
        let (before, after) = seg.split_cells(2);
        assert_eq!(before.style, Some(style));
        assert_eq!(after.style, Some(style));
    }

    #[test]
    fn test_split_cells_control_segment() {
        let seg = Segment::control(ControlType::Bell);
        let (before, after) = seg.split_cells(5);
        assert!(before.control.is_some());
        assert_eq!(&*after.text, "");
    }

    #[test]
    fn test_split_cells_emoji() {
        // Emoji are typically 2 cells wide
        let seg = Segment::new("😀hello");
        let (before, after) = seg.split_cells(2);
        assert_eq!(&*before.text, "😀");
        assert_eq!(&*after.text, "hello");
    }

    // ==================== split_lines tests ====================

    #[test]
    fn test_split_lines_no_newlines() {
        let segments = vec![Segment::new("hello"), Segment::new(" world")];
        let lines = Segment::split_lines(segments);
        assert_eq!(lines.len(), 1);
        assert_eq!(lines[0].len(), 2);
    }

    #[test]
    fn test_split_lines_single_newline() {
        let segments = vec![Segment::new("hello\nworld")];
        let lines = Segment::split_lines(segments);
        assert_eq!(lines.len(), 2);
        assert_eq!(&*lines[0][0].text, "hello");
        assert_eq!(&*lines[1][0].text, "world");
    }

    #[test]
    fn test_split_lines_multiple_newlines() {
        let segments = vec![Segment::new("a\nb\nc")];
        let lines = Segment::split_lines(segments);
        assert_eq!(lines.len(), 3);
        assert_eq!(&*lines[0][0].text, "a");
        assert_eq!(&*lines[1][0].text, "b");
        assert_eq!(&*lines[2][0].text, "c");
    }

    #[test]
    fn test_split_lines_trailing_newline() {
        let segments = vec![Segment::new("hello\n")];
        let lines = Segment::split_lines(segments);
        assert_eq!(lines.len(), 1);
        assert_eq!(&*lines[0][0].text, "hello");
    }

    #[test]
    fn test_split_lines_preserves_style() {
        let style = Style::new().with_bold(true);
        let segments = vec![Segment::styled("hello\nworld", style)];
        let lines = Segment::split_lines(segments);
        assert_eq!(lines[0][0].style, Some(style));
        assert_eq!(lines[1][0].style, Some(style));
    }

    #[test]
    fn test_split_lines_control_segment_unaffected() {
        let segments = vec![
            Segment::new("hello"),
            Segment::control(ControlType::Bell),
            Segment::new("world"),
        ];
        let lines = Segment::split_lines(segments);
        assert_eq!(lines.len(), 1);
        assert_eq!(lines[0].len(), 3);
    }

    // ==================== split_and_crop_lines tests ====================

    #[test]
    fn test_split_and_crop_lines_basic() {
        let segments = vec![Segment::new("hello world")];
        let lines = Segment::split_and_crop_lines(segments, 5, None, true, false);
        assert_eq!(lines.len(), 1);
        // Line should be cropped to 5 cells
        let total_len: usize = lines[0].iter().map(|s| cell_len(&s.text)).sum();
        assert_eq!(total_len, 5);
    }

    #[test]
    fn test_split_and_crop_lines_with_newlines() {
        let segments = vec![Segment::new("hello\nworld")];
        let lines = Segment::split_and_crop_lines(segments, 10, None, true, false);
        assert_eq!(lines.len(), 2);
    }

    #[test]
    fn test_split_and_crop_lines_include_newlines() {
        let segments = vec![Segment::new("hello\nworld")];
        let lines = Segment::split_and_crop_lines(segments, 10, None, true, true);
        assert_eq!(lines.len(), 2);
        // First line should have a newline segment at the end
        let last_seg = lines[0].last().unwrap();
        assert_eq!(&*last_seg.text, "\n");
    }

    #[test]
    fn test_split_and_crop_lines_padding() {
        let segments = vec![Segment::new("hi")];
        let lines = Segment::split_and_crop_lines(segments, 5, None, true, false);
        let total_len: usize = lines[0].iter().map(|s| cell_len(&s.text)).sum();
        assert_eq!(total_len, 5); // Should be padded to 5
    }

    #[test]
    fn test_split_and_crop_lines_no_padding() {
        let segments = vec![Segment::new("hi")];
        let lines = Segment::split_and_crop_lines(segments, 5, None, false, false);
        let total_len: usize = lines[0].iter().map(|s| cell_len(&s.text)).sum();
        assert_eq!(total_len, 2); // Should not be padded
    }

    // ==================== adjust_line_length tests ====================

    #[test]
    fn test_adjust_line_length_exact() {
        let line = vec![Segment::new("hello")];
        let result = Segment::adjust_line_length(&line, 5, None, true);
        assert_eq!(Segment::get_line_length(&result), 5);
    }

    #[test]
    fn test_adjust_line_length_pad() {
        let line = vec![Segment::new("hi")];
        let result = Segment::adjust_line_length(&line, 5, None, true);
        assert_eq!(Segment::get_line_length(&result), 5);
        assert_eq!(result.len(), 2); // Original + padding
    }

    #[test]
    fn test_adjust_line_length_pad_inherits_end_style() {
        let end_style = Style::new().with_bgcolor(crate::SimpleColor::Rgb { r: 1, g: 2, b: 3 });
        let line = vec![Segment::styled("x", end_style)];
        let result = Segment::adjust_line_length(&line, 3, None, true);
        assert_eq!(Segment::get_line_length(&result), 3);
        let padding = result.last().unwrap();
        assert_eq!(&*padding.text, "  ");
        assert_eq!(padding.style.unwrap().bgcolor, end_style.bgcolor);
    }

    #[test]
    fn test_adjust_line_length_pad_combines_base_and_end_style() {
        let base = Style::new().with_bold(true);
        let end_style = Style::new().with_bgcolor(crate::SimpleColor::Rgb { r: 4, g: 5, b: 6 });
        let line = vec![Segment::styled("x", end_style)];
        let result = Segment::adjust_line_length(&line, 3, Some(base), true);
        let padding = result.last().unwrap().style.unwrap();
        assert_eq!(padding.bold, Some(true));
        assert_eq!(padding.bgcolor, end_style.bgcolor);
    }

    #[test]
    fn test_adjust_line_length_no_pad() {
        let line = vec![Segment::new("hi")];
        let result = Segment::adjust_line_length(&line, 5, None, false);
        assert_eq!(Segment::get_line_length(&result), 2);
    }

    #[test]
    fn test_adjust_line_length_crop() {
        let line = vec![Segment::new("hello world")];
        let result = Segment::adjust_line_length(&line, 5, None, true);
        assert_eq!(Segment::get_line_length(&result), 5);
    }

    #[test]
    fn test_adjust_line_length_crop_multiple_segments() {
        let line = vec![Segment::new("hello"), Segment::new(" world")];
        let result = Segment::adjust_line_length(&line, 7, None, true);
        assert_eq!(Segment::get_line_length(&result), 7);
    }

    #[test]
    fn test_adjust_line_length_preserves_control() {
        let line = vec![Segment::control(ControlType::Bell), Segment::new("hello")];
        let result = Segment::adjust_line_length(&line, 3, None, true);
        assert!(result[0].control.is_some());
    }

    #[test]
    fn test_adjust_line_length_crop_cjk() {
        // CJK characters are 2 cells wide
        let line = vec![Segment::new("你好世界")]; // 8 cells
        let result = Segment::adjust_line_length(&line, 5, None, true);
        assert_eq!(Segment::get_line_length(&result), 5);
    }

    // ==================== simplify tests ====================

    #[test]
    fn test_simplify_empty() {
        let segments: Vec<Segment> = vec![];
        let result = Segment::simplify(segments);
        assert!(result.is_empty());
    }

    #[test]
    fn test_simplify_single() {
        let segments = vec![Segment::new("hello")];
        let result = Segment::simplify(segments);
        assert_eq!(result.len(), 1);
        assert_eq!(&*result.iter().next().unwrap().text, "hello");
    }

    #[test]
    fn test_simplify_same_style() {
        let segments = vec![Segment::new("hello"), Segment::new(" world")];
        let result = Segment::simplify(segments);
        assert_eq!(result.len(), 1);
        assert_eq!(&*result.iter().next().unwrap().text, "hello world");
    }

    #[test]
    fn test_simplify_different_styles() {
        let style1 = Style::new().with_bold(true);
        let style2 = Style::new().with_italic(true);
        let segments = vec![
            Segment::styled("hello", style1),
            Segment::styled(" world", style2),
        ];
        let result = Segment::simplify(segments);
        assert_eq!(result.len(), 2);
    }

    #[test]
    fn test_simplify_control_not_merged() {
        let segments = vec![
            Segment::new("hello"),
            Segment::control(ControlType::Bell),
            Segment::new(" world"),
        ];
        let result = Segment::simplify(segments);
        assert_eq!(result.len(), 3);
    }

    #[test]
    fn test_simplify_mixed() {
        let style = Style::new().with_bold(true);
        let segments = vec![
            Segment::new("a"),
            Segment::new("b"),
            Segment::styled("c", style),
            Segment::styled("d", style),
            Segment::new("e"),
        ];
        let result = Segment::simplify(segments);
        assert_eq!(result.len(), 3);
        let texts: Vec<&str> = result.iter().map(|s| &*s.text).collect();
        assert_eq!(texts, vec!["ab", "cd", "e"]);
    }

    // ==================== divide tests ====================

    #[test]
    fn test_divide_empty_cuts() {
        let segments = vec![Segment::new("hello")];
        let result = Segment::divide(segments, &[]);
        assert!(result.is_empty());
    }

    #[test]
    fn test_divide_single_cut() {
        let segments = vec![Segment::new("hello world")];
        let result = Segment::divide(segments, &[5]);
        // With trailing partition: [0..5) = "hello", [5..) = " world"
        assert_eq!(result.len(), 2);
        let first_text: String = result[0].iter().map(|s| s.text.to_string()).collect();
        let second_text: String = result[1].iter().map(|s| s.text.to_string()).collect();
        assert_eq!(first_text, "hello");
        assert_eq!(second_text, " world");
    }

    #[test]
    fn test_divide_multiple_cuts() {
        let segments = vec![Segment::new("hello world!")];
        // Cuts at cell positions 5 and 11 divide the string into portions
        // [0..5) = "hello", [5..11) = " world", [11..) = "!" (trailing partition)
        let result = Segment::divide(segments, &[5, 11]);
        assert_eq!(result.len(), 3);
        let first: String = result[0].iter().map(|s| s.text.to_string()).collect();
        let second: String = result[1].iter().map(|s| s.text.to_string()).collect();
        let third: String = result[2].iter().map(|s| s.text.to_string()).collect();
        assert_eq!(first, "hello");
        assert_eq!(second, " world");
        assert_eq!(third, "!");
    }

    #[test]
    fn test_divide_includes_remainder() {
        let segments = vec![Segment::new("hello world!")];
        // With cuts at 5 and 12, we get "hello", " world!", and empty trailing partition
        let result = Segment::divide(segments, &[5, 12]);
        assert_eq!(result.len(), 3);
        let first: String = result[0].iter().map(|s| s.text.to_string()).collect();
        let second: String = result[1].iter().map(|s| s.text.to_string()).collect();
        let third: String = result[2].iter().map(|s| s.text.to_string()).collect();
        assert_eq!(first, "hello");
        assert_eq!(second, " world!");
        assert_eq!(third, ""); // Empty trailing partition when content ends exactly at cut
    }

    #[test]
    fn test_divide_zero_cut() {
        let segments = vec![Segment::new("hello")];
        let result = Segment::divide(segments, &[0, 3]);
        // [0..0) = empty, [0..3) = "hel", [3..) = "lo" (trailing)
        assert_eq!(result.len(), 3);
        assert!(result[0].is_empty()); // Zero cut yields empty
        let second: String = result[1].iter().map(|s| s.text.to_string()).collect();
        let third: String = result[2].iter().map(|s| s.text.to_string()).collect();
        assert_eq!(second, "hel");
        assert_eq!(third, "lo");
    }

    #[test]
    fn test_divide_cjk() {
        // "你好世界" = 8 cells
        let segments = vec![Segment::new("你好世界")];
        let result = Segment::divide(segments, &[4]);
        // [0..4) = "你好", [4..) = "世界" (trailing partition)
        assert_eq!(result.len(), 2);
        let first: String = result[0].iter().map(|s| s.text.to_string()).collect();
        let second: String = result[1].iter().map(|s| s.text.to_string()).collect();
        assert_eq!(first, "你好");
        assert_eq!(second, "世界");
    }

    #[test]
    fn test_divide_trailing_content_after_last_cut() {
        // This is the key test for the bug fix: content after last cut should be included
        let segments = vec![Segment::new("abc123xyz")];
        let result = Segment::divide(segments, &[3, 6]);
        // [0..3) = "abc", [3..6) = "123", [6..) = "xyz" (trailing)
        assert_eq!(result.len(), 3);
        let first: String = result[0].iter().map(|s| s.text.to_string()).collect();
        let second: String = result[1].iter().map(|s| s.text.to_string()).collect();
        let third: String = result[2].iter().map(|s| s.text.to_string()).collect();
        assert_eq!(first, "abc");
        assert_eq!(second, "123");
        assert_eq!(third, "xyz");
    }

    #[test]
    fn test_divide_empty_trailing_partition_when_content_ends_at_cut() {
        // When content ends exactly at the last cut, we still get an empty trailing partition
        let segments = vec![Segment::new("hello")];
        let result = Segment::divide(segments, &[5]);
        // [0..5) = "hello", [5..) = "" (empty trailing)
        assert_eq!(result.len(), 2);
        let first: String = result[0].iter().map(|s| s.text.to_string()).collect();
        let second: String = result[1].iter().map(|s| s.text.to_string()).collect();
        assert_eq!(first, "hello");
        assert_eq!(second, "");
    }

    #[test]
    fn test_divide_multiple_segments_with_trailing() {
        // Test with multiple input segments
        let segments = vec![
            Segment::new("hello"),
            Segment::new(" "),
            Segment::new("world"),
        ];
        let result = Segment::divide(segments, &[6]);
        // [0..6) = "hello ", [6..) = "world"
        assert_eq!(result.len(), 2);
        let first: String = result[0].iter().map(|s| s.text.to_string()).collect();
        let second: String = result[1].iter().map(|s| s.text.to_string()).collect();
        assert_eq!(first, "hello ");
        assert_eq!(second, "world");
    }

    // ==================== apply_style_to_segments tests ====================

    #[test]
    fn test_apply_style_base() {
        let base = Style::new().with_bold(true);
        let segments = vec![Segment::new("hello")];
        let result = Segment::apply_style_to_segments(segments, Some(base), None);
        assert_eq!(result.iter().next().unwrap().style, Some(base));
    }

    #[test]
    fn test_apply_style_post() {
        let post = Style::new().with_italic(true);
        let segments = vec![Segment::new("hello")];
        let result = Segment::apply_style_to_segments(segments, None, Some(post));
        assert_eq!(result.iter().next().unwrap().style, Some(post));
    }

    #[test]
    fn test_apply_style_both() {
        let base = Style::new().with_bold(true);
        let post = Style::new().with_italic(true);
        let segments = vec![Segment::new("hello")];
        let result = Segment::apply_style_to_segments(segments, Some(base), Some(post));
        let style = result.iter().next().unwrap().style.unwrap();
        assert_eq!(style.bold, Some(true));
        assert_eq!(style.italic, Some(true));
    }

    #[test]
    fn test_apply_style_combines_with_existing() {
        let base = Style::new().with_bold(true);
        let existing = Style::new().with_italic(true);
        let segments = vec![Segment::styled("hello", existing)];
        let result = Segment::apply_style_to_segments(segments, Some(base), None);
        let style = result.iter().next().unwrap().style.unwrap();
        assert_eq!(style.bold, Some(true));
        assert_eq!(style.italic, Some(true));
    }

    #[test]
    fn test_apply_style_control_unchanged() {
        let base = Style::new().with_bold(true);
        let segments = vec![Segment::control(ControlType::Bell)];
        let result = Segment::apply_style_to_segments(segments, Some(base), None);
        let seg = result.iter().next().unwrap();
        assert!(seg.control.is_some());
    }

    // ==================== filter_control tests ====================

    #[test]
    fn test_filter_control_keep_control() {
        let segments = vec![
            Segment::new("hello"),
            Segment::control(ControlType::Bell),
            Segment::new("world"),
        ];
        let result = Segment::filter_control(segments, true);
        assert_eq!(result.len(), 1);
        assert!(result.iter().next().unwrap().control.is_some());
    }

    #[test]
    fn test_filter_control_keep_non_control() {
        let segments = vec![
            Segment::new("hello"),
            Segment::control(ControlType::Bell),
            Segment::new("world"),
        ];
        let result = Segment::filter_control(segments, false);
        assert_eq!(result.len(), 2);
        for seg in result.iter() {
            assert!(seg.control.is_none());
        }
    }

    // ==================== strip_styles tests ====================

    #[test]
    fn test_strip_styles() {
        let style = Style::new().with_bold(true);
        let segments = vec![
            Segment::styled("hello", style),
            Segment::styled("world", style),
        ];
        let result = Segment::strip_styles(segments);
        for seg in result.iter() {
            assert!(seg.style.is_none());
        }
    }

    #[test]
    fn test_strip_styles_preserves_control() {
        let segments = vec![Segment::control(ControlType::Bell)];
        let result = Segment::strip_styles(segments);
        assert!(result.iter().next().unwrap().control.is_some());
    }

    // ==================== get_line_length tests ====================

    #[test]
    fn test_get_line_length_simple() {
        let line = vec![Segment::new("hello")];
        assert_eq!(Segment::get_line_length(&line), 5);
    }

    #[test]
    fn test_get_line_length_multiple() {
        let line = vec![Segment::new("hello"), Segment::new(" world")];
        assert_eq!(Segment::get_line_length(&line), 11);
    }

    #[test]
    fn test_get_line_length_ignores_control() {
        let line = vec![
            Segment::new("hello"),
            Segment::control(ControlType::Bell),
            Segment::new("world"),
        ];
        assert_eq!(Segment::get_line_length(&line), 10);
    }

    #[test]
    fn test_get_line_length_cjk() {
        let line = vec![Segment::new("你好")];
        assert_eq!(Segment::get_line_length(&line), 4);
    }

    // ==================== get_shape tests ====================

    #[test]
    fn test_get_shape_empty() {
        let lines: Vec<Vec<Segment>> = vec![];
        assert_eq!(Segment::get_shape(&lines), (0, 0));
    }

    #[test]
    fn test_get_shape_single_line() {
        let lines = vec![vec![Segment::new("hello")]];
        assert_eq!(Segment::get_shape(&lines), (5, 1));
    }

    #[test]
    fn test_get_shape_multiple_lines() {
        let lines = vec![
            vec![Segment::new("hello")],
            vec![Segment::new("world!")],
            vec![Segment::new("hi")],
        ];
        assert_eq!(Segment::get_shape(&lines), (6, 3));
    }

    // ==================== set_shape tests ====================

    #[test]
    fn test_set_shape_pad_width() {
        let lines = vec![vec![Segment::new("hi")]];
        let result = Segment::set_shape(&lines, 5, None, None, false);
        assert_eq!(result.len(), 1);
        assert_eq!(Segment::get_line_length(&result[0]), 5);
    }

    #[test]
    fn test_set_shape_add_height() {
        let lines = vec![vec![Segment::new("hello")]];
        let result = Segment::set_shape(&lines, 5, Some(3), None, false);
        assert_eq!(result.len(), 3);
    }

    #[test]
    fn test_set_shape_crop_height() {
        let lines = vec![
            vec![Segment::new("a")],
            vec![Segment::new("b")],
            vec![Segment::new("c")],
        ];
        let result = Segment::set_shape(&lines, 5, Some(2), None, false);
        assert_eq!(result.len(), 2);
    }

    #[test]
    fn test_set_shape_with_newlines() {
        let lines = vec![vec![Segment::new("hi")]];
        let result = Segment::set_shape(&lines, 5, Some(2), None, true);
        assert_eq!(result.len(), 2);
        // Blank lines should contain newline
        let blank_text = result[1]
            .iter()
            .map(|s| s.text.to_string())
            .collect::<String>();
        assert!(blank_text.ends_with('\n'));
    }

    #[test]
    fn test_set_shape_with_style() {
        let style = Style::new().with_bold(true);
        let lines: Vec<Vec<Segment>> = vec![];
        let result = Segment::set_shape(&lines, 5, Some(1), Some(style), false);
        assert_eq!(result.len(), 1);
        assert_eq!(result[0][0].style, Some(style));
    }

    // ==================== vertical alignment tests ====================

    #[test]
    fn test_align_top() {
        let lines = vec![vec![Segment::new("hello")]];
        let result = Segment::align_top(&lines, 5, 3, None, false);
        assert_eq!(result.len(), 3);
        assert_eq!(&*result[0][0].text, "hello");
        // Blank lines
        assert_eq!(Segment::get_line_length(&result[1]), 5);
        assert_eq!(Segment::get_line_length(&result[2]), 5);
    }

    #[test]
    fn test_align_bottom() {
        let lines = vec![vec![Segment::new("hello")]];
        let result = Segment::align_bottom(&lines, 5, 3, None, false);
        assert_eq!(result.len(), 3);
        // Content at bottom
        assert_eq!(&*result[2][0].text, "hello");
        // Blank lines at top
        assert_eq!(Segment::get_line_length(&result[0]), 5);
        assert_eq!(Segment::get_line_length(&result[1]), 5);
    }

    #[test]
    fn test_align_middle() {
        let lines = vec![vec![Segment::new("hello")]];
        let result = Segment::align_middle(&lines, 5, 3, None, false);
        assert_eq!(result.len(), 3);
        // Content in the middle
        assert_eq!(&*result[1][0].text, "hello");
    }

    #[test]
    fn test_align_no_extra_lines() {
        let lines = vec![
            vec![Segment::new("a")],
            vec![Segment::new("b")],
            vec![Segment::new("c")],
        ];
        let result = Segment::align_top(&lines, 5, 3, None, false);
        assert_eq!(result.len(), 3);
    }

    // ==================== split_lines_terminator tests ====================

    #[test]
    fn test_split_lines_terminator_basic() {
        let segments = vec![Segment::new("hello\nworld")];
        let lines = Segment::split_lines_terminator(segments);
        assert_eq!(lines.len(), 2);
        assert!(lines[0].1); // newline was found
        assert!(!lines[1].1); // end of content, no newline
        assert_eq!(&*lines[0].0[0].text, "hello");
        assert_eq!(&*lines[1].0[0].text, "world");
    }

    #[test]
    fn test_split_lines_terminator_trailing_newline() {
        let segments = vec![Segment::new("hello\n")];
        let lines = Segment::split_lines_terminator(segments);
        assert_eq!(lines.len(), 1);
        assert!(lines[0].1);
    }

    // ==================== strip_links tests ====================

    #[test]
    fn test_strip_links() {
        let meta = StyleMeta::with_link("https://example.com");
        let segments = vec![
            Segment::styled_with_meta("link", Style::new().with_bold(true), meta),
            Segment::new("plain"),
        ];
        let result = Segment::strip_links(segments);
        for seg in result.iter() {
            assert!(seg.meta.is_none());
        }
    }

    // ==================== remove_color tests ====================

    #[test]
    fn test_remove_color() {
        let style = Style::new()
            .with_bold(true)
            .with_color(crate::SimpleColor::Standard(1));
        let segments = vec![Segment::styled("hello", style)];
        let result = Segment::remove_color(segments);
        let seg = result.iter().next().unwrap();
        assert_eq!(seg.style.unwrap().bold, Some(true));
        assert_eq!(seg.style.unwrap().color, None);
    }

    // ==================== SegmentLines tests ====================

    #[test]
    fn test_segment_lines_to_segments() {
        let lines = vec![vec![Segment::new("hello")], vec![Segment::new("world")]];
        let sl = SegmentLines::new(lines, true);
        let segs = sl.to_segments();
        // 2 content segments + 2 newlines
        assert_eq!(segs.len(), 4);
    }

    #[test]
    fn test_segment_lines_no_newlines() {
        let lines = vec![vec![Segment::new("hello")], vec![Segment::new("world")]];
        let sl = SegmentLines::new(lines, false);
        let segs = sl.to_segments();
        assert_eq!(segs.len(), 2);
    }

    // ==================== Send + Sync compile-time assertions ====================

    /// Compile-time assertion that Segment is Send + Sync.
    /// This test ensures that if a future field breaks these traits, the build will fail.
    #[test]
    fn test_segment_is_send_sync() {
        fn assert_send<T: Send>() {}
        fn assert_sync<T: Sync>() {}
        assert_send::<Segment>();
        assert_sync::<Segment>();
    }

    /// Compile-time assertion that Segments is Send + Sync.
    #[test]
    fn test_segments_is_send_sync() {
        fn assert_send<T: Send>() {}
        fn assert_sync<T: Sync>() {}
        assert_send::<Segments>();
        assert_sync::<Segments>();
    }
}