rich-rs 1.2.0

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
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
//! Text: rich text with styled spans.
//!
//! Text is the primary way to work with styled content in Rich.
//! It stores plain text with a list of spans that define styled regions.

use std::cmp::Ordering;
use std::collections::BTreeMap;
use std::sync::Arc;

use regex::Regex;

use crate::Renderable;
use crate::cells::cell_len;
use crate::console::{Console, ConsoleOptions, JustifyMethod};
use crate::control::strip_control_codes;
use crate::error::Result;
use crate::markup;
use crate::measure::Measurement;
use crate::segment::{Segment, Segments};
use crate::style::{Style, StyleMeta};

/// A span of styled text within a Text object.
///
/// Spans define a region of text (by character index) and the style to apply.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Span {
    /// Start index (character offset, inclusive).
    pub start: usize,
    /// End index (character offset, exclusive).
    pub end: usize,
    /// Style to apply.
    pub style: Style,
    /// Optional style metadata (hyperlinks, Textual handlers, etc.).
    pub meta: Option<StyleMeta>,
}

impl Span {
    /// Create a new span.
    pub fn new(start: usize, end: usize, style: Style) -> Self {
        Span {
            start,
            end,
            style,
            meta: None,
        }
    }

    /// Create a new span with optional metadata.
    pub fn new_with_meta(start: usize, end: usize, style: Style, meta: Option<StyleMeta>) -> Self {
        Span {
            start,
            end,
            style,
            meta: meta.and_then(|m| if m.is_empty() { None } else { Some(m) }),
        }
    }

    /// Check if the span has any content (end > start).
    pub fn is_empty(&self) -> bool {
        self.end <= self.start
    }

    /// Split a span into two at a given offset.
    ///
    /// If the offset is outside the span, returns `(self, None)`.
    ///
    /// # Arguments
    ///
    /// * `offset` - The character offset at which to split.
    ///
    /// # Returns
    ///
    /// A tuple of (first_span, optional_second_span).
    ///
    /// # Example
    ///
    /// ```
    /// use rich_rs::text::Span;
    /// use rich_rs::Style;
    ///
    /// let span = Span::new(0, 10, Style::new().with_bold(true));
    /// let (first, second) = span.split(5);
    /// assert_eq!(first.start, 0);
    /// assert_eq!(first.end, 5);
    /// assert!(second.is_some());
    /// let second = second.unwrap();
    /// assert_eq!(second.start, 5);
    /// assert_eq!(second.end, 10);
    /// ```
    pub fn split(&self, offset: usize) -> (Span, Option<Span>) {
        if offset < self.start {
            return (self.clone(), None);
        }
        if offset >= self.end {
            return (self.clone(), None);
        }

        let span1 = Span::new_with_meta(
            self.start,
            offset.min(self.end),
            self.style,
            self.meta.clone(),
        );
        let span2 = Span::new_with_meta(span1.end, self.end, self.style, self.meta.clone());
        (span1, Some(span2))
    }

    /// Move the span by a given offset.
    ///
    /// Both start and end are adjusted by adding the offset.
    ///
    /// # Arguments
    ///
    /// * `offset` - The amount to add to start and end (can be negative via wrapping).
    ///
    /// # Returns
    ///
    /// A new Span with adjusted positions.
    pub fn move_by(&self, offset: isize) -> Span {
        let new_start = (self.start as isize + offset).max(0) as usize;
        let new_end = (self.end as isize + offset).max(0) as usize;
        Span::new_with_meta(new_start, new_end, self.style, self.meta.clone())
    }

    /// Crop the span at a given offset.
    ///
    /// If offset is at or beyond the end, returns self unchanged.
    /// Otherwise, returns a span ending at offset.
    ///
    /// # Arguments
    ///
    /// * `offset` - The offset at which to crop.
    ///
    /// # Returns
    ///
    /// A new (possibly smaller) span.
    pub fn right_crop(&self, offset: usize) -> Span {
        if offset >= self.end {
            return self.clone();
        }
        Span::new_with_meta(
            self.start,
            offset.min(self.end),
            self.style,
            self.meta.clone(),
        )
    }

    /// Extend the span by a given number of cells.
    ///
    /// # Arguments
    ///
    /// * `cells` - The number of cells to add to the end.
    ///
    /// # Returns
    ///
    /// A new span with extended end position.
    pub fn extend(&self, cells: usize) -> Span {
        if cells == 0 {
            return self.clone();
        }
        Span::new_with_meta(self.start, self.end + cells, self.style, self.meta.clone())
    }
}

/// A part that can be assembled into Text.
///
/// Used by `Text::assemble()` to accept various input types.
#[derive(Debug, Clone)]
pub enum TextPart {
    /// Plain text without styling.
    Plain(String),
    /// Text with a style.
    Styled(String, Style),
    /// Another Text object.
    Text(Text),
}

impl From<&str> for TextPart {
    fn from(s: &str) -> Self {
        TextPart::Plain(s.to_string())
    }
}

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

impl From<Text> for TextPart {
    fn from(t: Text) -> Self {
        TextPart::Text(t)
    }
}

impl From<(&str, Style)> for TextPart {
    fn from((s, style): (&str, Style)) -> Self {
        TextPart::Styled(s.to_string(), style)
    }
}

impl From<(String, Style)> for TextPart {
    fn from((s, style): (String, Style)) -> Self {
        TextPart::Styled(s, style)
    }
}

/// Rich text with styled spans.
///
/// Text is the primary way to work with styled content in Rich.
/// It stores plain text with a list of spans that define styled regions.
///
/// # Example
///
/// ```
/// use rich_rs::Text;
/// use rich_rs::Style;
///
/// let mut text = Text::plain("Hello, World!");
/// text.stylize(0, 5, Style::new().with_bold(true));
/// text.stylize(7, 12, Style::new().with_italic(true));
/// ```
#[derive(Debug, Clone, Default)]
pub struct Text {
    /// The plain text content.
    text: String,
    /// Styled spans applied to the text.
    spans: Vec<Span>,
    /// Base style for the entire text.
    style: Option<Style>,
    /// Base metadata for the entire text.
    meta: Option<StyleMeta>,
}

impl Text {
    /// Create new empty text.
    pub fn new() -> Self {
        Text::default()
    }

    /// Create text from a plain string.
    pub fn plain(text: impl Into<String>) -> Self {
        Text {
            text: text.into(),
            spans: Vec::new(),
            style: None,
            meta: None,
        }
    }

    /// Create text with a style applied to the entire content.
    ///
    /// Note: Unlike creating Text::plain and then calling stylize(),
    /// this sets the base style which affects the entire text including
    /// any padding added later. The base style is applied as a background
    /// to all spans during rendering.
    pub fn styled(text: impl Into<String>, style: Style) -> Self {
        let text = text.into();
        Text {
            text,
            spans: Vec::new(),
            style: Some(style),
            meta: None,
        }
    }

    /// Create text with a base style and base metadata applied to the entire content.
    pub fn styled_with_meta(text: impl Into<String>, style: Style, meta: StyleMeta) -> Self {
        let text = text.into();
        Text {
            text,
            spans: Vec::new(),
            style: Some(style),
            meta: if meta.is_empty() { None } else { Some(meta) },
        }
    }

    /// Create text from markup string.
    ///
    /// Parses BBCode-like markup (e.g., `[bold red]text[/]`) into styled Text.
    ///
    /// # Arguments
    ///
    /// * `markup` - The markup string to parse.
    /// * `emoji` - Whether to replace emoji codes (`:smile:` -> actual emoji).
    ///
    /// # Returns
    ///
    /// A `Text` object with styled spans, or an error if the markup is invalid.
    ///
    /// # Example
    ///
    /// ```
    /// use rich_rs::Text;
    ///
    /// let text = Text::from_markup("[bold]Hello[/] World", true).unwrap();
    /// assert_eq!(text.plain_text(), "Hello World");
    /// ```
    pub fn from_markup(markup: &str, emoji: bool) -> Result<Text> {
        crate::markup::render(markup, emoji)
    }

    /// Create a Text object from a string containing ANSI escape codes.
    ///
    /// This is a port of Python Rich's `Text.from_ansi`, backed by `AnsiDecoder`.
    /// The decoder is lenient and will ignore unknown / malformed escape sequences.
    ///
    /// Style state may persist across lines, matching Rich behavior.
    pub fn from_ansi(ansi_text: &str) -> Text {
        let mut decoder = crate::ansi::AnsiDecoder::new();
        // Match Python Rich: `Text.from_ansi` constructs a joiner Text with an explicit (possibly empty)
        // base style. In rich-rs, using `Some(NULL_STYLE)` preserves that API-visible base-style
        // without affecting rendering (null styles are ignored when generating spans).
        let joiner = Text::styled("\n", Style::new());
        joiner.join(decoder.decode(ansi_text))
    }

    /// Assemble text from multiple parts.
    ///
    /// Each part can be:
    /// - A plain string (`&str` or `String`)
    /// - A `Text` object
    /// - A tuple of `(text, Style)`
    ///
    /// # Example
    ///
    /// ```
    /// use rich_rs::{Text, TextPart, Style};
    ///
    /// let bold = Style::new().with_bold(true);
    /// let text = Text::assemble([
    ///     TextPart::from("Hello, "),
    ///     TextPart::from(("World", bold)),
    ///     TextPart::from("!"),
    /// ]);
    /// assert_eq!(text.plain_text(), "Hello, World!");
    /// ```
    pub fn assemble<I, P>(parts: I) -> Self
    where
        I: IntoIterator<Item = P>,
        P: Into<TextPart>,
    {
        let mut result = Text::new();

        for part in parts {
            match part.into() {
                TextPart::Plain(s) => {
                    result.append(&s, None);
                }
                TextPart::Styled(s, style) => {
                    result.append(&s, Some(style));
                }
                TextPart::Text(t) => {
                    result.append_text(&t);
                }
            }
        }

        result
    }

    /// Get the plain text content.
    pub fn plain_text(&self) -> &str {
        &self.text
    }

    /// Get the cell width of the text.
    pub fn cell_len(&self) -> usize {
        cell_len(&self.text)
    }

    /// Get the character count.
    pub fn len(&self) -> usize {
        self.text.chars().count()
    }

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

    /// Append text with an optional style.
    pub fn append(&mut self, text: impl Into<String>, style: Option<Style>) {
        let text = text.into();
        let start = self.len();
        let end = start + text.chars().count();

        self.text.push_str(&text);

        if let Some(s) = style {
            self.spans.push(Span::new(start, end, s));
        }
    }

    /// Append another Text object, preserving its spans and base style.
    pub fn append_text(&mut self, other: &Text) {
        let offset = self.len();
        let other_len = other.len();
        self.text.push_str(&other.text);

        // If the other text has a base style/meta, add a span for it.
        // This preserves region-specific base attributes when merging Text objects.
        let other_base_style = other.style.unwrap_or_default();
        let other_base_meta = other.meta.clone().unwrap_or_default();
        if !other_base_style.is_null() || !other_base_meta.is_empty() {
            self.spans.push(Span::new_with_meta(
                offset,
                offset + other_len,
                other_base_style,
                Some(other_base_meta),
            ));
        }

        // Copy and offset spans from the other text
        for span in &other.spans {
            self.spans.push(Span::new_with_meta(
                span.start + offset,
                span.end + offset,
                span.style,
                span.meta.clone(),
            ));
        }
    }

    /// Apply a style to a range of the text (legacy API, kept for compatibility).
    ///
    /// Spans are clamped to the text bounds. Out-of-bounds or empty spans are ignored.
    /// For the enhanced version with negative index support, use `stylize_range`.
    pub fn stylize(&mut self, start: usize, end: usize, style: Style) {
        let length = self.len();
        if start >= length || end <= start {
            return;
        }
        let clamped_end = end.min(length);
        self.spans.push(Span::new(start, clamped_end, style));
    }

    /// Apply a style to a range of the text with negative index support.
    ///
    /// Negative indices count from the end of the text (-1 is the last character).
    /// If `end` is `None`, styles to the end of the text.
    ///
    /// # Arguments
    ///
    /// * `style` - The style to apply.
    /// * `start` - Start offset (negative indexing supported). Defaults to 0.
    /// * `end` - End offset (negative indexing supported), or `None` for end of text.
    ///
    /// # Example
    ///
    /// ```
    /// use rich_rs::{Text, Style};
    ///
    /// let mut text = Text::plain("Hello World");
    /// // Style the last 5 characters
    /// text.stylize_range(Style::new().with_bold(true), -5, None);
    /// ```
    pub fn stylize_range(&mut self, style: Style, start: isize, end: Option<isize>) {
        if style.is_null() {
            return;
        }

        let length = self.len() as isize;

        // Handle negative indices
        let start = if start < 0 {
            (length + start).max(0) as usize
        } else {
            start as usize
        };

        let end = match end {
            None => self.len(),
            Some(e) if e < 0 => (length + e).max(0) as usize,
            Some(e) => e as usize,
        };

        // Validate range
        if start >= self.len() || end <= start {
            return;
        }

        self.spans
            .push(Span::new(start, end.min(self.len()), style));
    }

    /// Apply a style to the text, inserting at the beginning of the spans list.
    ///
    /// Styles applied with `stylize_before` have lower priority than existing styles.
    /// This is useful for adding a base style that existing styles can override.
    ///
    /// # Arguments
    ///
    /// * `style` - The style to apply.
    /// * `start` - Start offset (negative indexing supported). Defaults to 0.
    /// * `end` - End offset (negative indexing supported), or `None` for end of text.
    pub fn stylize_before(&mut self, style: Style, start: isize, end: Option<isize>) {
        if style.is_null() {
            return;
        }

        let length = self.len() as isize;

        // Handle negative indices
        let start = if start < 0 {
            (length + start).max(0) as usize
        } else {
            start as usize
        };

        let end = match end {
            None => self.len(),
            Some(e) if e < 0 => (length + e).max(0) as usize,
            Some(e) => e as usize,
        };

        // Validate range
        if start >= self.len() || end <= start {
            return;
        }

        // Insert at the beginning for lower priority
        self.spans
            .insert(0, Span::new(start, end.min(self.len()), style));
    }

    /// Apply metadata to the text (or a range), using a metadata-only span.
    ///
    /// Negative indices count from the end of the text (-1 is the last character).
    /// If `end` is `None`, metadata is applied to the end of the text.
    pub fn apply_meta(
        &mut self,
        meta: BTreeMap<String, crate::style::MetaValue>,
        start: isize,
        end: Option<isize>,
    ) {
        if meta.is_empty() {
            return;
        }

        let length = self.len() as isize;

        let start = if start < 0 {
            (length + start).max(0) as usize
        } else {
            start as usize
        };

        let end = match end {
            None => self.len(),
            Some(e) if e < 0 => (length + e).max(0) as usize,
            Some(e) => e as usize,
        };

        if start >= self.len() || end <= start {
            return;
        }

        let meta = StyleMeta {
            link: None,
            link_id: None,
            meta: Some(Arc::new(meta)),
        };

        self.spans.push(Span::new_with_meta(
            start,
            end.min(self.len()),
            Style::new(),
            Some(meta),
        ));
    }

    /// Highlight text matching a regular expression.
    ///
    /// # Arguments
    ///
    /// * `pattern` - A regular expression pattern.
    /// * `style` - The style to apply to matches.
    ///
    /// # Returns
    ///
    /// The number of matches found.
    ///
    /// # Example
    ///
    /// ```
    /// use rich_rs::{Text, Style};
    ///
    /// let mut text = Text::plain("foo bar foo baz");
    /// let count = text.highlight_regex(r"foo", Style::new().with_bold(true));
    /// assert_eq!(count, 2);
    /// ```
    pub fn highlight_regex(&mut self, pattern: &str, style: Style) -> usize {
        let re = match Regex::new(pattern) {
            Ok(r) => r,
            Err(_) => return 0,
        };

        let mut count = 0;
        let plain = self.plain_text().to_string();

        for mat in re.find_iter(&plain) {
            // Convert byte offsets to character offsets
            let start_char = plain[..mat.start()].chars().count();
            let end_char = start_char + plain[mat.start()..mat.end()].chars().count();

            if end_char > start_char {
                self.spans.push(Span::new(start_char, end_char, style));
                count += 1;
            }
        }

        count
    }

    /// Highlight occurrences of specific words.
    ///
    /// # Arguments
    ///
    /// * `words` - Words to highlight.
    /// * `style` - The style to apply.
    /// * `case_sensitive` - Whether matching should be case-sensitive.
    ///
    /// # Returns
    ///
    /// The number of words highlighted.
    ///
    /// # Example
    ///
    /// ```
    /// use rich_rs::{Text, Style};
    ///
    /// let mut text = Text::plain("Hello World Hello");
    /// let count = text.highlight_words(&["Hello"], Style::new().with_bold(true), true);
    /// assert_eq!(count, 2);
    /// ```
    pub fn highlight_words(&mut self, words: &[&str], style: Style, case_sensitive: bool) -> usize {
        if words.is_empty() {
            return 0;
        }

        // Build regex pattern from words
        let pattern = words
            .iter()
            .map(|w| regex::escape(w))
            .collect::<Vec<_>>()
            .join("|");

        let pattern = if case_sensitive {
            pattern
        } else {
            format!("(?i){}", pattern)
        };

        let re = match Regex::new(&pattern) {
            Ok(r) => r,
            Err(_) => return 0,
        };

        let mut count = 0;
        let plain = self.plain_text().to_string();

        for mat in re.find_iter(&plain) {
            // Convert byte offsets to character offsets
            let start_char = plain[..mat.start()].chars().count();
            let end_char = start_char + plain[mat.start()..mat.end()].chars().count();

            if end_char > start_char {
                self.spans.push(Span::new(start_char, end_char, style));
                count += 1;
            }
        }

        count
    }

    /// Divide text at multiple offsets.
    ///
    /// This is a critical algorithm for text wrapping. It splits the text at
    /// the given character offsets and correctly distributes spans across
    /// the resulting Text objects.
    ///
    /// # Arguments
    ///
    /// * `offsets` - Character offsets at which to divide the text.
    ///
    /// # Returns
    ///
    /// A vector of Text objects, one for each division.
    ///
    /// # Example
    ///
    /// ```
    /// use rich_rs::Text;
    ///
    /// let text = Text::plain("Hello World!");
    /// let divided = text.divide([5, 6]);
    /// assert_eq!(divided.len(), 3);
    /// assert_eq!(divided[0].plain_text(), "Hello");
    /// assert_eq!(divided[1].plain_text(), " ");
    /// assert_eq!(divided[2].plain_text(), "World!");
    /// ```
    pub fn divide(&self, offsets: impl IntoIterator<Item = usize>) -> Vec<Text> {
        let plain = self.plain_text();
        let text_length = self.len();

        // Collect, sort, clamp, and deduplicate offsets
        let mut offsets: Vec<usize> = offsets
            .into_iter()
            .map(|o| o.min(text_length)) // Clamp to text length
            .collect();
        offsets.sort_unstable();
        offsets.dedup();

        // Filter out 0 and text_length since we add them below
        let offsets: Vec<usize> = offsets
            .into_iter()
            .filter(|&o| o > 0 && o < text_length)
            .collect();

        if offsets.is_empty() {
            return vec![self.clone()];
        }

        // Build line ranges: [0..offset[0]], [offset[0]..offset[1]], ..., [last_offset..len]
        let mut divide_offsets = vec![0];
        divide_offsets.extend(offsets.iter().copied());
        divide_offsets.push(text_length);

        // Create ranges from consecutive offset pairs
        let line_ranges: Vec<(usize, usize)> = divide_offsets
            .windows(2)
            .map(|w| (w[0], w[1]))
            .filter(|(start, end)| start < end) // Skip empty ranges
            .collect();

        if line_ranges.is_empty() {
            return vec![self.clone()];
        }

        // Extract substrings for each range (character-based slicing)
        let chars: Vec<char> = plain.chars().collect();
        let new_lines: Vec<Text> = line_ranges
            .iter()
            .map(|&(start, end)| {
                let clamped_end = end.min(chars.len());
                let clamped_start = start.min(clamped_end);
                let substring: String = chars[clamped_start..clamped_end].iter().collect();
                Text {
                    text: substring,
                    spans: Vec::new(),
                    style: self.style,
                    meta: self.meta.clone(),
                }
            })
            .collect();

        // If no spans, we're done
        if self.spans.is_empty() {
            return new_lines;
        }

        // Distribute spans to the appropriate lines
        let mut result = new_lines;
        let line_count = line_ranges.len();

        for span in &self.spans {
            // Skip invalid or out-of-bounds spans
            if span.start >= span.end || span.start >= text_length {
                continue;
            }
            let span_start = span.start;
            let span_end = span.end.min(text_length);

            // Binary search to find the starting line for this span
            let mut lower_bound = 0;
            let mut upper_bound = line_count;
            let mut start_line_no = (lower_bound + upper_bound) / 2;

            loop {
                if start_line_no >= line_count {
                    break;
                }
                let (line_start, line_end) = line_ranges[start_line_no];
                if span_start < line_start {
                    if start_line_no == 0 {
                        break;
                    }
                    upper_bound = start_line_no - 1;
                } else if span_start > line_end {
                    lower_bound = start_line_no + 1;
                } else {
                    break;
                }
                start_line_no = (lower_bound + upper_bound) / 2;
            }

            // Find the ending line for this span
            let end_line_no = if span_end < line_ranges[start_line_no].1 {
                start_line_no
            } else {
                lower_bound = start_line_no;
                upper_bound = line_count;
                let mut end_line_no = (lower_bound + upper_bound) / 2;

                loop {
                    if end_line_no >= line_count {
                        end_line_no = line_count - 1;
                        break;
                    }
                    let (line_start, line_end) = line_ranges[end_line_no];
                    if span_end < line_start {
                        if end_line_no == 0 {
                            break;
                        }
                        upper_bound = end_line_no - 1;
                    } else if span_end > line_end {
                        lower_bound = end_line_no + 1;
                    } else {
                        break;
                    }
                    end_line_no = (lower_bound + upper_bound) / 2;
                }
                end_line_no
            };

            // Add span to all lines it covers
            for line_no in start_line_no..=end_line_no.min(line_count - 1) {
                let (line_start, line_end) = line_ranges[line_no];
                let new_start = span_start.saturating_sub(line_start);
                let new_end = span_end
                    .saturating_sub(line_start)
                    .min(line_end - line_start);

                if new_end > new_start {
                    result[line_no].spans.push(Span::new_with_meta(
                        new_start,
                        new_end,
                        span.style,
                        span.meta.clone(),
                    ));
                }
            }
        }

        result
    }

    /// Get the spans.
    pub fn spans(&self) -> &[Span] {
        &self.spans
    }

    /// Get mutable access to spans.
    pub fn spans_mut(&mut self) -> &mut Vec<Span> {
        &mut self.spans
    }

    /// Get the base style.
    pub fn base_style(&self) -> Option<Style> {
        self.style
    }

    /// Set the base style.
    pub fn set_base_style(&mut self, style: Option<Style>) {
        self.style = style;
    }

    /// Create a copy of this text.
    pub fn copy(&self) -> Text {
        self.clone()
    }

    /// Create a blank copy with same metadata but no content.
    pub fn blank_copy(&self, plain: &str) -> Text {
        Text {
            text: plain.to_string(),
            spans: Vec::new(),
            style: self.style,
            meta: self.meta.clone(),
        }
    }

    /// Join multiple Text objects with this text as separator.
    pub fn join<I>(&self, texts: I) -> Text
    where
        I: IntoIterator<Item = Text>,
    {
        let mut result = self.blank_copy("");
        let mut first = true;

        for text in texts {
            if !first && !self.is_empty() {
                result.append_text(self);
            }
            result.append_text(&text);
            first = false;
        }

        result
    }

    // ========================================================================
    // Padding and alignment methods
    // ========================================================================

    /// Pad text on the right to reach target cell width.
    ///
    /// Returns a new Text with spaces appended to reach the target width.
    /// If the text is already wider than width, returns a clone unchanged.
    ///
    /// # Example
    ///
    /// ```
    /// use rich_rs::Text;
    ///
    /// let text = Text::plain("hello");
    /// let padded = text.pad_right(10);
    /// assert_eq!(padded.plain_text(), "hello     ");
    /// assert_eq!(padded.cell_len(), 10);
    /// ```
    pub fn pad_right(&self, width: usize) -> Text {
        let current_width = self.cell_len();
        if current_width >= width {
            return self.clone();
        }

        let mut result = self.clone();
        let spaces = " ".repeat(width - current_width);
        result.text.push_str(&spaces);
        result
    }

    /// Pad text on the left to reach target cell width.
    ///
    /// Returns a new Text with spaces prepended to reach the target width.
    /// Existing spans are shifted by the padding amount.
    ///
    /// # Example
    ///
    /// ```
    /// use rich_rs::Text;
    ///
    /// let text = Text::plain("hello");
    /// let padded = text.pad_left(10);
    /// assert_eq!(padded.plain_text(), "     hello");
    /// assert_eq!(padded.cell_len(), 10);
    /// ```
    pub fn pad_left(&self, width: usize) -> Text {
        let current_width = self.cell_len();
        if current_width >= width {
            return self.clone();
        }

        let pad_count = width - current_width;
        let spaces = " ".repeat(pad_count);

        // Shift all spans by the padding amount
        let shifted_spans: Vec<Span> = self
            .spans
            .iter()
            .map(|span| {
                Span::new_with_meta(
                    span.start + pad_count,
                    span.end + pad_count,
                    span.style,
                    span.meta.clone(),
                )
            })
            .collect();

        Text {
            text: format!("{}{}", spaces, self.text),
            spans: shifted_spans,
            style: self.style,
            meta: self.meta.clone(),
        }
    }

    /// Center text within a given cell width.
    ///
    /// Returns a new Text padded on both sides to center within the width.
    /// Left padding is (width - cell_len) / 2, right padding fills the rest.
    ///
    /// # Example
    ///
    /// ```
    /// use rich_rs::Text;
    ///
    /// let text = Text::plain("hi");
    /// let centered = text.center(6);
    /// assert_eq!(centered.plain_text(), "  hi  ");
    /// assert_eq!(centered.cell_len(), 6);
    /// ```
    pub fn center(&self, width: usize) -> Text {
        let current_width = self.cell_len();
        if current_width >= width {
            return self.clone();
        }

        let total_pad = width - current_width;
        let left_pad = total_pad / 2;
        let right_pad = total_pad - left_pad;

        let left_spaces = " ".repeat(left_pad);
        let right_spaces = " ".repeat(right_pad);

        // Shift all spans by the left padding amount
        let shifted_spans: Vec<Span> = self
            .spans
            .iter()
            .map(|span| {
                Span::new_with_meta(
                    span.start + left_pad,
                    span.end + left_pad,
                    span.style,
                    span.meta.clone(),
                )
            })
            .collect();

        Text {
            text: format!("{}{}{}", left_spaces, self.text, right_spaces),
            spans: shifted_spans,
            style: self.style,
            meta: self.meta.clone(),
        }
    }

    /// Expand tabs to spaces.
    ///
    /// Returns a new Text with tabs replaced by spaces, aligning to tab stops.
    ///
    /// # Arguments
    ///
    /// * `tab_size` - The tab stop width (default 8).
    ///
    /// # Example
    ///
    /// ```
    /// use rich_rs::Text;
    ///
    /// let text = Text::plain("a\tb");
    /// let expanded = text.expand_tabs(4);
    /// assert_eq!(expanded.plain_text(), "a   b");
    /// ```
    pub fn expand_tabs(&self, tab_size: usize) -> Text {
        if !self.text.contains('\t') {
            return self.clone();
        }

        let tab_size = if tab_size == 0 { 8 } else { tab_size };

        let mut result_text = String::new();
        let mut result_spans: Vec<Span> = Vec::new();
        let mut cell_position: usize = 0;

        let chars: Vec<char> = self.text.chars().collect();

        for &c in &chars {
            if c == '\t' {
                // Calculate spaces needed to reach next tab stop
                let tab_remainder = cell_position % tab_size;
                let spaces = if tab_remainder == 0 {
                    tab_size
                } else {
                    tab_size - tab_remainder
                };

                result_text.push_str(&" ".repeat(spaces));
                cell_position += spaces;
            } else if c == '\n' {
                result_text.push(c);
                cell_position = 0; // Reset on newline
            } else {
                result_text.push(c);
                cell_position += crate::cells::char_width(c);
            }
        }

        // Rebuild spans with adjusted positions
        // We need to map old char offsets to new char offsets
        let mut old_to_new: Vec<usize> = Vec::with_capacity(chars.len() + 1);
        old_to_new.push(0);

        let mut new_pos: usize = 0;
        cell_position = 0;

        for &c in &chars {
            if c == '\t' {
                let tab_remainder = cell_position % tab_size;
                let spaces = if tab_remainder == 0 {
                    tab_size
                } else {
                    tab_size - tab_remainder
                };
                new_pos += spaces;
                cell_position += spaces;
            } else if c == '\n' {
                new_pos += 1;
                cell_position = 0;
            } else {
                new_pos += 1;
                cell_position += crate::cells::char_width(c);
            }
            old_to_new.push(new_pos);
        }

        for span in &self.spans {
            let new_start = if span.start < old_to_new.len() {
                old_to_new[span.start]
            } else {
                old_to_new.last().copied().unwrap_or(0)
            };
            let new_end = if span.end < old_to_new.len() {
                old_to_new[span.end]
            } else {
                old_to_new.last().copied().unwrap_or(0)
            };

            if new_end > new_start {
                result_spans.push(Span::new_with_meta(
                    new_start,
                    new_end,
                    span.style,
                    span.meta.clone(),
                ));
            }
        }

        Text {
            text: result_text,
            spans: result_spans,
            style: self.style,
            meta: self.meta.clone(),
        }
    }

    /// Add indentation guides to the text.
    ///
    /// This adds visual indentation guides (like vertical lines) to show
    /// the indentation level of each line.
    ///
    /// # Arguments
    ///
    /// * `indent_size` - The number of spaces per indentation level.
    /// * `style` - Optional style for the guide characters.
    ///
    /// # Returns
    ///
    /// A new Text with indentation guides added.
    pub fn with_indent_guides(self, indent_size: usize, style: Option<crate::Style>) -> Text {
        let guide_style = style.unwrap_or_else(|| {
            Style::new()
                .with_dim(true)
                .with_color(crate::color::SimpleColor::Standard(2))
        });
        self.with_indent_guides_full(Some(indent_size), "│", guide_style)
    }

    /// Strip trailing whitespace from the text.
    ///
    /// Returns a new Text with trailing whitespace removed.
    /// Spans are adjusted to fit within the new text bounds.
    pub fn rstrip(&self) -> Text {
        let trimmed = self.text.trim_end();
        let new_len = trimmed.chars().count();

        let adjusted_spans: Vec<Span> = self
            .spans
            .iter()
            .filter_map(|span| {
                if span.start >= new_len {
                    None
                } else {
                    Some(Span::new_with_meta(
                        span.start,
                        span.end.min(new_len),
                        span.style,
                        span.meta.clone(),
                    ))
                }
            })
            .filter(|span| !span.is_empty())
            .collect();

        Text {
            text: trimmed.to_string(),
            spans: adjusted_spans,
            style: self.style,
            meta: self.meta.clone(),
        }
    }

    /// Remove trailing whitespace beyond a certain width.
    ///
    /// Only removes whitespace characters that extend beyond the target size.
    /// This is used after wrapping to clean up trailing spaces on lines.
    ///
    /// # Arguments
    ///
    /// * `size` - The desired cell width target.
    pub fn rstrip_end(&self, size: usize) -> Text {
        let text_width = self.cell_len();
        if text_width <= size {
            return self.clone();
        }

        let excess = text_width - size;

        // Find how much trailing whitespace we have (in cell width)
        let mut trailing_ws_width = 0;
        for c in self.text.chars().rev() {
            if c.is_whitespace() {
                trailing_ws_width += crate::cells::char_width(c);
            } else {
                break;
            }
        }

        if trailing_ws_width == 0 {
            return self.clone();
        }

        // Remove trailing whitespace until we've removed min(trailing_ws_width, excess) cells
        let cells_to_remove = trailing_ws_width.min(excess);

        // Build new text by removing trailing whitespace
        let mut chars: Vec<char> = self.text.chars().collect();
        let mut removed = 0;
        while !chars.is_empty() && removed < cells_to_remove {
            if let Some(&c) = chars.last() {
                if c.is_whitespace() {
                    removed += crate::cells::char_width(c);
                    chars.pop();
                } else {
                    break;
                }
            } else {
                break;
            }
        }

        let new_text: String = chars.iter().collect();
        let new_len = chars.len();

        let adjusted_spans: Vec<Span> = self
            .spans
            .iter()
            .filter_map(|span| {
                if span.start >= new_len {
                    None
                } else {
                    Some(Span::new_with_meta(
                        span.start,
                        span.end.min(new_len),
                        span.style,
                        span.meta.clone(),
                    ))
                }
            })
            .filter(|span| !span.is_empty())
            .collect();

        Text {
            text: new_text,
            spans: adjusted_spans,
            style: self.style,
            meta: self.meta.clone(),
        }
    }

    /// Truncate text to fit within a cell width.
    ///
    /// # Arguments
    ///
    /// * `max_width` - Maximum cell width.
    /// * `overflow` - How to handle overflow (Fold, Crop, Ellipsis).
    /// * `pad` - If true, pad with spaces if text is shorter than max_width.
    pub fn truncate(
        &self,
        max_width: usize,
        overflow: crate::console::OverflowMethod,
        pad: bool,
    ) -> Text {
        use crate::cells::set_cell_size;
        use crate::console::OverflowMethod;

        if overflow == OverflowMethod::Ignore {
            if pad && self.cell_len() < max_width {
                return self.pad_right(max_width);
            }
            return self.clone();
        }

        let current_width = self.cell_len();

        if current_width <= max_width {
            if pad {
                return self.pad_right(max_width);
            }
            return self.clone();
        }

        // Truncate the text
        let new_plain = if overflow == OverflowMethod::Ellipsis && max_width > 0 {
            let truncated = set_cell_size(&self.text, max_width.saturating_sub(1));
            format!("{}…", truncated)
        } else {
            set_cell_size(&self.text, max_width)
        };

        let new_char_len = new_plain.chars().count();

        // Adjust spans
        let adjusted_spans: Vec<Span> = self
            .spans
            .iter()
            .filter_map(|span| {
                if span.start >= new_char_len {
                    None
                } else {
                    Some(Span::new_with_meta(
                        span.start,
                        span.end.min(new_char_len),
                        span.style,
                        span.meta.clone(),
                    ))
                }
            })
            .filter(|span| !span.is_empty())
            .collect();

        Text {
            text: new_plain,
            spans: adjusted_spans,
            style: self.style,
            meta: self.meta.clone(),
        }
    }

    /// Split text on a separator into a list of Text objects.
    ///
    /// # Arguments
    ///
    /// * `separator` - The string to split on.
    /// * `include_separator` - If true, include the separator at the end of each line.
    /// * `allow_blank` - If true, include a blank line if text ends with separator.
    ///
    /// # Returns
    ///
    /// A vector of Text objects, one per split segment.
    pub fn split(&self, separator: &str, include_separator: bool, allow_blank: bool) -> Vec<Text> {
        if separator.is_empty() {
            return vec![self.clone()];
        }

        if !self.text.contains(separator) {
            return vec![self.clone()];
        }

        // Find all separator positions (ranges)
        let chars: Vec<char> = self.text.chars().collect();
        let sep_chars: Vec<char> = separator.chars().collect();
        let sep_len = sep_chars.len();
        let text_len = chars.len();

        // Collect separator ranges (start, end)
        let mut sep_ranges: Vec<(usize, usize)> = Vec::new();
        let mut i = 0;
        while i + sep_len <= text_len {
            if &chars[i..i + sep_len] == sep_chars.as_slice() {
                sep_ranges.push((i, i + sep_len));
                i += sep_len;
            } else {
                i += 1;
            }
        }

        if sep_ranges.is_empty() {
            return vec![self.clone()];
        }

        // Build segments by extracting text between separators
        let mut result: Vec<Text> = Vec::new();
        let mut pos = 0;

        for (sep_start, sep_end) in &sep_ranges {
            // Extract segment before separator
            if include_separator {
                // Include everything from pos up to and including separator
                if *sep_end > pos {
                    let segment_text: String = chars[pos..*sep_end].iter().collect();
                    result.push(self.slice_at_offsets(pos, *sep_end, &segment_text));
                }
            } else {
                // Only include the part before the separator
                let segment_text: String = chars[pos..*sep_start].iter().collect();
                if allow_blank || !segment_text.is_empty() {
                    result.push(self.slice_at_offsets(pos, *sep_start, &segment_text));
                }
            }
            pos = *sep_end;
        }

        // Handle the trailing segment after the last separator
        if pos < text_len {
            let segment_text: String = chars[pos..].iter().collect();
            if allow_blank || !segment_text.is_empty() {
                result.push(self.slice_at_offsets(pos, text_len, &segment_text));
            }
        } else if include_separator {
            // Text ends with separator and include_separator is true
            // Add trailing empty segment only if allow_blank
            if allow_blank {
                result.push(self.blank_copy(""));
            }
        } else {
            // Text ends with separator and include_separator is false
            // Add trailing empty segment only if allow_blank
            if allow_blank {
                result.push(self.blank_copy(""));
            }
        }

        result
    }

    /// Helper to create a slice with adjusted spans.
    fn slice_at_offsets(&self, start: usize, end: usize, text: &str) -> Text {
        let adjusted_spans: Vec<Span> = self
            .spans
            .iter()
            .filter_map(|span| {
                if span.end <= start || span.start >= end {
                    None
                } else {
                    let new_start = span.start.saturating_sub(start);
                    let new_end = span.end.min(end).saturating_sub(start);
                    if new_start < new_end {
                        Some(Span::new_with_meta(
                            new_start,
                            new_end,
                            span.style,
                            span.meta.clone(),
                        ))
                    } else {
                        None
                    }
                }
            })
            .collect();

        Text {
            text: text.to_string(),
            spans: adjusted_spans,
            style: self.style,
            meta: self.meta.clone(),
        }
    }

    // ========================================================================
    // Full justification helper
    // ========================================================================

    /// Justify text to fill width by expanding spaces between words.
    ///
    /// Used for "full" justification. This expands spaces between words
    /// to make the text fill the entire width.
    fn justify_full(&self, width: usize) -> Text {
        let current_width = self.cell_len();
        if current_width >= width {
            return self.clone();
        }

        // Split into words on spaces.
        // Note: Python Rich uses `split(" ")`, which preserves empty tokens for
        // consecutive spaces. Our split currently drops empty segments unless
        // `allow_blank` is true; this is sufficient for the demo content which
        // uses single spaces between words.
        let words = self.split(" ", false, false);
        if words.len() <= 1 {
            // Single word or empty - can't justify, just pad right
            return self.pad_right(width);
        }

        // Calculate total word width and number of gaps
        let words_width: usize = words.iter().map(|w| w.cell_len()).sum();
        let num_gaps = words.len().saturating_sub(1);
        if num_gaps == 0 {
            return self.pad_right(width);
        }

        // Distribute spaces to match Python Rich:
        // start with 1 space per gap, then add extra spaces from right-to-left.
        let mut spaces: Vec<usize> = vec![1; num_gaps];
        let mut num_spaces = num_gaps;
        let mut index = 0usize;
        while words_width + num_spaces < width {
            let pos = num_gaps.saturating_sub(index).saturating_sub(1);
            spaces[pos] += 1;
            num_spaces += 1;
            index = (index + 1) % num_gaps;
        }

        let mut result = Text::new();
        result.style = self.style;

        for (i, word) in words.iter().enumerate() {
            result.append_text(word);

            if i < num_gaps {
                // Add spaces between words
                result.append(" ".repeat(spaces[i]), None);
            }
        }

        result
    }

    // ========================================================================
    // Wrap method
    // ========================================================================

    /// Wrap text to fit within a given width.
    ///
    /// This method word-wraps the text to fit within the specified cell width,
    /// applying justification and handling overflow as specified.
    ///
    /// # Arguments
    ///
    /// * `width` - Maximum width in cells.
    /// * `justify` - Text justification (None for no justification).
    /// * `overflow` - How to handle words longer than width.
    /// * `tab_size` - Tab stop width (default 8).
    /// * `no_wrap` - If true, don't wrap (just return self).
    ///
    /// # Returns
    ///
    /// A vector of Text objects, one per wrapped line.
    ///
    /// # Example
    ///
    /// ```
    /// use rich_rs::{Text, OverflowMethod};
    ///
    /// let text = Text::plain("hello world this is a test");
    /// let lines = text.wrap(10, None, Some(OverflowMethod::Fold), 8, false);
    /// assert!(lines.len() >= 3);
    /// ```
    pub fn wrap(
        &self,
        width: usize,
        justify: Option<crate::console::JustifyMethod>,
        overflow: Option<crate::console::OverflowMethod>,
        tab_size: usize,
        no_wrap: bool,
    ) -> Vec<Text> {
        use crate::console::{JustifyMethod, OverflowMethod};
        use crate::wrap::divide_line;

        let wrap_justify = justify.unwrap_or(JustifyMethod::Default);
        let wrap_overflow = overflow.unwrap_or(OverflowMethod::Fold);

        // If overflow is Ignore, treat as no_wrap
        let no_wrap = no_wrap || wrap_overflow == OverflowMethod::Ignore;

        let mut all_lines: Vec<Text> = Vec::new();

        // Split on existing newlines first
        let source_lines = self.split("\n", false, true);

        for line in source_lines {
            // Expand tabs
            let line = if line.plain_text().contains('\t') {
                line.expand_tabs(tab_size)
            } else {
                line
            };

            let wrapped_lines = if no_wrap {
                vec![line.clone()]
            } else {
                // Get break positions using divide_line
                let fold = wrap_overflow == OverflowMethod::Fold;
                let offsets = divide_line(line.plain_text(), width, fold);

                if offsets.is_empty() {
                    vec![line.clone()]
                } else {
                    // Convert byte offsets to character offsets
                    let char_offsets: Vec<usize> = offsets
                        .iter()
                        .map(|&byte_offset| line.plain_text()[..byte_offset].chars().count())
                        .collect();
                    line.divide(char_offsets)
                }
            };

            // Process each wrapped line
            for wrapped_line in wrapped_lines {
                all_lines.push(wrapped_line);
            }
        }

        // Apply post-processing: rstrip_end, justification, truncation
        let num_lines = all_lines.len();
        for (i, wrapped_line) in all_lines.iter_mut().enumerate() {
            let is_last_line = i == num_lines - 1;

            // Strip trailing whitespace beyond width (only if wrapping)
            if !no_wrap {
                *wrapped_line = wrapped_line.rstrip_end(width);
            }

            // Apply justification
            *wrapped_line = match wrap_justify {
                JustifyMethod::Left => wrapped_line.pad_right(width),
                JustifyMethod::Right => {
                    let stripped = wrapped_line.rstrip();
                    stripped.pad_left(width)
                }
                JustifyMethod::Center => {
                    let stripped = wrapped_line.rstrip();
                    stripped.center(width)
                }
                JustifyMethod::Full => {
                    // Full justification - last line should be left-aligned
                    if is_last_line {
                        wrapped_line.rstrip().pad_right(width)
                    } else {
                        wrapped_line.justify_full(width)
                    }
                }
                JustifyMethod::Default => wrapped_line.clone(),
            };

            // Truncate if needed (but not for no_wrap/ignore)
            if !no_wrap {
                *wrapped_line = wrapped_line.truncate(width, wrap_overflow, false);
            }
        }

        all_lines
    }
}

// ========================================================================
// Additional parity methods
// ========================================================================

impl Text {
    /// Return a sub-Text from character offsets `start..end` with correctly adjusted spans.
    ///
    /// This is the equivalent of Python's `text[start:end]`. Spans that partially overlap
    /// the range are clipped. Spans fully outside are dropped.
    pub fn slice(&self, start: usize, end: usize) -> Text {
        let text_len = self.len();
        let start = start.min(text_len);
        let end = end.min(text_len);
        if start >= end {
            return self.blank_copy("");
        }
        let lines = self.divide([start, end]);
        // divide([start, end]) returns up to 3 segments: [0..start], [start..end], [end..len]
        // We want the middle one (index 1), or the first one if start==0.
        if start == 0 {
            lines
                .into_iter()
                .next()
                .unwrap_or_else(|| self.blank_copy(""))
        } else if lines.len() > 1 {
            lines
                .into_iter()
                .nth(1)
                .unwrap_or_else(|| self.blank_copy(""))
        } else {
            self.blank_copy("")
        }
    }

    /// Align text within width: left (pad right), center (pad both sides), right (pad left),
    /// full (distribute spaces between words).
    pub fn align(&mut self, align: JustifyMethod, width: usize) {
        let current_width = self.cell_len();
        if current_width >= width {
            *self = self.truncate(width, crate::console::OverflowMethod::Crop, false);
            return;
        }
        let excess_space = width - current_width;
        if excess_space == 0 {
            return;
        }
        match align {
            JustifyMethod::Left | JustifyMethod::Default => {
                *self = self.pad_right(width);
            }
            JustifyMethod::Center => {
                *self = self.center(width);
            }
            JustifyMethod::Right => {
                *self = self.pad_left(width);
            }
            JustifyMethod::Full => {
                *self = self.justify_full(width);
            }
        }
    }

    /// Check if the plain text contains a substring.
    pub fn contains(&self, text: &str) -> bool {
        self.text.contains(text)
    }

    /// Reconstruct a markup string from the styled text.
    ///
    /// For each span, wraps the text range in `[style]...[/style]` tags.
    pub fn to_markup(&self) -> String {
        let plain = &self.text;
        if self.spans.is_empty() && self.style.is_none_or(|s| s.is_null()) {
            return markup::escape(plain);
        }

        // Build events: (offset, is_closing, style_string)
        let mut events: Vec<(usize, bool, String)> = Vec::new();

        // Base style
        if let Some(style) = self.style {
            if !style.is_null() {
                let style_str = style.to_markup_string();
                if !style_str.is_empty() {
                    events.push((0, false, style_str.clone()));
                    events.push((self.len(), true, style_str));
                }
            }
        }

        // Span styles
        for span in &self.spans {
            let style_str = span.style.to_markup_string();
            if !style_str.is_empty() {
                events.push((span.start, false, style_str.clone()));
                events.push((span.end, true, style_str));
            }
        }

        // Sort by offset, then closings before openings at same position
        events.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.cmp(&b.1)));

        let mut output = String::new();
        let chars: Vec<char> = plain.chars().collect();
        let mut position = 0;

        for (offset, closing, style_str) in &events {
            let offset = (*offset).min(chars.len());
            if offset > position {
                let text_slice: String = chars[position..offset].iter().collect();
                output.push_str(&markup::escape(&text_slice));
                position = offset;
            }
            if *closing {
                output.push_str(&format!("[/{}]", style_str));
            } else {
                output.push_str(&format!("[{}]", style_str));
            }
        }

        // Remaining text
        if position < chars.len() {
            let text_slice: String = chars[position..].iter().collect();
            output.push_str(&markup::escape(&text_slice));
        }

        output
    }

    /// Get the combined style at a specific character offset by combining all overlapping spans.
    pub fn get_style_at_offset(&self, offset: usize) -> Style {
        let mut style = self.style.unwrap_or_default();
        for span in &self.spans {
            if span.start <= offset && offset < span.end {
                style = style.combine(&span.style);
            }
        }
        style
    }

    /// Truncate or pad (with spaces) to exact character length.
    pub fn set_length(&mut self, length: usize) {
        let current = self.len();
        match current.cmp(&length) {
            Ordering::Less => {
                // Pad right
                *self = self.pad_right(length);
            }
            Ordering::Greater => {
                // Right crop
                self.right_crop(current - length);
            }
            Ordering::Equal => {}
        }
    }

    /// Remove `amount` characters from the right side.
    pub fn right_crop(&mut self, amount: usize) {
        if amount == 0 {
            return;
        }
        let chars: Vec<char> = self.text.chars().collect();
        if amount >= chars.len() {
            self.text.clear();
            self.spans.clear();
            return;
        }
        let new_len = chars.len() - amount;
        self.text = chars[..new_len].iter().collect();
        self.spans = self
            .spans
            .iter()
            .filter(|span| span.start < new_len)
            .map(|span| {
                if span.end <= new_len {
                    span.clone()
                } else {
                    Span::new_with_meta(span.start, new_len, span.style, span.meta.clone())
                }
            })
            .collect();
    }

    /// Fit text to width by splitting on newlines, then setting each line to exact width.
    pub fn fit(&self, width: usize) -> Vec<Text> {
        let mut lines = Vec::new();
        for mut line in self.split("\n", false, true) {
            line.set_length(width);
            lines.push(line);
        }
        lines
    }

    /// Remove suffix from the text if present.
    pub fn remove_suffix(&mut self, suffix: &str) {
        if self.text.ends_with(suffix) {
            let suffix_chars = suffix.chars().count();
            self.right_crop(suffix_chars);
        }
    }

    /// Extend the last span's style to cover `count` more characters.
    pub fn extend_style(&mut self, count: usize) {
        if count == 0 {
            return;
        }
        let end_offset = self.len();
        if !self.spans.is_empty() {
            for span in &mut self.spans {
                if span.end >= end_offset {
                    span.end += count;
                }
            }
        }
        self.text.push_str(&" ".repeat(count));
    }

    /// Detect the common indentation level.
    pub fn detect_indentation(&self) -> usize {
        let re = Regex::new(r"(?m)^( *)(.*)$").unwrap_or_else(|_| Regex::new("$^").unwrap());
        let mut indentations: Vec<usize> = Vec::new();
        for cap in re.captures_iter(&self.text) {
            let indent_len = cap.get(1).map_or(0, |m| m.as_str().len());
            let content = cap.get(2).map_or("", |m| m.as_str());
            if !content.is_empty() && indent_len > 0 {
                indentations.push(indent_len);
            }
        }

        if indentations.is_empty() {
            return 1;
        }

        // Filter to even indentations, then compute GCD
        let even_indents: Vec<usize> = indentations.into_iter().filter(|i| i % 2 == 0).collect();
        if even_indents.is_empty() {
            return 1;
        }

        even_indents.iter().copied().reduce(gcd).unwrap_or(1).max(1)
    }

    /// Copy spans from another Text onto this one (direct copy, no offset adjustment).
    pub fn copy_styles(&mut self, other: &Text) {
        self.spans.extend(other.spans.iter().cloned());
    }

    /// Append an iterable of `(content, style)` tokens.
    ///
    /// Control codes are stripped from each token before appending, matching append behavior.
    pub fn append_tokens<I, S>(&mut self, tokens: I)
    where
        I: IntoIterator<Item = (S, Option<Style>)>,
        S: AsRef<str>,
    {
        for (content, style) in tokens {
            let sanitized = strip_control_codes(content.as_ref());
            self.append(sanitized, style);
        }
    }

    /// Implement real indent guide rendering.
    ///
    /// Scans for leading whitespace and replaces indent positions with the guide
    /// character in the given style.
    pub fn with_indent_guides_full(
        &self,
        indent_size: Option<usize>,
        character: &str,
        style: Style,
    ) -> Text {
        let indent_size = indent_size.unwrap_or_else(|| self.detect_indentation());
        if indent_size == 0 {
            return self.clone();
        }

        let expanded = self.expand_tabs(indent_size);
        let indent_line = format!("{}{}", character, " ".repeat(indent_size.saturating_sub(1)));
        let re_indent = Regex::new(r"^( *)(.*)$").unwrap();

        let mut new_lines: Vec<Text> = Vec::new();
        let mut blank_lines: usize = 0;

        for line in expanded.split("\n", false, true) {
            let plain = line.plain_text().to_string();
            if let Some(caps) = re_indent.captures(&plain) {
                let indent = caps.get(1).map_or("", |m| m.as_str());
                let content = caps.get(2).map_or("", |m| m.as_str());

                if content.is_empty() {
                    blank_lines += 1;
                    continue;
                }

                let indent_len = indent.len();
                let full_indents = indent_len / indent_size;
                let remaining_space = indent_len % indent_size;
                let new_indent = format!(
                    "{}{}",
                    indent_line.repeat(full_indents),
                    " ".repeat(remaining_space)
                );

                let mut result_line = line.clone();
                // Replace the leading whitespace with guide characters
                let new_indent_len = new_indent.chars().count();
                let chars: Vec<char> = result_line.text.chars().collect();
                let replace_len = indent_len.min(new_indent_len).min(chars.len());
                let mut new_text = new_indent.clone();
                if replace_len < chars.len() {
                    let rest: String = chars[replace_len..].iter().collect();
                    new_text.push_str(&rest);
                }
                result_line.text = new_text;
                result_line.stylize(0, new_indent_len.min(indent_len), style);

                // Add blank lines with indent guides
                if blank_lines > 0 {
                    for _ in 0..blank_lines {
                        let blank_guide = Text::styled(new_indent.clone(), style);
                        new_lines.push(blank_guide);
                    }
                    blank_lines = 0;
                }

                new_lines.push(result_line);
            } else {
                blank_lines += 1;
            }
        }

        // Handle trailing blank lines
        for _ in 0..blank_lines {
            new_lines.push(Text::new());
        }

        let joiner = expanded.blank_copy("\n");
        joiner.join(new_lines)
    }
}

impl std::ops::Add for Text {
    type Output = Text;

    fn add(self, rhs: Text) -> Text {
        let mut result = self.clone();
        result.append_text(&rhs);
        result
    }
}

impl std::ops::Add<&str> for Text {
    type Output = Text;

    fn add(self, rhs: &str) -> Text {
        let mut result = self.clone();
        result.append(rhs, None);
        result
    }
}

/// Compute the greatest common divisor.
fn gcd(a: usize, b: usize) -> usize {
    if b == 0 { a } else { gcd(b, a % b) }
}

impl From<&str> for Text {
    fn from(s: &str) -> Self {
        Text::plain(s)
    }
}

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

/// Implement Renderable for Text.
///
/// This converts Text to Segments for rendering to the terminal.
impl Renderable for Text {
    fn render(&self, _console: &Console, options: &ConsoleOptions) -> Segments {
        let text = self.plain_text();
        let width = options.max_width;

        // Even when `no_wrap` is enabled, we still need to run through `wrap()` when
        // justification or overflow is requested, so that padding/truncation can be applied.
        let needs_processing = width > 0
            && (options.justify.is_some()
                || options.overflow.is_some()
                || text.lines().any(|line| cell_len(line) > width));

        if !needs_processing {
            return self.render_unwrapped();
        }

        let lines = self.wrap(
            width,
            options.justify,
            options.overflow,
            options.tab_size,
            options.no_wrap,
        );

        if lines.len() == 1 {
            return lines[0].render_unwrapped();
        }

        // Render each already-wrapped line without re-running wrap/justify/overflow.
        // Re-processing would strip trailing padding and re-center again, which can
        // shift multiline centered text to the right line-by-line (demo parity issue).
        let mut segments = Segments::new();
        for (i, line) in lines.iter().enumerate() {
            segments.extend(line.render_unwrapped());
            if i + 1 < lines.len() {
                segments.push(Segment::line());
            }
        }

        segments
    }

    fn measure(&self, _console: &Console, options: &ConsoleOptions) -> Measurement {
        let text = self.plain_text();
        let lines: Vec<&str> = text.lines().collect();

        let mut max_width = lines.iter().map(|line| cell_len(line)).max().unwrap_or(0);

        let words: Vec<&str> = text.split_whitespace().collect();
        let mut min_width = words
            .iter()
            .map(|word| cell_len(word))
            .max()
            .unwrap_or(max_width);

        if options.max_width > 0 {
            if max_width > options.max_width {
                max_width = options.max_width;
            }
            if min_width > options.max_width {
                min_width = options.max_width;
            }
        }

        Measurement::new(min_width, max_width)
    }
}

impl Text {
    fn render_unwrapped(&self) -> Segments {
        let text = self.plain_text();

        // Fast path: no spans - still apply base style if present
        if self.spans.is_empty() {
            let base_style = self.style.unwrap_or_default();
            let base_meta = self.meta.clone().unwrap_or_default();
            let segment = match (base_style.is_null(), base_meta.is_empty()) {
                (true, true) => Segment::new(text.to_string()),
                (true, false) => Segment::new_with_meta(text.to_string(), base_meta),
                (false, true) => Segment::styled(text.to_string(), base_style),
                (false, false) => {
                    Segment::styled_with_meta(text.to_string(), base_style, base_meta)
                }
            };
            return Segments::from(segment);
        }

        // Build a list of events: (offset, is_end, span_index)
        // span_index 0 is reserved for the base style
        let enumerated_spans: Vec<(usize, &Span)> = self
            .spans
            .iter()
            .enumerate()
            .map(|(i, s)| (i + 1, s))
            .collect();

        // Build style map: index -> style
        let mut style_map: std::collections::HashMap<usize, Style> =
            std::collections::HashMap::new();
        style_map.insert(0, self.style.unwrap_or_default());
        for (index, span) in &enumerated_spans {
            style_map.insert(*index, span.style);
        }

        // Build meta map: index -> meta
        let mut meta_map: std::collections::HashMap<usize, StyleMeta> =
            std::collections::HashMap::new();
        meta_map.insert(0, self.meta.clone().unwrap_or_default());
        for (index, span) in &enumerated_spans {
            meta_map.insert(*index, span.meta.clone().unwrap_or_default());
        }

        // Build events
        let mut events: Vec<(usize, bool, usize)> = Vec::new();
        events.push((0, false, 0)); // Base style starts at 0
        for (index, span) in &enumerated_spans {
            events.push((span.start, false, *index)); // Start event
            events.push((span.end, true, *index)); // End event
        }
        events.push((self.len(), true, 0)); // Base style ends at text end

        // Sort by offset, then by is_end (starts before ends at same position)
        events.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.cmp(&b.1)));

        // Process events and generate segments
        let mut segments = Segments::new();
        let mut stack: Vec<usize> = Vec::new();

        let chars: Vec<char> = text.chars().collect();

        for i in 0..events.len() - 1 {
            let (offset, leaving, style_id) = events[i];
            let (next_offset, _, _) = events[i + 1];

            if leaving {
                // Remove style from stack
                if let Some(pos) = stack.iter().position(|&x| x == style_id) {
                    stack.remove(pos);
                }
            } else {
                // Add style to stack
                stack.push(style_id);
            }

            // Generate segment for this region
            if next_offset > offset && offset < chars.len() {
                let end = next_offset.min(chars.len());
                let segment_text: String = chars[offset..end].iter().collect();

                // Combine styles from stack (later styles override earlier ones)
                let mut combined_style = Style::new();
                let mut combined_meta = StyleMeta::new();
                let mut sorted_stack = stack.clone();
                sorted_stack.sort();
                for &style_id in &sorted_stack {
                    if let Some(&style) = style_map.get(&style_id) {
                        combined_style = combined_style.combine(&style);
                    }
                    if let Some(meta) = meta_map.get(&style_id) {
                        combined_meta = combined_meta.combine(meta);
                    }
                }

                match (combined_style.is_null(), combined_meta.is_empty()) {
                    (true, true) => segments.push(Segment::new(segment_text)),
                    (true, false) => {
                        segments.push(Segment::new_with_meta(segment_text, combined_meta))
                    }
                    (false, true) => segments.push(Segment::styled(segment_text, combined_style)),
                    (false, false) => segments.push(Segment::styled_with_meta(
                        segment_text,
                        combined_style,
                        combined_meta,
                    )),
                }
            }
        }

        segments
    }
}

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

    // ==================== Span tests ====================

    #[test]
    fn test_span_new() {
        let style = Style::new().with_bold(true);
        let span = Span::new(0, 10, style);
        assert_eq!(span.start, 0);
        assert_eq!(span.end, 10);
        assert_eq!(span.style, style);
    }

    #[test]
    fn test_span_is_empty() {
        let style = Style::new();
        assert!(Span::new(5, 5, style).is_empty());
        assert!(Span::new(10, 5, style).is_empty());
        assert!(!Span::new(0, 5, style).is_empty());
    }

    #[test]
    fn test_span_split_middle() {
        let style = Style::new().with_bold(true);
        let span = Span::new(0, 10, style);
        let (first, second) = span.split(5);

        assert_eq!(first.start, 0);
        assert_eq!(first.end, 5);
        assert!(second.is_some());
        let second = second.unwrap();
        assert_eq!(second.start, 5);
        assert_eq!(second.end, 10);
    }

    #[test]
    fn test_span_split_before_start() {
        let style = Style::new();
        let span = Span::new(5, 10, style);
        let (first, second) = span.split(3);

        assert_eq!(first.start, 5);
        assert_eq!(first.end, 10);
        assert!(second.is_none());
    }

    #[test]
    fn test_span_split_after_end() {
        let style = Style::new();
        let span = Span::new(0, 5, style);
        let (first, second) = span.split(10);

        assert_eq!(first.start, 0);
        assert_eq!(first.end, 5);
        assert!(second.is_none());
    }

    #[test]
    fn test_span_split_at_end() {
        let style = Style::new();
        let span = Span::new(0, 5, style);
        let (first, second) = span.split(5);

        assert_eq!(first.start, 0);
        assert_eq!(first.end, 5);
        assert!(second.is_none());
    }

    #[test]
    fn test_span_move_positive() {
        let style = Style::new();
        let span = Span::new(5, 10, style);
        let moved = span.move_by(3);

        assert_eq!(moved.start, 8);
        assert_eq!(moved.end, 13);
    }

    #[test]
    fn test_span_move_negative() {
        let style = Style::new();
        let span = Span::new(5, 10, style);
        let moved = span.move_by(-3);

        assert_eq!(moved.start, 2);
        assert_eq!(moved.end, 7);
    }

    #[test]
    fn test_span_move_negative_clamp() {
        let style = Style::new();
        let span = Span::new(2, 5, style);
        let moved = span.move_by(-10);

        assert_eq!(moved.start, 0);
        assert_eq!(moved.end, 0);
    }

    #[test]
    fn test_span_right_crop() {
        let style = Style::new();
        let span = Span::new(0, 10, style);

        let cropped = span.right_crop(5);
        assert_eq!(cropped.start, 0);
        assert_eq!(cropped.end, 5);

        let uncropped = span.right_crop(15);
        assert_eq!(uncropped.start, 0);
        assert_eq!(uncropped.end, 10);
    }

    #[test]
    fn test_span_extend() {
        let style = Style::new();
        let span = Span::new(0, 5, style);

        let extended = span.extend(3);
        assert_eq!(extended.start, 0);
        assert_eq!(extended.end, 8);

        let unchanged = span.extend(0);
        assert_eq!(unchanged.start, 0);
        assert_eq!(unchanged.end, 5);
    }

    // ==================== Text basic tests ====================

    #[test]
    fn test_text_plain() {
        let text = Text::plain("hello");
        assert_eq!(text.plain_text(), "hello");
        assert_eq!(text.len(), 5);
    }

    #[test]
    fn test_text_styled() {
        let style = Style::new().with_bold(true);
        let text = Text::styled("hello", style);
        // Text::styled sets base style, not a span (matching Python behavior)
        assert_eq!(text.spans().len(), 0);
        assert_eq!(text.base_style(), Some(style));
    }

    #[test]
    fn test_text_append() {
        let mut text = Text::new();
        text.append("hello ", None);
        text.append("world", Some(Style::new().with_bold(true)));
        assert_eq!(text.plain_text(), "hello world");
        assert_eq!(text.spans().len(), 1);
    }

    #[test]
    fn test_text_append_text() {
        let mut text = Text::plain("Hello ");
        let other = Text::styled("World", Style::new().with_bold(true));
        text.append_text(&other);

        assert_eq!(text.plain_text(), "Hello World");
        assert_eq!(text.spans().len(), 1);
        assert_eq!(text.spans()[0].start, 6);
        assert_eq!(text.spans()[0].end, 11);
    }

    // ==================== Text::assemble tests ====================

    #[test]
    fn test_text_assemble() {
        let bold = Style::new().with_bold(true);
        let text = Text::assemble([
            TextPart::Plain("Hello, ".to_string()),
            TextPart::Styled("World".to_string(), bold),
            TextPart::Plain("!".to_string()),
        ]);

        assert_eq!(text.plain_text(), "Hello, World!");
        assert_eq!(text.spans().len(), 1);
        assert_eq!(text.spans()[0].start, 7);
        assert_eq!(text.spans()[0].end, 12);
    }

    #[test]
    fn test_text_assemble_with_text() {
        let inner = Text::styled("styled", Style::new().with_italic(true));
        let text = Text::assemble([
            TextPart::Plain("prefix ".to_string()),
            TextPart::Text(inner),
            TextPart::Plain(" suffix".to_string()),
        ]);

        assert_eq!(text.plain_text(), "prefix styled suffix");
    }

    // ==================== stylize_range tests ====================

    #[test]
    fn test_stylize_range_basic() {
        let mut text = Text::plain("Hello World");
        text.stylize_range(Style::new().with_bold(true), 0, Some(5));

        assert_eq!(text.spans().len(), 1);
        assert_eq!(text.spans()[0].start, 0);
        assert_eq!(text.spans()[0].end, 5);
    }

    #[test]
    fn test_stylize_range_negative_start() {
        let mut text = Text::plain("Hello World");
        text.stylize_range(Style::new().with_bold(true), -5, None);

        assert_eq!(text.spans().len(), 1);
        assert_eq!(text.spans()[0].start, 6); // 11 - 5 = 6
        assert_eq!(text.spans()[0].end, 11);
    }

    #[test]
    fn test_stylize_range_negative_end() {
        let mut text = Text::plain("Hello World");
        text.stylize_range(Style::new().with_bold(true), 0, Some(-6));

        assert_eq!(text.spans().len(), 1);
        assert_eq!(text.spans()[0].start, 0);
        assert_eq!(text.spans()[0].end, 5); // 11 - 6 = 5
    }

    #[test]
    fn test_stylize_range_none_end() {
        let mut text = Text::plain("Hello World");
        text.stylize_range(Style::new().with_bold(true), 6, None);

        assert_eq!(text.spans().len(), 1);
        assert_eq!(text.spans()[0].start, 6);
        assert_eq!(text.spans()[0].end, 11);
    }

    #[test]
    fn test_stylize_range_invalid() {
        let mut text = Text::plain("Hello");
        // Start after end
        text.stylize_range(Style::new().with_bold(true), 10, Some(5));
        assert!(text.spans().is_empty());

        // Start >= length
        text.stylize_range(Style::new().with_bold(true), 10, None);
        assert!(text.spans().is_empty());
    }

    // ==================== stylize_before tests ====================

    #[test]
    fn test_stylize_before() {
        let mut text = Text::plain("Hello World");
        text.stylize_range(Style::new().with_bold(true), 0, None);
        text.stylize_before(Style::new().with_italic(true), 0, None);

        // stylize_before should insert at beginning
        assert_eq!(text.spans().len(), 2);
        assert_eq!(text.spans()[0].style.italic, Some(true));
        assert_eq!(text.spans()[1].style.bold, Some(true));
    }

    // ==================== highlight_regex tests ====================

    #[test]
    fn test_highlight_regex_basic() {
        let mut text = Text::plain("foo bar foo baz");
        let count = text.highlight_regex(r"foo", Style::new().with_bold(true));

        assert_eq!(count, 2);
        assert_eq!(text.spans().len(), 2);
    }

    #[test]
    fn test_highlight_regex_no_match() {
        let mut text = Text::plain("hello world");
        let count = text.highlight_regex(r"xyz", Style::new().with_bold(true));

        assert_eq!(count, 0);
        assert!(text.spans().is_empty());
    }

    #[test]
    fn test_highlight_regex_invalid() {
        let mut text = Text::plain("hello world");
        let count = text.highlight_regex(r"[invalid", Style::new().with_bold(true));

        assert_eq!(count, 0);
    }

    // ==================== highlight_words tests ====================

    #[test]
    fn test_highlight_words_basic() {
        let mut text = Text::plain("Hello World Hello");
        let count = text.highlight_words(&["Hello"], Style::new().with_bold(true), true);

        assert_eq!(count, 2);
        assert_eq!(text.spans().len(), 2);
    }

    #[test]
    fn test_highlight_words_case_insensitive() {
        let mut text = Text::plain("Hello HELLO hello");
        let count = text.highlight_words(&["hello"], Style::new().with_bold(true), false);

        assert_eq!(count, 3);
    }

    #[test]
    fn test_highlight_words_case_sensitive() {
        let mut text = Text::plain("Hello HELLO hello");
        let count = text.highlight_words(&["Hello"], Style::new().with_bold(true), true);

        assert_eq!(count, 1);
    }

    #[test]
    fn test_highlight_words_multiple() {
        let mut text = Text::plain("foo bar baz foo");
        let count = text.highlight_words(&["foo", "bar"], Style::new().with_bold(true), true);

        assert_eq!(count, 3); // foo, bar, foo
    }

    #[test]
    fn test_highlight_words_empty() {
        let mut text = Text::plain("hello");
        let count = text.highlight_words(&[], Style::new().with_bold(true), true);

        assert_eq!(count, 0);
    }

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

    #[test]
    fn test_divide_empty_offsets() {
        let text = Text::plain("Hello World");
        let divided = text.divide([]);

        assert_eq!(divided.len(), 1);
        assert_eq!(divided[0].plain_text(), "Hello World");
    }

    #[test]
    fn test_divide_single_offset() {
        let text = Text::plain("Hello World");
        let divided = text.divide([5]);

        assert_eq!(divided.len(), 2);
        assert_eq!(divided[0].plain_text(), "Hello");
        assert_eq!(divided[1].plain_text(), " World");
    }

    #[test]
    fn test_divide_multiple_offsets() {
        let text = Text::plain("Hello World!");
        let divided = text.divide([5, 6]);

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

    #[test]
    fn test_divide_with_spans() {
        let mut text = Text::plain("Hello World");
        text.stylize(0, 5, Style::new().with_bold(true));

        let divided = text.divide([5]);

        assert_eq!(divided.len(), 2);
        assert_eq!(divided[0].plain_text(), "Hello");
        assert_eq!(divided[0].spans().len(), 1);
        assert_eq!(divided[0].spans()[0].start, 0);
        assert_eq!(divided[0].spans()[0].end, 5);

        assert_eq!(divided[1].plain_text(), " World");
        assert!(divided[1].spans().is_empty());
    }

    #[test]
    fn test_divide_span_crosses_boundary() {
        let mut text = Text::plain("Hello World");
        // Span covers "llo Wo" (3-9)
        text.stylize(3, 9, Style::new().with_bold(true));

        let divided = text.divide([5]);

        // First part: "Hello" with span 3-5
        assert_eq!(divided[0].plain_text(), "Hello");
        assert_eq!(divided[0].spans().len(), 1);
        assert_eq!(divided[0].spans()[0].start, 3);
        assert_eq!(divided[0].spans()[0].end, 5);

        // Second part: " World" with span 0-4 (was 5-9, offset by -5)
        assert_eq!(divided[1].plain_text(), " World");
        assert_eq!(divided[1].spans().len(), 1);
        assert_eq!(divided[1].spans()[0].start, 0);
        assert_eq!(divided[1].spans()[0].end, 4);
    }

    // ==================== Renderable tests ====================

    #[test]
    fn test_text_render_plain() {
        let text = Text::plain("Hello World");
        let console = Console::new();
        let options = ConsoleOptions::default();

        let segments = text.render(&console, &options);
        assert_eq!(segments.len(), 1);
        assert_eq!(&*segments.iter().next().unwrap().text, "Hello World");
    }

    #[test]
    fn test_text_render_styled() {
        let mut text = Text::plain("Hello World");
        text.stylize(0, 5, Style::new().with_bold(true));

        let console = Console::new();
        let options = ConsoleOptions::default();

        let segments = text.render(&console, &options);
        assert!(segments.len() >= 2);
    }

    #[test]
    fn test_text_measure() {
        let text = Text::plain("Hello\nWorld!");
        let console = Console::new();
        let options = ConsoleOptions::default();

        let measurement = text.measure(&console, &options);
        assert_eq!(measurement.maximum, 6); // "World!" is longest
        assert_eq!(measurement.minimum, 6); // "World!" is longest word
    }

    // ==================== from_markup tests ====================

    #[test]
    fn test_from_markup() {
        let text = Text::from_markup("[bold]Hello[/] World", false).unwrap();
        assert_eq!(text.plain_text(), "Hello World");
        assert!(!text.spans().is_empty());
    }

    // ==================== join tests ====================

    #[test]
    fn test_text_join() {
        let separator = Text::plain(", ");
        let texts = vec![Text::plain("a"), Text::plain("b"), Text::plain("c")];

        let joined = separator.join(texts);
        assert_eq!(joined.plain_text(), "a, b, c");
    }

    #[test]
    fn test_text_join_empty_separator() {
        let separator = Text::plain("");
        let texts = vec![Text::plain("a"), Text::plain("b")];

        let joined = separator.join(texts);
        assert_eq!(joined.plain_text(), "ab");
    }

    // ==================== Unicode tests ====================

    #[test]
    fn test_text_unicode_len() {
        let text = Text::plain("你好");
        assert_eq!(text.len(), 2); // 2 characters
        assert_eq!(text.cell_len(), 4); // 4 cells (each CJK char is 2 wide)
    }

    #[test]
    fn test_divide_unicode() {
        let text = Text::plain("你好世界");
        let divided = text.divide([2]);

        assert_eq!(divided.len(), 2);
        assert_eq!(divided[0].plain_text(), "你好");
        assert_eq!(divided[1].plain_text(), "世界");
    }

    // ==================== pad_right tests ====================

    #[test]
    fn test_pad_right_basic() {
        let text = Text::plain("hello");
        let padded = text.pad_right(10);
        assert_eq!(padded.plain_text(), "hello     ");
        assert_eq!(padded.cell_len(), 10);
    }

    #[test]
    fn test_pad_right_already_wide() {
        let text = Text::plain("hello world");
        let padded = text.pad_right(5);
        assert_eq!(padded.plain_text(), "hello world");
    }

    #[test]
    fn test_pad_right_preserves_spans() {
        let mut text = Text::plain("hello");
        text.stylize(0, 5, Style::new().with_bold(true));
        let padded = text.pad_right(10);
        assert_eq!(padded.spans().len(), 1);
        assert_eq!(padded.spans()[0].start, 0);
        assert_eq!(padded.spans()[0].end, 5);
    }

    // ==================== pad_left tests ====================

    #[test]
    fn test_pad_left_basic() {
        let text = Text::plain("hello");
        let padded = text.pad_left(10);
        assert_eq!(padded.plain_text(), "     hello");
        assert_eq!(padded.cell_len(), 10);
    }

    #[test]
    fn test_pad_left_shifts_spans() {
        let mut text = Text::plain("hello");
        text.stylize(0, 5, Style::new().with_bold(true));
        let padded = text.pad_left(10);
        assert_eq!(padded.spans().len(), 1);
        assert_eq!(padded.spans()[0].start, 5); // Shifted by padding
        assert_eq!(padded.spans()[0].end, 10);
    }

    // ==================== center tests ====================

    #[test]
    fn test_center_basic() {
        let text = Text::plain("hi");
        let centered = text.center(6);
        assert_eq!(centered.plain_text(), "  hi  ");
        assert_eq!(centered.cell_len(), 6);
    }

    #[test]
    fn test_center_odd_padding() {
        let text = Text::plain("hi");
        let centered = text.center(7);
        // 5 total padding, 2 left, 3 right
        assert_eq!(centered.plain_text(), "  hi   ");
    }

    #[test]
    fn test_center_shifts_spans() {
        let mut text = Text::plain("hi");
        text.stylize(0, 2, Style::new().with_bold(true));
        let centered = text.center(6);
        assert_eq!(centered.spans().len(), 1);
        assert_eq!(centered.spans()[0].start, 2);
        assert_eq!(centered.spans()[0].end, 4);
    }

    // ==================== expand_tabs tests ====================

    #[test]
    fn test_expand_tabs_basic() {
        let text = Text::plain("a\tb");
        let expanded = text.expand_tabs(4);
        assert_eq!(expanded.plain_text(), "a   b");
    }

    #[test]
    fn test_expand_tabs_multiple() {
        let text = Text::plain("a\tbc\td");
        let expanded = text.expand_tabs(4);
        // "a" at pos 0, tab expands to 3 spaces (to reach pos 4)
        // "bc" at pos 4-5, tab expands to 2 spaces (to reach pos 8)
        // "d" at pos 8
        assert_eq!(expanded.plain_text(), "a   bc  d");
    }

    #[test]
    fn test_expand_tabs_no_tabs() {
        let text = Text::plain("hello");
        let expanded = text.expand_tabs(4);
        assert_eq!(expanded.plain_text(), "hello");
    }

    #[test]
    fn test_expand_tabs_preserves_spans() {
        let mut text = Text::plain("a\tb");
        text.stylize(0, 1, Style::new().with_bold(true)); // Style "a"
        text.stylize(2, 3, Style::new().with_italic(true)); // Style "b"
        let expanded = text.expand_tabs(4);

        // "a" should still be styled at position 0
        // "b" should now be at position 4 (after "a   ")
        assert_eq!(expanded.spans().len(), 2);
        assert_eq!(expanded.spans()[0].start, 0);
        assert_eq!(expanded.spans()[0].end, 1);
        assert_eq!(expanded.spans()[1].start, 4);
        assert_eq!(expanded.spans()[1].end, 5);
    }

    // ==================== rstrip tests ====================

    #[test]
    fn test_rstrip_basic() {
        let text = Text::plain("hello   ");
        let stripped = text.rstrip();
        assert_eq!(stripped.plain_text(), "hello");
    }

    #[test]
    fn test_rstrip_no_whitespace() {
        let text = Text::plain("hello");
        let stripped = text.rstrip();
        assert_eq!(stripped.plain_text(), "hello");
    }

    #[test]
    fn test_rstrip_adjusts_spans() {
        let mut text = Text::plain("hello   ");
        text.stylize(0, 8, Style::new().with_bold(true));
        let stripped = text.rstrip();
        assert_eq!(stripped.spans().len(), 1);
        assert_eq!(stripped.spans()[0].end, 5); // Clamped to new length
    }

    // ==================== rstrip_end tests ====================

    #[test]
    fn test_rstrip_end_basic() {
        let text = Text::plain("hello   ");
        let stripped = text.rstrip_end(5);
        assert_eq!(stripped.plain_text(), "hello");
    }

    #[test]
    fn test_rstrip_end_partial() {
        let text = Text::plain("hello   ");
        let stripped = text.rstrip_end(7);
        // Only removes 1 trailing space (8 - 7 = 1)
        assert_eq!(stripped.plain_text(), "hello  ");
    }

    #[test]
    fn test_rstrip_end_already_short() {
        let text = Text::plain("hello");
        let stripped = text.rstrip_end(10);
        assert_eq!(stripped.plain_text(), "hello");
    }

    // ==================== truncate tests ====================

    #[test]
    fn test_truncate_crop() {
        use crate::console::OverflowMethod;
        let text = Text::plain("hello world");
        let truncated = text.truncate(5, OverflowMethod::Crop, false);
        assert_eq!(truncated.plain_text(), "hello");
    }

    #[test]
    fn test_truncate_ellipsis() {
        use crate::console::OverflowMethod;
        let text = Text::plain("hello world");
        let truncated = text.truncate(6, OverflowMethod::Ellipsis, false);
        assert_eq!(truncated.plain_text(), "hello…");
    }

    #[test]
    fn test_truncate_with_pad() {
        use crate::console::OverflowMethod;
        let text = Text::plain("hi");
        let truncated = text.truncate(5, OverflowMethod::Crop, true);
        assert_eq!(truncated.plain_text(), "hi   ");
    }

    // ==================== split tests ====================

    #[test]
    fn test_split_newlines() {
        let text = Text::plain("hello\nworld");
        let lines = text.split("\n", false, false);
        assert_eq!(lines.len(), 2);
        assert_eq!(lines[0].plain_text(), "hello");
        assert_eq!(lines[1].plain_text(), "world");
    }

    #[test]
    fn test_split_include_separator() {
        let text = Text::plain("hello\nworld");
        let lines = text.split("\n", true, false);
        assert_eq!(lines.len(), 2);
        assert_eq!(lines[0].plain_text(), "hello\n");
        assert_eq!(lines[1].plain_text(), "world");
    }

    #[test]
    fn test_split_allow_blank() {
        let text = Text::plain("hello\n");
        let lines = text.split("\n", false, true);
        assert_eq!(lines.len(), 2);
        assert_eq!(lines[0].plain_text(), "hello");
        assert_eq!(lines[1].plain_text(), "");
    }

    // ==================== wrap tests ====================

    #[test]
    fn test_wrap_basic() {
        let text = Text::plain("hello world test");
        let lines = text.wrap(6, None, None, 8, false);
        assert_eq!(lines.len(), 3);
        assert_eq!(lines[0].plain_text(), "hello ");
        assert_eq!(lines[1].plain_text(), "world ");
        assert_eq!(lines[2].plain_text(), "test");
    }

    #[test]
    fn test_wrap_existing_newlines() {
        let text = Text::plain("hello\nworld");
        let lines = text.wrap(20, None, None, 8, false);
        assert_eq!(lines.len(), 2);
        assert_eq!(lines[0].plain_text(), "hello");
        assert_eq!(lines[1].plain_text(), "world");
    }

    #[test]
    fn test_wrap_left_justify() {
        use crate::console::JustifyMethod;
        let text = Text::plain("hi");
        let lines = text.wrap(5, Some(JustifyMethod::Left), None, 8, false);
        assert_eq!(lines.len(), 1);
        assert_eq!(lines[0].plain_text(), "hi   ");
    }

    #[test]
    fn test_wrap_right_justify() {
        use crate::console::JustifyMethod;
        let text = Text::plain("hi");
        let lines = text.wrap(5, Some(JustifyMethod::Right), None, 8, false);
        assert_eq!(lines.len(), 1);
        assert_eq!(lines[0].plain_text(), "   hi");
    }

    #[test]
    fn test_wrap_center_justify() {
        use crate::console::JustifyMethod;
        let text = Text::plain("hi");
        let lines = text.wrap(6, Some(JustifyMethod::Center), None, 8, false);
        assert_eq!(lines.len(), 1);
        assert_eq!(lines[0].plain_text(), "  hi  ");
    }

    #[test]
    fn test_wrap_fold_long_word() {
        use crate::console::OverflowMethod;
        let text = Text::plain("abcdefghij");
        let lines = text.wrap(4, None, Some(OverflowMethod::Fold), 8, false);
        assert_eq!(lines.len(), 3);
        assert_eq!(lines[0].plain_text(), "abcd");
        assert_eq!(lines[1].plain_text(), "efgh");
        assert_eq!(lines[2].plain_text(), "ij");
    }

    #[test]
    fn test_wrap_no_wrap() {
        let text = Text::plain("hello world");
        let lines = text.wrap(5, None, None, 8, true);
        assert_eq!(lines.len(), 1);
        assert_eq!(lines[0].plain_text(), "hello world");
    }

    #[test]
    fn test_render_no_wrap_still_applies_justify() {
        use crate::Console;
        use crate::console::{ConsoleOptions, JustifyMethod};

        let console = Console::new();
        let options = ConsoleOptions {
            max_width: 6,
            justify: Some(JustifyMethod::Center),
            no_wrap: true,
            ..Default::default()
        };

        let text = Text::plain("hi");
        let segments = text.render(&console, &options);
        let rendered: String = segments.iter().map(|s| s.text.as_ref()).collect();
        assert_eq!(rendered, "  hi  ");
    }

    #[test]
    fn test_justify_full_distributes_extra_spaces_right_to_left() {
        // Words are "a", "b", "c" => 3 chars.
        // Width 8 means we need 5 spaces total between words.
        // Python Rich distributes extra spaces from right-to-left.
        // With 2 gaps, that yields left gap 2 spaces, right gap 3 spaces.
        let text = Text::plain("a b c");
        let justified = text.justify_full(8);
        assert_eq!(justified.plain_text(), "a  b   c");
    }

    #[test]
    fn test_wrap_with_tabs() {
        let text = Text::plain("a\tb");
        let lines = text.wrap(20, None, None, 4, false);
        assert_eq!(lines.len(), 1);
        assert_eq!(lines[0].plain_text(), "a   b");
    }

    #[test]
    fn test_wrap_preserves_spans() {
        let mut text = Text::plain("hello world");
        text.stylize(0, 5, Style::new().with_bold(true));
        let lines = text.wrap(6, None, None, 8, false);

        assert_eq!(lines.len(), 2);
        // First line "hello " should have the bold span
        assert!(!lines[0].spans().is_empty());
        assert_eq!(lines[0].spans()[0].style.bold, Some(true));
    }

    #[test]
    fn test_wrap_cjk() {
        let text = Text::plain("你好世界");
        // Each CJK char is 2 cells, so with width 5, we can fit 2 chars (4 cells)
        let lines = text.wrap(5, None, None, 8, false);
        assert_eq!(lines.len(), 2);
        assert_eq!(lines[0].plain_text(), "你好");
        assert_eq!(lines[1].plain_text(), "世界");
    }

    #[test]
    fn test_wrap_full_justify() {
        use crate::console::JustifyMethod;
        let text = Text::plain("a b c");
        let lines = text.wrap(7, Some(JustifyMethod::Full), None, 8, false);
        assert_eq!(lines.len(), 1);
        // Last line should be left-aligned, not full justified
        assert_eq!(lines[0].plain_text(), "a b c  ");
    }

    #[test]
    fn test_wrap_full_justify_multiline() {
        use crate::console::JustifyMethod;
        let text = Text::plain("a b c d e");
        let lines = text.wrap(5, Some(JustifyMethod::Full), None, 8, false);
        // Should have multiple lines, with full justification on non-last lines
        assert!(lines.len() >= 2);
    }

    // ==================== slice tests ====================

    #[test]
    fn test_slice_basic() {
        let text = Text::plain("Hello World");
        let sliced = text.slice(0, 5);
        assert_eq!(sliced.plain_text(), "Hello");
    }

    #[test]
    fn test_slice_middle() {
        let text = Text::plain("Hello World");
        let sliced = text.slice(6, 11);
        assert_eq!(sliced.plain_text(), "World");
    }

    #[test]
    fn test_slice_preserves_spans() {
        let mut text = Text::plain("Hello World");
        text.stylize(0, 5, Style::new().with_bold(true));

        let sliced = text.slice(0, 5);
        assert_eq!(sliced.plain_text(), "Hello");
        assert!(!sliced.spans().is_empty());
        assert_eq!(sliced.spans()[0].start, 0);
        assert_eq!(sliced.spans()[0].end, 5);
    }

    #[test]
    fn test_slice_clips_span() {
        let mut text = Text::plain("Hello World");
        text.stylize(3, 8, Style::new().with_bold(true));

        let sliced = text.slice(0, 5);
        assert_eq!(sliced.plain_text(), "Hello");
        assert!(!sliced.spans().is_empty());
        assert_eq!(sliced.spans()[0].start, 3);
        assert_eq!(sliced.spans()[0].end, 5);
    }

    #[test]
    fn test_slice_empty_range() {
        let text = Text::plain("Hello World");
        let sliced = text.slice(5, 5);
        assert_eq!(sliced.plain_text(), "");
    }

    // ==================== align tests ====================

    #[test]
    fn test_align_left() {
        use crate::console::JustifyMethod;
        let mut text = Text::plain("hi");
        text.align(JustifyMethod::Left, 6);
        assert_eq!(text.plain_text(), "hi    ");
    }

    #[test]
    fn test_align_right() {
        use crate::console::JustifyMethod;
        let mut text = Text::plain("hi");
        text.align(JustifyMethod::Right, 6);
        assert_eq!(text.plain_text(), "    hi");
    }

    #[test]
    fn test_align_center() {
        use crate::console::JustifyMethod;
        let mut text = Text::plain("hi");
        text.align(JustifyMethod::Center, 6);
        assert_eq!(text.plain_text(), "  hi  ");
    }

    // ==================== contains tests ====================

    #[test]
    fn test_contains_true() {
        let text = Text::plain("Hello World");
        assert!(text.contains("World"));
    }

    #[test]
    fn test_contains_false() {
        let text = Text::plain("Hello World");
        assert!(!text.contains("xyz"));
    }

    // ==================== get_style_at_offset tests ====================

    #[test]
    fn test_get_style_at_offset() {
        let mut text = Text::plain("Hello World");
        let bold = Style::new().with_bold(true);
        text.stylize(0, 5, bold);

        let style_at_0 = text.get_style_at_offset(0);
        assert_eq!(style_at_0.bold, Some(true));

        let style_at_6 = text.get_style_at_offset(6);
        assert_ne!(style_at_6.bold, Some(true));
    }

    // ==================== set_length tests ====================

    #[test]
    fn test_set_length_pad() {
        let mut text = Text::plain("hi");
        text.set_length(5);
        assert_eq!(text.cell_len(), 5);
        assert!(text.plain_text().starts_with("hi"));
    }

    #[test]
    fn test_set_length_crop() {
        let mut text = Text::plain("hello world");
        text.set_length(5);
        assert_eq!(text.plain_text(), "hello");
    }

    // ==================== right_crop tests ====================

    #[test]
    fn test_text_right_crop() {
        let mut text = Text::plain("Hello World");
        text.right_crop(6);
        assert_eq!(text.plain_text(), "Hello");
    }

    #[test]
    fn test_text_right_crop_adjusts_spans() {
        let mut text = Text::plain("Hello World");
        text.stylize(0, 11, Style::new().with_bold(true));
        text.right_crop(6);
        assert_eq!(text.spans()[0].end, 5);
    }

    // ==================== fit tests ====================

    #[test]
    fn test_fit_basic() {
        let text = Text::plain("Hello\nWorld");
        let lines = text.fit(10);
        assert_eq!(lines.len(), 2);
        assert_eq!(lines[0].cell_len(), 10);
        assert_eq!(lines[1].cell_len(), 10);
    }

    // ==================== remove_suffix tests ====================

    #[test]
    fn test_remove_suffix_found() {
        let mut text = Text::plain("Hello World");
        text.remove_suffix(" World");
        assert_eq!(text.plain_text(), "Hello");
    }

    #[test]
    fn test_remove_suffix_not_found() {
        let mut text = Text::plain("Hello World");
        text.remove_suffix("xyz");
        assert_eq!(text.plain_text(), "Hello World");
    }

    // ==================== extend_style tests ====================

    #[test]
    fn test_extend_style() {
        let mut text = Text::plain("hello");
        text.stylize(0, 5, Style::new().with_bold(true));
        text.extend_style(3);
        assert_eq!(text.len(), 8);
        assert_eq!(text.spans()[0].end, 8);
    }

    // ==================== detect_indentation tests ====================

    #[test]
    fn test_detect_indentation() {
        let text = Text::plain("  foo\n    bar\n      baz");
        let indent = text.detect_indentation();
        assert_eq!(indent, 2);
    }

    // ==================== copy_styles tests ====================

    #[test]
    fn test_copy_styles() {
        let mut text = Text::plain("Hello World");
        let mut other = Text::plain("Hello World");
        other.stylize(0, 5, Style::new().with_bold(true));

        text.copy_styles(&other);
        assert_eq!(text.spans().len(), 1);
    }

    // ==================== apply_meta tests ====================

    #[test]
    fn test_apply_meta_adds_metadata_span() {
        let mut text = Text::plain("Hello World");
        let mut meta = BTreeMap::new();
        meta.insert("foo".to_string(), crate::style::MetaValue::str("bar"));

        text.apply_meta(meta, 0, Some(5));

        assert_eq!(text.spans().len(), 1);
        let span = &text.spans()[0];
        assert_eq!(span.start, 0);
        assert_eq!(span.end, 5);
        assert!(span.style.is_null());
        let span_meta = span.meta.as_ref().and_then(|m| m.meta.as_ref());
        assert!(span_meta.is_some());
        assert_eq!(
            span_meta.and_then(|m| m.get("foo")),
            Some(&crate::style::MetaValue::str("bar"))
        );
    }

    #[test]
    fn test_apply_meta_supports_negative_offsets() {
        let mut text = Text::plain("abcdef");
        let mut meta = BTreeMap::new();
        meta.insert(
            "@click".to_string(),
            crate::style::MetaValue::str("handler"),
        );

        text.apply_meta(meta, -3, None);

        assert_eq!(text.spans().len(), 1);
        assert_eq!(text.spans()[0].start, 3);
        assert_eq!(text.spans()[0].end, 6);
    }

    // ==================== append_tokens tests ====================

    #[test]
    fn test_append_tokens_appends_content_and_styles() {
        let mut text = Text::plain("A");
        let bold = Style::new().with_bold(true);
        let italic = Style::new().with_italic(true);

        text.append_tokens(vec![("B", Some(bold)), ("C", None), ("D", Some(italic))]);

        assert_eq!(text.plain_text(), "ABCD");
        assert_eq!(text.spans().len(), 2);
        assert_eq!(text.spans()[0].start, 1);
        assert_eq!(text.spans()[0].end, 2);
        assert_eq!(text.spans()[0].style.bold, Some(true));
        assert_eq!(text.spans()[1].start, 3);
        assert_eq!(text.spans()[1].end, 4);
        assert_eq!(text.spans()[1].style.italic, Some(true));
    }

    #[test]
    fn test_append_tokens_strips_control_codes() {
        let mut text = Text::new();
        let bold = Style::new().with_bold(true);

        text.append_tokens(vec![("a\x07b", Some(bold))]);

        assert_eq!(text.plain_text(), "ab");
        assert_eq!(text.spans().len(), 1);
        assert_eq!(text.spans()[0].start, 0);
        assert_eq!(text.spans()[0].end, 2);
    }

    // ==================== Add trait tests ====================

    #[test]
    fn test_add_text() {
        let a = Text::plain("Hello ");
        let b = Text::plain("World");
        let result = a + b;
        assert_eq!(result.plain_text(), "Hello World");
    }

    #[test]
    fn test_add_str() {
        let a = Text::plain("Hello ");
        let result = a + "World";
        assert_eq!(result.plain_text(), "Hello World");
    }

    // ==================== to_markup tests ====================

    #[test]
    fn test_to_markup_plain() {
        let text = Text::plain("Hello World");
        assert_eq!(text.to_markup(), "Hello World");
    }

    #[test]
    fn test_to_markup_with_style() {
        let mut text = Text::plain("Hello");
        text.stylize(0, 5, Style::new().with_bold(true));
        let markup = text.to_markup();
        assert!(markup.contains("[bold]"));
        assert!(markup.contains("[/bold]"));
        assert!(markup.contains("Hello"));
    }
}