tree_fmt 0.9.0

Multi-format data visualization library with 10 formatters, 31 variants, and granular per-variant feature flags for minimal binary size
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
# tree_fmt Specification

## Overview

Generic multi-format data visualization library with unified format interface supporting eight output formats: **Table**, **Expanded**, **Tree**, **Logfmt**, **JSON**, **YAML**, **TOML**, and **Text** (NEW in v0.4.0+). Granular feature flags enable zero-cost abstractions with minimal dependencies. Core visual formatters have zero dependencies.

## Purpose

Provide reusable formatters for displaying data in multiple formats with seamless conversion between representations. Enables displaying the same data as horizontal tables, vertical records, or hierarchical trees across wflow and other projects.

## Design Principles

1. **Single Data Structure**: TreeNode<T> for all data (hierarchical and tabular)
2. **Unified Format Interface**: Same API for all formatters via Format trait (NEW v0.4.0)
3. **Canonical Data Format**: TableView struct for format-agnostic code (NEW v0.4.0)
4. **Granular Features**: Zero-cost abstractions with optional formatters (NEW v0.4.0)
5. **Mutual Replaceability**: Any data can be displayed in any format
6. **Minimal Dependencies**: Core has zero dependencies, formatters are optional
7. **Generic**: Works with any data type via `TreeNode<T>`
8. **ANSI-Aware**: Proper alignment with color codes
9. **Flexible Output**: String return and io::Write support
10. **Helper Traits**: Ergonomic builders and traits for table-shaped trees
11. **Modular Architecture**: Separated concerns across 16 source modules

## Display Formats

### Table Format (Horizontal Tabular)

Standard row-and-column table layout.

```text
 sid | sname | gap
-----+-------+-----
   3 | Alice |   5
   6 | Joe   |   1
  10 | Boris |   5
```

**Characteristics:**
- Horizontal layout
- Column headers with separator line
- Fixed-width columns with alignment
- Optional borders
- Compact representation for many rows

**Use cases:** Database results, comparison tables, spreadsheet-like data

### Table Styles (NEW in v0.3.0)

The `TableFormatter` supports 9 distinct table styles through comprehensive configuration options. Each style is optimized for specific use cases and output formats.

#### 1. Plain Style (Process Monitoring)

Clean space-separated columns with dash separator. Ideal for CLI tools output.

```text
 COUNT  MEMORY  NAMES  COMMANDS                        PATH
 -----  ------  -----  ------------------------------  ----
    45   12.4GB      3  claude,npm exec firecr,Main...  /home/user1/.nvm
    68    7.1GB      1  cargo                           /home/user1/.rustup
```

**Usage**:
```rust
let formatter = TableFormatter::with_config( TableConfig::plain() );
```

**Characteristics**:
- No vertical borders
- Dash-only header separator
- Space-separated columns (2 spaces default)
- Minimal padding
- Highly readable for terminal output

**Use cases**: Process monitors (ps, top), system utilities, log analysis, CLI tool output

#### 2. Minimal Style (No Separator)

Space-separated columns with no header separator. Maximum simplicity.

```text
 COUNT  MEMORY  NAMES  COMMANDS                        PATH
    45   12.4GB      3  claude,npm exec firecr,Main...  /home/user1/.nvm
    68    7.1GB      1  cargo                           /home/user1/.rustup
```

**Usage**:
```rust
let formatter = TableFormatter::with_config( TableConfig::minimal() );
```

**Characteristics**:
- No borders or separators
- Space-separated columns
- Cleanest possible output
- Maximum information density

**Use cases**: Simple reports, data exports, piping to other tools

#### 3. Bordered Style (Default)

Traditional pipe-separated table with full borders. Current default behavior.

```text
 COUNT  | MEMORY  | NAMES  | COMMANDS                        | PATH
--------+---------+--------+---------------------------------+-----------
    45  | 12.4GB  |     3  | claude,npm exec firecr,Main...  | /home/...
    68  | 7.1GB   |     1  | cargo                           | /home/...
```

**Usage**:
```rust
let formatter = TableFormatter::new();
// or
let formatter = TableFormatter::with_config( TableConfig::bordered() );
```

**Characteristics**:
- Pipe-separated columns (` | `)
- Dash+plus separator (` --------+--------- `)
- Clear visual boundaries
- Traditional database output style

**Use cases**: Database query results, formal reports, PostgreSQL-style output

#### 4. Markdown Style

GitHub-flavored Markdown table format.

```text
| COUNT | MEMORY | NAMES | COMMANDS                        | PATH      |
|-------|--------|-------|----------------------------------|-----------|
| 45    | 12.4GB | 3     | claude,npm exec firecr,Main...  | /home/... |
| 68    | 7.1GB  | 1     | cargo                            | /home/... |
```

**Usage**:
```rust
let formatter = TableFormatter::with_config( TableConfig::markdown() );
```

**Characteristics**:
- Pipes at start and end of each line
- Dash-only separator
- Compatible with Markdown renderers
- GitHub/GitLab documentation ready

**Use cases**: README files, documentation, GitHub issues, Markdown reports

#### 5. Grid Style (ASCII Box)

Full ASCII box drawing with intersections.

```text
+-------+--------+-------+----------------------------------+-----------+
| COUNT | MEMORY | NAMES | COMMANDS                         | PATH      |
+-------+--------+-------+----------------------------------+-----------+
| 45    | 12.4GB | 3     | claude,npm exec firecr,Main...  | /home/... |
+-------+--------+-------+----------------------------------+-----------+
| 68    | 7.1GB  | 1     | cargo                            | /home/... |
+-------+--------+-------+----------------------------------+-----------+
```

**Usage**:
```rust
let formatter = TableFormatter::with_config( TableConfig::grid() );
```

**Characteristics**:
- Full box with top/bottom borders
- Plus sign intersections
- Row separators between data rows
- Maximum visual clarity

**Use cases**: Formal reports, printed output, ASCII art dashboards

#### 6. Unicode Box Style

Full Unicode box drawing characters.

```text
┌───────┬────────┬───────┬──────────────────────────────────┬───────────┐
│ COUNT │ MEMORY │ NAMES │ COMMANDS                         │ PATH      │
├───────┼────────┼───────┼──────────────────────────────────┼───────────┤
│ 45    │ 12.4GB │ 3     │ claude,npm exec firecr,Main...  │ /home/... │
├───────┼────────┼───────┼──────────────────────────────────┼───────────┤
│ 68    │ 7.1GB  │ 1     │ cargo                            │ /home/... │
└───────┴────────┴───────┴──────────────────────────────────┴───────────┘
```

**Usage**:
```rust
let formatter = TableFormatter::with_config( TableConfig::unicode_box() );
```

**Characteristics**:
- Unicode box-drawing characters (┌─┬─┐)
- Smooth, professional appearance
- Top and bottom borders
- Row separators

**Use cases**: Terminal UIs, modern CLI tools, rich console output

#### 7. CSV Style

Comma-separated values with proper quoting.

```text
COUNT,MEMORY,NAMES,COMMANDS,PATH
45,12.4GB,3,"claude,npm exec firecr,Main...",/home/user1/.nvm
68,7.1GB,1,cargo,/home/user1/.rustup
```

**Usage**:
```rust
let formatter = TableFormatter::with_config( TableConfig::csv() );
```

**Characteristics**:
- Comma-separated
- Automatic quoting of values containing commas
- Standard CSV format
- No padding or alignment

**Use cases**: Data export, Excel import, database loading, data analysis

#### 8. TSV Style

Tab-separated values for clipboard and spreadsheet compatibility.

```text
COUNT→MEMORY→NAMES→COMMANDS→PATH
45→12.4GB→3→claude,npm exec firecr,Main...→/home/user1/.nvm
68→7.1GB→1→cargo→/home/user1/.rustup
```

Note: `→` represents tab character (`\t`) in actual output.

**Usage**:
```rust
let formatter = TableFormatter::with_config( TableConfig::tsv() );
```

**Characteristics**:
- Tab-separated (`\t`)
- No quoting needed
- Excel/Google Sheets compatible
- Preserves commas in data

**Use cases**: Spreadsheet paste, clipboard data, simple data exchange

#### 9. Compact Style

Minimal spacing for maximum information density.

```text
COUNT MEMORY NAMES COMMANDS                        PATH
    45 12.4GB     3 claude,npm exec firecr,Main... /home/user1/.nvm
    68  7.1GB     1 cargo                          /home/user1/.rustup
```

**Usage**:
```rust
let formatter = TableFormatter::with_config( TableConfig::compact() );
```

**Characteristics**:
- Single space column separator
- No padding around separators
- Maximum density
- No borders or separators

**Use cases**: Space-constrained displays, embedded systems, narrow terminals

### Table Formatter Parameters

The table formatter parameters system is built on three enums that can be mixed and matched:

#### BorderVariant Enum

```rust
pub enum BorderVariant
{
  /// No borders, space-separated columns
  None,

  /// ASCII borders with pipes: | + -
  Ascii,

  /// Full ASCII grid with row separators: +---+
  AsciiGrid,

  /// Unicode box drawing: ┌─┬─┐ ├─┼─┤ └─┴─┘
  Unicode,

  /// Markdown table format: | col | col |
  Markdown,
}
```

#### HeaderSeparatorVariant Enum

```rust
pub enum HeaderSeparatorVariant
{
  /// No separator line below header
  None,

  /// Dashes only: -----
  Dash,

  /// ASCII grid separator: +-----+
  AsciiGrid,

  /// Unicode separator: ├─────┤
  Unicode,

  /// Markdown separator: |-----|
  Markdown,
}
```

#### ColumnSeparator Enum

```rust
pub enum ColumnSeparator
{
  /// N spaces between columns
  Spaces( usize ),

  /// Single character separator (|, ,, \t, etc.)
  Character( char ),

  /// Custom string separator
  String( String ),
}
```

### Advanced Table Formatter Parameters

Beyond style presets, `TableConfig` supports granular control over formatter parameters:

```rust
pub struct TableConfig
{
  // Existing fields
  pub column_widths : Vec< usize >,
  pub align_right : Vec< bool >,

  // NEW in v0.3.0
  pub border_variant : BorderVariant,
  pub header_separator_variant : HeaderSeparatorVariant,
  pub column_separator : ColumnSeparator,
  pub outer_padding : bool,
  pub inner_padding : usize,
  pub colorize_header : bool,
  pub header_color : String,
  pub alternating_rows : bool,
  pub row_color1 : String,
  pub row_color2 : String,
  pub min_column_width : usize,
  pub max_column_width : Option< usize >,
  pub truncation_marker : String,
}
```

**Builder Methods**:
```rust
impl TableConfig
{
  // Style presets (NEW)
  pub fn plain() -> Self;
  pub fn minimal() -> Self;
  pub fn bordered() -> Self;
  pub fn markdown() -> Self;
  pub fn grid() -> Self;
  pub fn unicode_box() -> Self;
  pub fn csv() -> Self;
  pub fn tsv() -> Self;
  pub fn compact() -> Self;

  // Existing builders
  pub fn column_widths( self, widths : Vec< usize > ) -> Self;
  pub fn align_right( self, align : Vec< bool > ) -> Self;

  // NEW builders
  pub fn border_variant( self, variant : BorderVariant ) -> Self;
  pub fn header_separator_variant( self, variant : HeaderSeparatorVariant ) -> Self;
  pub fn column_separator( self, sep : ColumnSeparator ) -> Self;
  pub fn outer_padding( self, enabled : bool ) -> Self;
  pub fn inner_padding( self, spaces : usize ) -> Self;
  pub fn colorize_header( self, enabled : bool ) -> Self;
  pub fn header_color( self, color : String ) -> Self;
  pub fn alternating_rows( self, enabled : bool ) -> Self;
  pub fn row_colors( self, color1 : String, color2 : String ) -> Self;
  pub fn min_column_width( self, width : usize ) -> Self;
  pub fn max_column_width( self, width : Option< usize > ) -> Self;
  pub fn truncation_marker( self, marker : String ) -> Self;
}
```

### Custom Table Styles

Mix configuration options for custom styles:

```rust
// Custom: Cyan header with bold text and alternating row colors
let formatter = TableFormatter::with_config(
  TableConfig::plain()
    .colorize_header( true )
    .header_color( "\x1b[1;36m".to_string() )  // Bold cyan
    .alternating_rows( true )
    .row_colors(
      "\x1b[0m".to_string(),        // Normal
      "\x1b[48;5;236m".to_string()  // Dark gray background
    )
);

// Custom: Narrow terminal with truncation
let formatter = TableFormatter::with_config(
  TableConfig::minimal()
    .max_column_width( Some( 30 ) )
    .truncation_marker( "…".to_string() )
);

// Custom: Double-space separated with custom separator
let formatter = TableFormatter::with_config(
  TableConfig::new()
    .border_variant( BorderVariant::None )
    .header_separator_variant( HeaderSeparatorVariant::Dash )
    .column_separator( ColumnSeparator::Spaces( 4 ) )
);
```

### Logfmt Format (Structured Logging) - NEW v0.5.0

Machine-parseable structured logging format where each table row becomes one line of space-separated `key=value` pairs. Ideal for log aggregation tools and grep-friendly logging output.

```text
timestamp=2025-01-15T10:30:00Z level=info msg="user login" user_id=12345 duration=0.043
timestamp=2025-01-15T10:30:01Z level=error msg="database timeout" user_id=67890 duration=5.234
```

**Characteristics:**
- One line per data row
- Space-separated key=value pairs
- Header names become keys, cell values become values
- Automatic value escaping (spaces → quotes, quotes → backslashes)
- No visual formatting overhead (pure data)
- Human-readable AND machine-parseable

**Usage:**
```rust
let formatter = LogfmtFormatter::new();
// or with custom separator
let formatter = LogfmtFormatter::with_separator( ":" );
```

**Escaping Rules:**
- Values containing spaces/tabs → wrapped in double quotes
- Values containing quotes → quotes escaped with backslash
- Values containing newlines → newlines replaced with `\n` literal

**Example:**
```rust
let data = RowBuilder::new( vec![ "name".into(), "status".into(), "message".into() ] )
  .add_row( vec![ "server1".into(), "ok".into(), "running".into() ] )
  .add_row( vec![ "server2".into(), "error".into(), "disk full".into() ] )
  .build();

let formatter = LogfmtFormatter::new();
let output = formatter.format( &data );
```

**Output:**
```text
name=server1 status=ok message=running
name=server2 status=error message="disk full"
```

**Use cases:**
- Structured application logging
- Observability tool ingestion (Prometheus, Loki, Elasticsearch)
- Grep-friendly log formats
- Log aggregation pipelines
- CLI tool output for parsing

**Feature Flag:** Included in default `visual_formats` bundle (zero dependencies)

### Html Format (Web Tables) - NEW v0.5.0

Semantic HTML table output with CSS theme support for web dashboards, documentation, and email reports.

```html
<table class="table table-striped">
  <thead>
    <tr><th>Name</th><th>Age</th><th>City</th></tr>
  </thead>
  <tbody>
    <tr><td>Alice</td><td>30</td><td>NYC</td></tr>
    <tr><td>Bob</td><td>25</td><td>LA</td></tr>
  </tbody>
</table>
```

**Characteristics:**
- Semantic HTML5 markup (`<table>`, `<thead>`, `<tbody>`, `<tr>`, `<th>`, `<td>`)
- Multiple CSS themes (Bootstrap, Tailwind, Minimal, Custom)
- Automatic HTML escaping (`<`, `>`, `&`, quotes)
- Optional inline CSS inclusion
- Optional ANSI-to-HTML color conversion
- Clean, accessible HTML output

**Usage:**
```rust
let formatter = HtmlFormatter::new();  // Minimal theme
// or with Bootstrap theme
let formatter = HtmlFormatter::with_theme( HtmlTheme::Bootstrap );
// or with custom CSS classes
let formatter = HtmlFormatter::with_table_class( "my-table" );
```

**Themes:**
- **Minimal**: Basic `<table>` with no classes (pure semantic HTML)
- **Bootstrap**: Bootstrap 5 classes (`table table-striped table-hover`)
- **Tailwind**: Tailwind CSS classes (`min-w-full divide-y divide-gray-200`)
- **Custom**: User-provided CSS class string

**HTML Escaping:**
- `<``&lt;`
- `>``&gt;`
- `&``&amp;`
- `"``&quot;`
- `'``&#x27;`

**Example:**
```rust
let data = RowBuilder::new( vec![ "Name".into(), "Status".into() ] )
  .add_row( vec![ "Task 1".into(), "Done".into() ] )
  .add_row( vec![ "Task <2>".into(), "Pending & active".into() ] )
  .build_view();

let formatter = HtmlFormatter::with_theme( HtmlTheme::Bootstrap );
let html = formatter.format( &data )?;
```

**Output:**
```html
<table class="table table-striped">
  <thead>
    <tr>
      <th>Name</th>
      <th>Status</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Task 1</td>
      <td>Done</td>
    </tr>
    <tr>
      <td>Task &lt;2&gt;</td>
      <td>Pending &amp; active</td>
    </tr>
  </tbody>
</table>
```

**Use cases:**
- Web dashboards and admin panels
- Static site generation
- HTML email reports
- Documentation generation (embeddable tables)
- Export data for web display

**Feature Flag:** `format_html` (zero dependencies, part of optional bundle)

### Sql Format (Database INSERT Statements) - NEW v0.5.0

Generate SQL INSERT statements for database loading from tabular data.

```sql
INSERT INTO users (name, age, city) VALUES
  ('Alice', 30, 'NYC'),
  ('Bob', 25, 'LA');
```

**Characteristics:**
- Multi-row INSERT statement generation
- SQL dialect support (PostgreSQL, MySQL, SQLite, ANSI)
- Automatic SQL escaping (quotes, special chars)
- Configurable table name
- NULL value handling
- Batch insert optimization

**Usage:**
```rust
let formatter = SqlFormatter::new( "users" );  // Table name
// or with specific dialect
let formatter = SqlFormatter::with_dialect( "users", SqlDialect::PostgreSQL );
```

**Dialects:**
- **ANSI** (default): Standard SQL compliant
- **PostgreSQL**: PostgreSQL-specific syntax
- **MySQL**: MySQL/MariaDB syntax
- **SQLite**: SQLite3 syntax

**SQL Escaping:**
- Single quotes doubled: `'``''`
- Backslashes escaped: `\``\\` (MySQL)
- NULL values: Empty strings → `NULL`
- Numbers: Unquoted

**Example:**
```rust
let data = RowBuilder::new( vec![ "name".into(), "age".into(), "email".into() ] )
  .add_row( vec![ "Alice".into(), "30".into(), "alice@example.com".into() ] )
  .add_row( vec![ "Bob O'Brien".into(), "25".into(), "bob@example.com".into() ] )
  .build_view();

let formatter = SqlFormatter::new( "customers" );
let sql = formatter.format( &data )?;
```

**Output:**
```sql
INSERT INTO customers (name, age, email) VALUES
  ('Alice', 30, 'alice@example.com'),
  ('Bob O''Brien', 25, 'bob@example.com');
```

**PostgreSQL-specific features:**
- `ON CONFLICT` clause support
- `RETURNING` clause support
- Array literal support

**MySQL-specific features:**
- Backtick quoting for identifiers
- `ON DUPLICATE KEY UPDATE` support

**Use cases:**
- Database seeding and migrations
- ETL pipelines (extract-transform-load)
- Data export for database loading
- Test data generation
- Quick INSERT statement creation

**Feature Flag:** `format_sql` (zero dependencies, part of optional `data_formats` bundle)

### Expanded Format (Vertical Records)

Each row displayed vertically as key-value pairs. Supports two styles: PostgreSQL `\x` mode and property list.

**PostgreSQL Style (default):**
```text
-[ RECORD 1 ]
sid   | 3
sname | Alice
gap   | 5
-[ RECORD 2 ]
sid   | 6
sname | Joe
gap   | 1
```

**Property List Style (with default gray keys):**
```text
Command:           sleep 10 && echo hello1
Working Directory: /
Status:            Completed
Duration:          10 seconds

Command:           sleep 5 && echo hello2
Working Directory: /home
Status:            Failed
Duration:          3 seconds
```

Note: Keys appear in gray in terminal output by default when using `property_style()`.

**Characteristics:**
- Vertical layout
- One record per block
- Key-value pairs with alignment
- Configurable record separators (or none)
- Configurable padding location (before or after separator)
- Easy reading for wide tables
- Optional ANSI color support for keys (terminal output)

**Formatter Parameters:**
- `padding_side`: Where to place alignment padding (`BeforeSeparator` or `AfterSeparator`)
- `colorize_keys`: Enable/disable key coloring (default: `false`)
- `key_color`: ANSI color code for keys (default: `\x1b[90m` gray)
- `record_separator`: Format string for section headers (empty string to disable)
- `key_value_separator`: Separator between key and value (` | ` or `: `)
- `show_record_numbers`: Show record numbers in separator (only when separator non-empty)

**Padding Styles:**
- `BeforeSeparator`: Keys padded before separator - `Name   | Value`
- `AfterSeparator`: Values padded after separator - `Name: Value`

**Use cases:** Wide tables with many columns, detailed record inspection, configuration display, command output, terminal logs, property files

### Tree Format (Hierarchical Outline)

Hierarchical tree structure with parent-child relationships.

```text
project
├── src
│   ├── main.rs (1024 bytes)
│   └── lib.rs (2048 bytes)
└── Cargo.toml (256 bytes)
```

**Characteristics:**
- Hierarchical layout
- Parent-child relationships
- Box-drawing characters
- Unlimited nesting depth
- Shows containment structure

**Use cases:** File systems, call graphs, org charts, nested categories

### Aligned Tree Format (Column-Aligned Hierarchical) - NEW v0.2.0

Hierarchical tree with multi-column attributes aligned vertically across all levels.

```text
├── api_ollama  v0.1.0  (api/ollama)
├── as_curl     v0.1.0  (module/as_curl)
│   ├── dep1  v2.0.0  (path/to/dep1)
│   └── dep2  v1.5.0  (path/to/dep2)
└── unikit      v0.1.0  (service/unikit)
```

**Characteristics:**
- Hierarchical layout with tree symbols
- Multiple columns per node (name, version, path, etc.)
- Vertical column alignment across all tree depths
- Automatic width calculation
- Configurable column separator
- Preserves tree structure (├──, │, └──)

**Use cases:** Package dependency trees, file listings with metadata, process trees with stats, any hierarchical data with aligned attributes

**Key Difference from Regular Tree**: Regular tree shows single data value per node; aligned tree shows multiple columns with vertical alignment, making it much easier to scan and compare attributes across different tree levels.

### Unified Format Interface (NEW in v0.4.0)

The Format trait provides a unified interface for all output formatters, enabling format-agnostic code with granular feature flags for minimal dependencies.

**Design Goals:**
1. **Unified Interface**: Same API for all formatters (table, json, yaml, toml, text)
2. **Canonical Data Format**: TableView struct as common interchange format
3. **Granular Features**: Each formatter behind optional feature flag
4. **Zero-Cost Abstractions**: Unused formatters compile to zero code/deps

**Core Types:**

```rust
/// Canonical data format for all formatters
pub struct TableView
{
  pub metadata : TableMetadata,
  pub rows : Vec< Vec< String > >,
}

/// Unified formatting interface
pub trait Format
{
  fn format( &self, data : &TableView ) -> Result< String, FormatError >;
}
```

**Available Formatters:**

| Formatter | Feature Flag | Dependencies | Use Case |
|-----------|-------------|--------------|----------|
| TableFormatter | `format_table` | None | Visual table output |
| ExpandedFormatter | `format_expanded` | None | Vertical records |
| TreeFormatter | `format_tree` | None | Hierarchical display |
| LogfmtFormatter | `format_logfmt` | None | Structured logging |
| HtmlFormatter | `format_html` | None | Web tables (HTML) |
| SqlFormatter | `format_sql` | None | SQL INSERT statements |
| JsonFormatter | `format_json` | serde, serde_json | Data interchange, APIs |
| YamlFormatter | `format_yaml` | serde, serde_yaml | Configuration files |
| TomlFormatter | `format_toml` | serde, toml | Rust config files |
| TextFormatter | `format_text` | None | Human-readable lists |

**Feature Bundles:**
- `visual_formats` = `format_table` + `format_expanded` + `format_tree` + `format_logfmt` (default)
- `web_formats` = `format_html` + `format_sql`
- `data_formats` = `format_json` + `format_yaml` + `format_toml`
- `all_formats` = `visual_formats` + `web_formats` + `data_formats` + `format_text`

**Usage Pattern:**

```rust
use tree_fmt::{ RowBuilder, Format };

// Build data once
let view = RowBuilder::new( vec![ "Name".into(), "Age".into() ] )
  .add_row( vec![ "Alice".into(), "30".into() ] )
  .build_view();  // NEW: Returns TableView instead of TreeNode

// Use with different formatters through unified interface
#[ cfg( feature = "format_json" ) ]
{
  use tree_fmt::JsonFormatter;
  let json = JsonFormatter::new();
  let output = Format::format( &json, &view )?;
}

#[ cfg( feature = "format_table" ) ]
{
  use tree_fmt::TableFormatter;
  let table = TableFormatter::with_config( TableConfig::plain() );
  let output = Format::format( &table, &view )?;
}
```

**Migration from TreeNode:**
- Existing API unchanged: `RowBuilder::build()` still returns `TreeNode<String>`
- New API available: `RowBuilder::build_view()` returns `TableView`
- Backward compatible: `TableView::to_tree_node()` converts back to TreeNode

**Key Benefits:**
- Write format-agnostic rendering code
- Minimal dependencies with granular features
- Easy addition of new format types
- Consistent error handling across formatters

### Color Themes (Advanced Feature) - NEW v0.5.0

Predefined color schemes for visual formatters with consistent styling across Table, Expanded, and Tree formatters.

**Purpose**: Provide easy-to-use, professionally designed color schemes for terminal output without manual ANSI code management.

**Available Themes:**

1. **Dark** - High contrast for dark terminals
   - Headers: Bright cyan
   - Borders: Dim white
   - Alternating rows: Default + dark gray background
   - Tree branches: Cyan

2. **Light** - Optimized for light terminals
   - Headers: Dark blue
   - Borders: Dark gray
   - Alternating rows: White + light gray background
   - Tree branches: Blue

3. **Monokai** - Popular code editor theme
   - Headers: Bright magenta
   - Borders: Dark gray
   - Alternating rows: Black + dark gray background
   - Tree branches: Green

4. **Solarized** - Low-contrast scientific palette
   - Headers: Yellow
   - Borders: Base01
   - Alternating rows: Base03 + base02 background
   - Tree branches: Cyan

5. **Nord** - Arctic-inspired cool palette
   - Headers: Frost blue
   - Borders: Polar night
   - Alternating rows: Default + polar night background
   - Tree branches: Frost green

6. **Dracula** - Dark theme with vibrant colors
   - Headers: Purple
   - Borders: Comment gray
   - Alternating rows: Background + selection background
   - Tree branches: Pink

**Usage:**

```rust
use tree_fmt::{ RowBuilder, TableFormatter, TableConfig, ColorTheme };

let data = RowBuilder::new( vec![ "Name".into(), "Status".into() ] )
  .add_row( vec![ "Alice".into(), "Active".into() ] )
  .add_row( vec![ "Bob".into(), "Pending".into() ] )
  .build_view();

// Apply theme to table
let formatter = TableFormatter::with_config(
  TableConfig::bordered().with_theme( ColorTheme::Dark )
);

// Apply theme to expanded format
let formatter = ExpandedFormatter::with_config(
  ExpandedConfig::postgres_style().with_theme( ColorTheme::Monokai )
);

// Apply theme to tree format
let formatter = TreeFormatter::with_config(
  TreeConfig::new().with_theme( ColorTheme::Nord )
);
```

**Theme Application:**

Themes automatically configure:
- **TableConfig**: `header_color`, `alternating_rows`, `row_color1`, `row_color2`, border colors
- **ExpandedConfig**: `key_color`, record separator colors
- **TreeConfig**: Branch symbol colors, data colors

**Custom Theme Creation:**

```rust
use tree_fmt::ColorTheme;

let custom_theme = ColorTheme::custom()
  .header_color( "\x1b[38;5;208m" )  // Orange
  .border_color( "\x1b[38;5;240m" )  // Gray
  .row_color1( "\x1b[0m" )           // Default
  .row_color2( "\x1b[48;5;235m" )    // Dark gray bg
  .build();

let formatter = TableFormatter::with_config(
  TableConfig::bordered().with_theme( custom_theme )
);
```

**Color Reset:**

All themes include automatic color reset (`\x1b[0m`) after colored elements to prevent color bleeding into subsequent output.

**Terminal Compatibility:**

- Uses standard ANSI escape codes
- 256-color support (` \x1b[38;5;Nm` format)
- Gracefully degrades in non-color terminals
- No-color mode: `ColorTheme::None` disables all colors

**Feature Flag:** `themes` (zero dependencies, optional enhancement)

**Integration:**

```rust
#[ cfg( feature = "themes" ) ]
{
  use tree_fmt::ColorTheme;
  let config = TableConfig::bordered().with_theme( ColorTheme::Dark );
}
```

**Use Cases:**
- Professional terminal UIs
- Consistent branding across CLI tools
- Accessibility (high-contrast themes)
- Developer tools with syntax-like highlighting
- Log viewers and monitoring dashboards

## Architecture

### Modular File Structure

**v0.4.0 Modular Architecture** - Separated concerns across 16 source files:

```
src/
├── lib.rs                     # Re-exports public API
├── data.rs                    # TreeNode, TableView struct, TableShapedView trait
├── builder.rs                 # TreeBuilder (hierarchical)
├── table_tree.rs              # RowBuilder (table-shaped)
├── config.rs                  # TreeConfig, TableConfig, ExpandedConfig
├── conversions.rs             # Tree↔Table conversions, FlattenConfig
├── helpers.rs                 # visual_len, pad_to_width
└── formatters/
    ├── mod.rs                 # TableShapedFormatter trait, Format trait re-export
    ├── format_trait.rs        # Format trait, FormatError (NEW v0.4.0)
    ├── tree.rs                # TreeFormatter with format() and format_aligned() methods
    ├── table.rs               # TableFormatter
    ├── expanded.rs            # ExpandedFormatter
    ├── json.rs                # JsonFormatter (NEW v0.4.0)
    ├── yaml.rs                # YamlFormatter (NEW v0.4.0)
    ├── toml_fmt.rs            # TomlFormatter (NEW v0.4.0)
    └── text.rs                # TextFormatter (NEW v0.4.0)
```

### Layer 1: Single Data Structure

**TreeNode<T>** serves both hierarchical and tabular use cases.

```rust
/// Universal data structure for trees and tables
pub struct TreeNode<T> {
  pub name: String,
  pub data: Option<T>,
  pub children: Vec<TreeNode<T>>,
}
```

**Tabular data representation:**
```
root
├── 1 (row name)
│   ├── sid: "3"
│   ├── sname: "Alice"
│   └── gap: "5"
└── 2 (row name)
    ├── sid: "6"
    ├── sname: "Joe"
    └── gap: "1"
```

**Design invariants:**
- Hierarchical trees: Directories have `data = None`, files have `data = Some(T)`
- Table-shaped trees: Root has row nodes, row nodes have column-named children
- Table validation: All row nodes have identical child structure (same column names)

### Layer 2: Table Construction Helpers

Ergonomic builders and traits for working with table-shaped trees.

```rust
/// Fluent builder for table-shaped trees
pub struct RowBuilder {
  root: TreeNode<String>,
  headers: Vec<String>,
  row_count: usize,
}

impl RowBuilder {
  pub fn new(headers: Vec<String>) -> Self;

  // Fluent API (consuming self)
  pub fn add_row(self, row: Vec<String>) -> Self;
  pub fn add_row_with_name(self, row_name: String, row: Vec<String>) -> Self;

  // Mutable API (for loops)
  pub fn add_row_mut(&mut self, row: Vec<String>);
  pub fn add_row_with_name_mut(&mut self, row_name: String, row: Vec<String>);

  pub fn build(self) -> TreeNode<String>;
}

/// Generic trait for extracting table data from trees
pub trait TableShapedView {
  fn extract_headers(&self) -> Option<Vec<String>>;
  fn is_table_shaped(&self) -> bool;
  fn to_rows(&self) -> Vec<Vec<String>>;
}

impl<T: std::fmt::Display> TableShapedView for TreeNode<T> {
  // Extract column names from first row's children
  fn extract_headers(&self) -> Option<Vec<String>>;

  // Validate all rows have identical structure
  fn is_table_shaped(&self) -> bool;

  // Extract row data as Vec<Vec<String>> (converts T to String via Display)
  fn to_rows(&self) -> Vec<Vec<String>>;
}
```

**Table construction patterns:**
- **Fluent builder**: Use `RowBuilder::new().add_row().add_row().build()`
- **Mutable builder**: Use `builder.add_row_mut()` in loops
- **Manual construction**: Use `TreeBuilder` for custom row naming
- **Generic support**: TableShapedView works with any `T: Display`

### Layer 3: Display Formatters (Format-Specific)

Three formatters all working with TreeNode<T>.

```rust
/// Horizontal table formatter (uses TableShapedView trait)
pub struct TableFormatter {
  config: TableConfig,
}

/// Vertical record formatter (uses TableShapedView trait)
pub struct ExpandedFormatter {
  config: ExpandedConfig,
}

/// Hierarchical tree formatter (native TreeNode rendering)
pub struct TreeFormatter {
  config: TreeConfig,
  symbols: TreeSymbols,
}

/// Common trait for table-shaped formatters (polymorphism)
pub trait TableShapedFormatter {
  fn format(&self, tree: &TreeNode<String>) -> String;
}

impl TableShapedFormatter for TableFormatter { ... }
impl TableShapedFormatter for ExpandedFormatter { ... }
```

**Formatter design:**
- TableFormatter/ExpandedFormatter use `TableShapedView` trait to extract headers/rows
- TreeFormatter renders TreeNode<T> directly with method-level generics
- Configuration controls display options (borders, symbols, alignment)
- All formatters support both String return and Write trait output
- `format()` returns String, `write_to()` writes to any io::Write

**Configuration builder pattern:**
All config structs have fluent builder APIs:
```rust
let config = TreeConfig::new()
  .show_branches(false)
  .max_depth(Some(3));
```

## API Contract

### Data Representation Types

```rust
/// Universal hierarchical data structure
pub struct TreeNode<T> {
  pub name: String,
  pub data: Option<T>,
  pub children: Vec<TreeNode<T>>,
}

impl<T> TreeNode<T> {
  pub const fn new(name: String, data: Option<T>) -> Self;
}

/// Tree builder for path-based construction
pub struct TreeBuilder<T> {
  root: TreeNode<T>,
}

impl<T> TreeBuilder<T> {
  pub fn new(root_name: impl Into<String>) -> Self;
  pub fn insert(self, path: &[&str], data: T) -> Self;
  pub fn build(self) -> TreeNode<T>;
}

impl<T: Clone> TreeBuilder<T> {
  pub fn from_items<I, P>(root_name: impl Into<String>, items: I) -> Self
  where
    I: IntoIterator<Item = (P, T)>,
    P: AsRef<[String]>;
}

/// Table construction helper with fluent API
pub struct RowBuilder {
  root: TreeNode<String>,
  headers: Vec<String>,
  row_count: usize,
}

impl RowBuilder {
  pub fn new(headers: Vec<String>) -> Self;

  // Fluent API (consuming, chainable)
  #[must_use]
  pub fn add_row(self, row: Vec<String>) -> Self;
  #[must_use]
  pub fn add_row_with_name(self, row_name: String, row: Vec<String>) -> Self;

  // Mutable API (for programmatic use)
  pub fn add_row_mut(&mut self, row: Vec<String>);
  pub fn add_row_with_name_mut(&mut self, row_name: String, row: Vec<String>);

  pub fn build(self) -> TreeNode<String>;
}

/// Generic trait for working with table-shaped trees
pub trait TableShapedView {
  fn extract_headers(&self) -> Option<Vec<String>>;
  fn is_table_shaped(&self) -> bool;
  fn to_rows(&self) -> Vec<Vec<String>>;
}

impl<T: std::fmt::Display> TableShapedView for TreeNode<T> {
  // Converts T to String via Display trait
  fn extract_headers(&self) -> Option<Vec<String>>;
  fn is_table_shaped(&self) -> bool;
  fn to_rows(&self) -> Vec<Vec<String>>;
}
```

### Conversion Utilities

```rust
/// Tree-to-table flattening configuration
pub struct FlattenConfig {
  pub include_path: bool,
  pub include_name: bool,
  pub include_depth: bool,
  pub include_data: bool,
  pub column_names: Option<(String, String, String, String)>,
}

impl FlattenConfig {
  pub fn new() -> Self;

  // Fluent builder methods
  #[must_use]
  pub fn include_path(self, include: bool) -> Self;
  #[must_use]
  pub fn include_name(self, include: bool) -> Self;
  #[must_use]
  pub fn include_depth(self, include: bool) -> Self;
  #[must_use]
  pub fn include_data(self, include: bool) -> Self;
  #[must_use]
  pub fn column_names(self, path: String, name: String, depth: String, data: String) -> Self;
}

/// Flatten hierarchical tree to table-shaped tree (default columns)
pub fn flatten_to_table_tree<T: Display>(tree: &TreeNode<T>) -> TreeNode<String>;

/// Flatten with custom column selection and naming
pub fn flatten_to_table_tree_with_config<T: Display>(
  tree: &TreeNode<T>,
  config: &FlattenConfig
) -> TreeNode<String>;
```

### Formatter Parameter Types

#### BorderVariant, HeaderSeparatorVariant, ColumnSeparator (NEW v0.3.0)

```rust
/// Border rendering variant for tables
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BorderVariant
{
  None,       // No borders, space-separated
  Ascii,      // Pipe borders: | + -
  AsciiGrid,  // Full ASCII grid: +---+
  Unicode,    // Unicode box drawing: ┌─┬─┐
  Markdown,   // Markdown table: | col |
}

/// Header separator line variant
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HeaderSeparatorVariant
{
  None,       // No separator line
  Dash,       // Dash-only: -----
  AsciiGrid,  // ASCII grid: +-----+
  Unicode,    // Unicode: ├─────┤
  Markdown,   // Markdown: |-----|
}

/// Column separator configuration
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ColumnSeparator
{
  Spaces( usize ),      // N spaces between columns
  Character( char ),    // Single character (|, ,, \t)
  String( String ),     // Custom string
}
```

#### TableConfig

```rust
/// Formatter parameters for table output
#[derive(Debug, Clone)]
pub struct TableConfig {
  // Legacy fields (v0.1-v0.2)
  pub show_borders: bool,          // Deprecated: use border_variant
  pub column_widths: Vec<usize>,
  pub align_right: Vec<bool>,

  // NEW in v0.3.0
  pub border_variant: BorderVariant,
  pub header_separator_variant: HeaderSeparatorVariant,
  pub column_separator: ColumnSeparator,
  pub outer_padding: bool,
  pub inner_padding: usize,
  pub colorize_header: bool,
  pub header_color: String,
  pub alternating_rows: bool,
  pub row_color1: String,
  pub row_color2: String,
  pub min_column_width: usize,
  pub max_column_width: Option<usize>,
  pub truncation_marker: String,
}

impl TableConfig {
  // Construction
  pub fn new() -> Self;

  // Style presets (NEW v0.3.0)
  pub fn plain() -> Self;
  pub fn minimal() -> Self;
  pub fn bordered() -> Self;
  pub fn markdown() -> Self;
  pub fn grid() -> Self;
  pub fn unicode_box() -> Self;
  pub fn csv() -> Self;
  pub fn tsv() -> Self;
  pub fn compact() -> Self;

  // Legacy builders (v0.1-v0.2)
  #[must_use]
  #[deprecated(note = "Use border_variant() instead")]
  pub fn show_borders(self, show: bool) -> Self;
  #[must_use]
  pub fn column_widths(self, widths: Vec<usize>) -> Self;
  #[must_use]
  pub fn align_right(self, align: Vec<bool>) -> Self;

  // NEW builders (v0.3.0)
  #[must_use]
  pub fn border_variant(self, variant: BorderVariant) -> Self;
  #[must_use]
  pub fn header_separator_variant(self, variant: HeaderSeparatorVariant) -> Self;
  #[must_use]
  pub fn column_separator(self, sep: ColumnSeparator) -> Self;
  #[must_use]
  pub fn outer_padding(self, enabled: bool) -> Self;
  #[must_use]
  pub fn inner_padding(self, spaces: usize) -> Self;
  #[must_use]
  pub fn colorize_header(self, enabled: bool) -> Self;
  #[must_use]
  pub fn header_color(self, color: String) -> Self;
  #[must_use]
  pub fn alternating_rows(self, enabled: bool) -> Self;
  #[must_use]
  pub fn row_colors(self, color1: String, color2: String) -> Self;
  #[must_use]
  pub fn min_column_width(self, width: usize) -> Self;
  #[must_use]
  pub fn max_column_width(self, width: Option<usize>) -> Self;
  #[must_use]
  pub fn truncation_marker(self, marker: String) -> Self;
}

/// Formatter parameters for expanded output
#[derive(Debug, Clone)]
pub struct ExpandedConfig {
  pub record_separator: String,
  pub key_value_separator: String,
  pub show_record_numbers: bool,
}

impl ExpandedConfig {
  pub fn new() -> Self;
  #[must_use]
  pub fn record_separator(self, separator: String) -> Self;
  #[must_use]
  pub fn key_value_separator(self, separator: String) -> Self;
  #[must_use]
  pub fn show_record_numbers(self, show: bool) -> Self;
}

/// Formatter parameters for tree output
#[derive(Debug, Clone)]
pub struct TreeConfig {
  pub show_branches: bool,
  pub show_root: bool,
  pub indent_size: usize,
  pub max_depth: Option<usize>,
  pub column_separator: String,
  pub min_column_width: usize,
}

impl TreeConfig {
  pub fn new() -> Self;
  #[must_use]
  pub fn show_branches(self, show: bool) -> Self;
  #[must_use]
  pub fn show_root(self, show: bool) -> Self;
  #[must_use]
  pub fn indent_size(self, size: usize) -> Self;
  #[must_use]
  pub fn max_depth(self, depth: Option<usize>) -> Self;
  #[must_use]
  pub fn column_separator(self, separator: String) -> Self;
  #[must_use]
  pub fn min_column_width(self, width: usize) -> Self;
}

/// Tree box-drawing symbols
#[derive(Debug, Clone)]
pub struct TreeSymbols {
  pub branch: &'static str,
  pub last_branch: &'static str,
  pub vertical: &'static str,
  pub space: &'static str,
}
```

### Formatter APIs

#### TableFormatter (Horizontal Tabular Display)

```rust
impl TableFormatter {
  // Construction
  pub fn new() -> Self;
  pub const fn with_config(config: TableConfig) -> Self;

  // Format table-shaped tree (extracts headers/rows via TableShapedView)
  pub fn format(&self, tree: &TreeNode<String>) -> String;

  // Format hierarchical tree (flattens to path/name/depth/data)
  pub fn format_tree<T: Display>(&self, tree: &TreeNode<T>) -> String;

  // Write directly to io::Write
  pub fn write_to<W: std::io::Write>(&self, tree: &TreeNode<String>, writer: &mut W) -> std::io::Result<()>;
}

impl TableShapedFormatter for TableFormatter {
  fn format(&self, tree: &TreeNode<String>) -> String;
}
```

#### ExpandedFormatter (Vertical Record Display)

```rust
impl ExpandedFormatter {
  // Construction
  pub fn new() -> Self;
  pub const fn with_config(config: ExpandedConfig) -> Self;

  // Format table-shaped tree (extracts headers/rows via TableShapedView)
  pub fn format(&self, tree: &TreeNode<String>) -> String;

  // Format hierarchical tree (flattens to path/name/depth/data)
  pub fn format_tree<T: Display>(&self, tree: &TreeNode<T>) -> String;

  // Write directly to io::Write
  pub fn write_to<W: std::io::Write>(&self, tree: &TreeNode<String>, writer: &mut W) -> std::io::Result<()>;
}

impl TableShapedFormatter for ExpandedFormatter {
  fn format(&self, tree: &TreeNode<String>) -> String;
}
```

#### TreeFormatter (Hierarchical Tree Display)

```rust
impl TreeFormatter {
  // Construction
  pub fn new() -> Self;
  pub fn with_config(config: TreeConfig) -> Self;
  pub fn with_symbols(symbols: TreeSymbols) -> Self;

  // Format tree data with custom renderer (method-level generics)
  pub fn format<T, F>(&self, tree: &TreeNode<T>, render_item: F) -> String
  where F: Fn(&T) -> String;

  // Format tree with column-aligned data (NEW merged from AlignedTreeFormatter)
  pub fn format_aligned(&self, tree: &TreeNode<ColumnData>) -> String;

  // Format tree with aggregated directory totals
  pub fn format_with_aggregation<T, V, A, F, D, C>(
    &self,
    tree: &TreeNode<T>,
    grand_total: V,
    aggregate_fn: A,
    convert_to_f64: C,
    render_file: F,
    render_directory: D,
  ) -> String
  where
    V: Copy + Add<Output = V> + Default + Sum,
    A: Fn(&T) -> V,
    C: Fn(V) -> f64,
    F: Fn(&T, V, f64) -> String,
    D: Fn(&str, V, f64) -> String;

  // Write directly to io::Write
  pub fn write_to<T, F, W>(&self, tree: &TreeNode<T>, writer: &mut W, render_item: F) -> std::io::Result<()>
  where
    F: Fn(&T) -> String,
    W: std::io::Write;
}
```

#### TableShapedFormatter Trait (Polymorphism)

```rust
/// Common trait for table-shaped formatters
pub trait TableShapedFormatter {
  fn format(&self, tree: &TreeNode<String>) -> String;
}

// Usage with trait objects
let formatters: Vec<Box<dyn TableShapedFormatter>> = vec![
  Box::new(TableFormatter::new()),
  Box::new(ExpandedFormatter::new()),
];

for formatter in formatters {
  let output = formatter.format(&tree);
}
```

### ANSI and Unicode Support

```rust
// Helper functions for ANSI color code and Unicode display width handling
pub fn visual_len(text: &str) -> usize;
pub fn pad_to_width(text: &str, target_width: usize, align_right: bool) -> String;
```

#### `visual_len()`

Calculates the visible character count (Unicode codepoints), ignoring ANSI escape sequences.

**Measurement**: Character count using `chars().count()` (not display width).

**Behavior**:
- ANSI escape sequences: 0 (filtered out)
- ASCII characters: 1 per char
- Cyrillic/Latin characters: 1 per char
- CJK characters: 1 per char (codepoint count, not display width)
- Emoji: 1 per codepoint (may be multiple codepoints for complex emoji)

**Note**: This function counts Unicode codepoints, not terminal display width. For display-width-aware operations, use `unicode-width` crate.

#### `pad_to_width()` - Display Width Aware (v0.5.0+)

Pads string to specified display width, handling wide Unicode characters correctly.

**Measurement**: Display width using East Asian Width property (`unicode-width` crate).

**API Contract**:
```rust
/// Pads string to target display width with spaces.
///
/// Uses display width (terminal columns) instead of character count.
/// Correctly handles:
/// - Wide characters (CJK, emoji): 2 display width
/// - Normal characters (ASCII, Cyrillic, Latin): 1 display width
/// - Zero-width characters (combining marks): 0 display width
/// - ANSI escape sequences: 0 display width (filtered out)
///
/// If text display width already >= target_width, returns text unchanged.
///
/// # Arguments
///
/// * `text` - Input text (may contain ANSI codes)
/// * `target_width` - Target display width in terminal columns
/// * `align_right` - If true, pad left; if false, pad right
///
/// # Returns
///
/// Padded string with correct display width for terminal alignment.
///
/// # Examples
///
/// ```rust
/// use tree_fmt::pad_to_width;
///
/// // ASCII text (1 display width per char)
/// let padded = pad_to_width("Hello", 10, false);
/// assert_eq!(unicode_width::UnicodeWidthStr::width(padded.as_str()), 10);
///
/// // CJK text (2 display width per char)
/// let padded = pad_to_width("日本語", 10, false);  // 3 chars, 6 display width
/// assert_eq!(unicode_width::UnicodeWidthStr::width(padded.as_str()), 10);
///
/// // Emoji text (2 display width per char)
/// let padded = pad_to_width("🎉", 10, false);  // 1 char, 2 display width
/// assert_eq!(unicode_width::UnicodeWidthStr::width(padded.as_str()), 10);
/// ```
///
/// # Fix(issue-003)
///
/// Root cause: Previous implementation mixed character-count-based padding
/// with Rust's display-width-based formatting (`{:<N}`), causing
/// misalignment with wide Unicode characters (CJK, emoji).
///
/// Pitfall: Always use display width for terminal alignment, not char count.
/// Display width ≠ char count ≠ byte count for Unicode.
/// CJK/emoji have display width = 2, not 1.
pub fn pad_to_width(text: &str, target_width: usize, align_right: bool) -> String;
```

**Character Width Reference**:

| Character Type | Example | Byte Count | Char Count | Display Width |
|----------------|---------|------------|------------|---------------|
| ASCII | "Hello" | 5 | 5 | 5 |
| Cyrillic | "Привіт" | 12 | 6 | 6 |
| CJK | "日本語" | 9 | 3 | **6** |
| Emoji | "🎉" | 4 | 1 | **2** |
| Combining | "é" (e + ◌́) | 3 | 2 | 1 |
| ANSI | "\x1b[31mtext\x1b[0m" | 14 | 4 (visible) | 4 |

**Key Insight**: Multi-byte encoding (byte count > char count) does NOT imply wide display (Cyrillic is multi-byte but 1 display width). Only CJK and emoji have display width = 2.

## Functional Requirements

### FR-1: Data Representation

**FR-1.1**: `TreeNode<T>` - hierarchical data with generic type support
**FR-1.2**: `RowBuilder` - fluent builder for table-shaped trees
**FR-1.3**: Support unlimited nesting depth in trees
**FR-1.4**: Validate table row lengths match header count

### FR-2: Data Conversion

**FR-2.1**: Convert hierarchical tree to table-shaped tree (flatten)
**FR-2.2**: Support generic type `T` with `Display` trait for conversions
**FR-2.3**: Preserve all data during conversion
**FR-2.4**: Customizable column selection via `FlattenConfig`

### FR-3: Table Format (Horizontal Tabular Display)

**FR-3.1**: Format table-shaped tree as horizontal table
**FR-3.2**: Format hierarchical tree as table (auto-flatten)
**FR-3.3**: Unicode borders with configurable styles
**FR-3.4**: Automatic column width calculation
**FR-3.5**: Manual column width specification
**FR-3.6**: Per-column alignment (left/right)
**FR-3.7**: Header row with separator line

### FR-4: Expanded Format (Vertical Record Display)

**FR-4.1**: Format table-shaped tree as vertical records
**FR-4.2**: Format hierarchical tree as records (auto-flatten)
**FR-4.3**: Record separators with sequential numbering
**FR-4.4**: Key-value pair display for each field
**FR-4.5**: Configurable separators and styling
**FR-4.6**: Align keys and values properly

### FR-5: Tree Format (Hierarchical Display)

**FR-5.1**: Format `TreeNode<T>` with box-drawing characters
**FR-5.2**: Format table-shaped tree as hierarchical tree
**FR-5.3**: Unicode symbols (`├──`, `└──`, `│`)
**FR-5.4**: Customizable symbols and indentation
**FR-5.5**: Closure-based data rendering
**FR-5.6**: Display file nodes with data
**FR-5.7**: Display directory nodes without data
**FR-5.8**: Aggregated subtree totals with percentages

### FR-6: ANSI Color Support

**FR-6.1**: Calculate visual length excluding ANSI codes
**FR-6.2**: Pad strings accounting for ANSI codes
**FR-6.3**: Proper alignment with colored cells (all formats)
**FR-6.4**: Support common ANSI escape sequences (`\x1b[...m`)

### FR-7: Builder Patterns

**FR-7.1**: Fluent RowBuilder API (chainable methods)
**FR-7.2**: Mutable RowBuilder API (for loops)
**FR-7.3**: Config builder pattern for all configs
**FR-7.4**: `#[must_use]` attributes on consuming methods

### FR-8: Output Flexibility

**FR-8.1**: String return from `format()` methods
**FR-8.2**: Write trait support via `write_to()` methods
**FR-8.3**: Zero-allocation output to io::Write

### FR-9: Edge Cases

**FR-9.1**: Empty tables return empty string in all formats
**FR-9.2**: Empty trees return empty string when formatted
**FR-9.3**: Single-row tables display correctly in all formats
**FR-9.4**: Generic TableShapedView works with any `T: Display`

## Implementation Details

### Data Representation Structures

**TreeNode<T>**:
```rust
pub struct TreeNode<T> {
  pub name: String,           // Node name (file/directory)
  pub data: Option<T>,        // None for directories
  pub children: Vec<TreeNode<T>>,
}
```

**Invariant**: Directories have `data = None`, files have `data = Some(T)`

**RowBuilder** (replaces legacy DataTable):
```rust
pub struct RowBuilder {
  root: TreeNode<String>,
  headers: Vec<String>,
  row_count: usize,
}
```

**Invariant**: All rows have length equal to `headers.len()`

### Data Conversion Algorithms

#### Hierarchical Tree → Table-Shaped Tree Conversion

**Algorithm** (via `flatten_to_table_tree`):
```rust
pub fn flatten_to_table_tree<T: Display>(tree: &TreeNode<T>) -> TreeNode<String> {
  // 1. Create headers: ["path", "name", "depth", "data"]
  // 2. Create RowBuilder with headers
  // 3. DFS traversal:
  //    - Track current path
  //    - Track current depth
  //    - For each node, add row: [path, name, depth, data]
  // 4. Return table-shaped tree
}
```

**Customizable via FlattenConfig**:
```rust
let config = FlattenConfig::new()
  .include_path(false)       // Exclude path column
  .include_depth(false)      // Exclude depth column
  .column_names(             // Custom column names
    "File Path".into(),
    "File Name".into(),
    "Level".into(),
    "Size".into()
  );

let flattened = flatten_to_table_tree_with_config(&tree, &config);
```

**Example (default columns)**:
```text
Tree:
project
├── src
│   └── main.rs (100)

Table-shaped tree:
root
├── 1
│   ├── path: "project"
│   ├── name: "project"
│   ├── depth: "0"
│   └── data: ""
├── 2
│   ├── path: "project/src"
│   ├── name: "src"
│   ├── depth: "1"
│   └── data: ""
└── 3
    ├── path: "project/src/main.rs"
    ├── name: "main.rs"
    ├── depth: "2"
    └── data: "100"
```

**Example (custom columns - name and data only)**:
```text
Config:
  .include_path(false)
  .include_depth(false)

Table-shaped tree:
root
├── 1
│   ├── name: "project"
│   └── data: ""
├── 2
│   ├── name: "src"
│   └── data: ""
└── 3
    ├── name: "main.rs"
    └── data: "100"
```

### Path-Based Insertion

**Algorithm**:
1. Split path into components
2. Traverse tree, creating intermediate nodes
3. Insert data at leaf node
4. Return updated builder for chaining

**Example**:
```rust
TreeBuilder::new("root")
  .insert(&["src", "main.rs"], 150)
  .insert(&["src", "lib.rs"], 200)
```

Creates:
```
root/
├── src/
    ├── main.rs (150)
    └── lib.rs (200)
```

### Format Rendering Algorithms

#### Table Format Algorithm

**Algorithm**:
```rust
impl TableFormatter {
  pub fn format(&self, tree: &TreeNode<String>) -> String {
    // 1. Extract headers via TableShapedView trait
    // 2. Extract rows via TableShapedView trait
    // 3. Calculate column widths (max of header and all rows)
    // 4. Format header row with padding
    // 5. Format separator line
    // 6. Format each data row with padding
    // 7. Return concatenated string
  }
}
```

**Column Width Calculation**: `max(header_width, max(row[i]_width for all rows))`

**Column Truncation** (NEW):

When `TableConfig::max_column_width` is set to `Some(width)`, cells exceeding this width are truncated:

```rust
// Truncation algorithm (ANSI-aware)
fn truncate_cell( cell : &str, max_width : usize, marker : &str ) -> String
{
  let visual_length = visual_len( cell );
  if visual_length <= max_width
  {
    return cell.to_string();
  }

  // Use ANSI-aware truncation
  let marker_len = visual_len( marker );
  let content_width = max_width.saturating_sub( marker_len );

  let truncated = strs_tools::ansi::truncate( cell, content_width );
  format!( "{}{}", truncated, marker )
}
```

**Truncation Behavior**:
- Applied during cell rendering in `format_row()`
- Uses visual length (ANSI color codes don't count toward width)
- Preserves ANSI codes in truncated output (colors/formatting maintained)
- Appends `truncation_marker` (default: "...") to truncated cells
- If marker doesn't fit, returns empty string with marker
- Applied to both header and data cells
- Disabled by default (`max_column_width = None`) for backward compatibility
- Column width calculation happens BEFORE truncation (based on full content)

**Example**:
```rust
let config = TableConfig::plain()
  .max_column_width( Some( 20 ) )
  .truncation_marker( "...".to_string() );
// Cell "Very long content that exceeds twenty characters"
// Becomes: "Very long conten..."  (20 chars total including marker)
```

**Multiline Cells** (NEW):

When cell content contains newline characters (`\n`), tables are rendered with multiline support using a two-pass algorithm:

```rust
// Multiline rendering algorithm
fn format_multiline_row( cells : &[String], column_widths : &[usize] ) -> String
{
  // Pass 1: Split all cells into lines and find maximum line count
  let split_cells : Vec<Vec<&str>> = cells
    .iter()
    .map( |cell| cell.lines().collect() )
    .collect();

  let row_height = split_cells
    .iter()
    .map( |lines| lines.len() )
    .max()
    .unwrap_or( 1 );

  // Pass 2: Render each line of the row
  let mut output = String::new();
  for line_idx in 0..row_height
  {
    for ( col_idx, cell_lines ) in split_cells.iter().enumerate()
    {
      let line = cell_lines.get( line_idx ).unwrap_or( &"" );
      let width = column_widths[ col_idx ];
      output.push_str( &pad_to_width( line, width, false ) );

      if col_idx < cells.len() - 1
      {
        append_column_separator( &mut output );
      }
    }
    output.push( '\n' );
  }

  output
}
```

**Multiline Behavior**:
- Detected automatically when ANY cell contains `\n` character
- Cells split on `\n` into individual lines (via `str::lines()`)
- Row height = maximum line count across all cells in that row
- Each line rendered separately with proper column alignment
- Shorter cells padded with empty strings to match row height
- Column separators and borders applied to each line
- Maintains alignment even with ANSI color codes (uses `visual_len()`)
- Applied per-row (different rows can have different heights)
- Backward compatible (single-line cells work unchanged)

**Multiline + Truncation Interaction**:

When both features are active:
1. Truncation applied BEFORE line splitting (to full cell content)
2. If truncated cell contains `\n`, multiline rendering still applies
3. Each LINE of a multiline cell can be individually truncated
4. Preferred: Apply truncation per-line after splitting for better visual result

```rust
// Combined algorithm (preferred implementation)
fn render_cell_with_both( cell : &str, max_width : Option<usize>, marker : &str )
  -> Vec<String>
{
  let lines : Vec<&str> = cell.lines().collect();

  lines
    .iter()
    .map( |line|
    {
      if let Some( width ) = max_width
      {
        truncate_cell( line, width, marker )
      }
      else
      {
        line.to_string()
      }
    })
    .collect()
}
```

**Feature Flags and Backward Compatibility**:
- Column truncation: Disabled by default (`max_column_width = None`)
- Multiline cells: Enabled automatically when `\n` detected
- No breaking changes to existing behavior
- Single-line cells without truncation work exactly as before
- CSV/TSV formats: Multiline disabled (newlines kept as literal `\n`)

#### Expanded Format Algorithm

**Algorithm**:
```rust
impl ExpandedFormatter {
  pub fn format(&self, tree: &TreeNode<String>) -> String {
    // 1. Extract headers via TableShapedView trait
    // 2. Calculate max key width (longest header name)
    // 3. For each row node (index i):
    //    - Output record separator: "-[ RECORD {i} ]"
    //    - For each cell child:
    //      - Pad cell name to max key width
    //      - Output: "{name} | {data}"
    // 4. Return concatenated string
  }
}
```

**Key Alignment**: All keys left-padded to same width for vertical alignment

#### Tree Format Algorithm

**Recursive DFS with method-level generics**:
```rust
fn format_node<T, F>(
  &self,
  node: &TreeNode<T>,
  output: &mut String,
  prefix: &str,
  is_last: bool,
  depth: usize,
  render: &F
)
where F: Fn(&T) -> String
```

**Prefix Accumulation**:
- Last child: `└── ``    ` (space for next level)
- Middle child: `├── ``` (vertical for next level)

### Aggregation Algorithm

**Two-Pass**:
1. Calculate subtree totals (bottom-up)
2. Render with percentages (top-down)

**Percentage Calculation**:
```rust
percentage = (subtree_total / grand_total) * 100.0
```

### ANSI Handling

**Visual Length Calculation**:
```rust
pub fn visual_len(text: &str) -> usize {
  // Count chars, skip ANSI sequences (\x1b[...m)
  let mut len = 0;
  let mut in_escape = false;

  for ch in text.chars() {
    if ch == '\x1b' { in_escape = true; }
    else if in_escape && ch == 'm' { in_escape = false; }
    else if !in_escape { len += 1; }
  }
  len
}
```

**Padding with ANSI**:
- Calculate visible length (excluding ANSI)
- Add padding to reach target width
- Preserve ANSI codes in output

## Performance Characteristics

**Time Complexity**:
- Tree construction: O(n × d) where n = nodes, d = depth
- Tree rendering: O(n) single traversal
- Table rendering: O(r × c) where r = rows, c = columns
- Aggregation: O(n) two passes
- Flattening: O(n) DFS traversal

**Space Complexity**:
- Tree: O(n) for node storage
- Rendering: O(d) recursion depth
- Table: O(r × c) for output buffer

**Memory Usage**:
- Minimal allocations
- String concatenation only
- No temporary collections

## Non-Functional Requirements

**Performance**:
- Render 1,000 node tree < 1ms
- Render 100 row table < 1ms
- Zero heap allocations in hot path

**Portability**:
- Zero dependencies
- Pure Rust standard library
- Platform-independent
- `no_std` compatible (with alloc)

**Safety**:
- No unsafe code
- No unwrap in production paths
- No panic paths
- Generic over `T` (minimal trait bounds)

**Architecture**:
- Modular design (16 source files)
- Clear separation of concerns
- Trait-based polymorphism (TableShapedFormatter, Format)
- Builder pattern throughout
- Feature-gated compilation for zero-cost abstractions

## Unicode Box-Drawing Characters

### Tree Symbols
```
├──  U+251C BOX DRAWINGS LIGHT VERTICAL AND RIGHT
│    U+2502 BOX DRAWINGS LIGHT VERTICAL
└──  U+2514 BOX DRAWINGS LIGHT UP AND RIGHT
```

### Table Borders
```
┌─┬─┐  Top border
├─┼─┤  Middle separator
└─┴─┘  Bottom border
│      Vertical separator
```

## Testing Strategy

**Unit Tests** (85 total across 8 test files):

*tests/builder.rs (15 tests)*
- TreeBuilder construction and manipulation
- Path insertion (single, multiple, nested)
- Edge cases (duplicates, empty components, unicode)
- Batch creation (from_items, from_pathbufs)
- Structure tests (deep, wide, insertion order)

*tests/data.rs (14 tests)*
- TreeNode creation and manipulation
- RowBuilder construction and validation
- TableShapedView trait implementation
- Edge cases (empty, single node, large trees)

*tests/column_data.rs (18 tests) - NEW v0.2.0*
- ColumnData construction (new, from_pairs)
- Display trait implementation
- Clone behavior and independence
- Edge cases (empty, unicode, long strings, special chars)

*tests/aligned_tree.rs (15 tests) - NEW v0.2.0*
- Basic aligned formatting (single/multiple nodes)
- Multi-level trees (2-5 depth levels)
- Wide trees (10+ siblings)
- Mixed column counts
- Configuration options (separator, min width)
- Edge cases (empty, unicode, long values)
- Realistic use cases (crate dependency simulation)

*tests/reproduce_alignment_problem.rs (3 tests) - NEW v0.2.0*
- Demonstrates alignment problem and solution
- Programmatic alignment verification
- Side-by-side comparison (aligned vs unaligned)

*tests/fluent_api.rs (8 tests)*
- Fluent RowBuilder API (chainable methods)
- Config builder patterns (Tree, Table, Expanded)
- Integration of builders with formatters

*tests/formatters.rs (8 tests)*
- TableShapedFormatter trait polymorphism
- Generic TableShapedView (integers, floats, custom types)
- Write trait support (stdout, multiple formatters)
- Generic type integration with formatters

*tests/flatten_config.rs (4 tests)*
- FlattenConfig column selection
- Custom column naming
- Path-only flattening
- Integration with TableFormatter

**Doc Tests** (34):
- All public API examples
- Conversion examples
- Common patterns
- Builder patterns
- ColumnData examples (NEW v0.2.0)
- AlignedTreeFormatter examples (NEW v0.2.0)

**Coverage**: 100% of public API

**Total Test Count**: 119 tests (85 unit + 34 doc)

**Test Organization**:
- All integration tests are gated behind the `integration` feature
- Feature is enabled by default in `[features]` section
- Each test file includes `#![ cfg( feature = "integration" ) ]` attribute
- Allows selective test execution and faster builds when needed

## Cargo Features

**Available Features** (NEW in v0.4.0):

**Individual Formatters**:
- `format_table` - TableFormatter (no dependencies)
- `format_expanded` - ExpandedFormatter (no dependencies)
- `format_tree` - TreeFormatter (no dependencies)
- `format_text` - TextFormatter with 6 styles (no dependencies)
- `format_json` - JsonFormatter (requires: serde, serde_json)
- `format_yaml` - YamlFormatter (requires: serde, serde_yaml)
- `format_toml` - TomlFormatter (requires: serde, toml)

**Feature Bundles**:
- `visual_formats` = `format_table` + `format_expanded` + `format_tree` (default)
- `data_formats` = `format_json` + `format_yaml` + `format_toml`
- `all_formats` = `visual_formats` + `data_formats` + `format_text`

**Other Features**:
- `serde_support` - Enables serde derives on data structures (required for data formatters)
- `integration` (default) - Enables all integration tests in `tests/` directory

**Feature Configuration**:
```toml
[features]
default = [ "integration", "visual_formats" ]
integration = []
serde_support = [ "dep:serde" ]
format_table = []
format_expanded = []
format_tree = []
format_text = []
format_json = [ "serde_support", "dep:serde_json" ]
format_yaml = [ "serde_support", "dep:serde_yaml" ]
format_toml = [ "serde_support", "dep:toml" ]
visual_formats = [ "format_table", "format_expanded", "format_tree" ]
data_formats = [ "format_json", "format_yaml", "format_toml" ]
all_formats = [ "visual_formats", "data_formats", "format_text" ]
```

**Usage Examples**:
```toml
# Default: visual formatters only (table, expanded, tree)
tree_fmt = "0.4.0"

# Add JSON support
tree_fmt = { version = "0.4.0", features = [ "format_json" ] }

# All formatters
tree_fmt = { version = "0.4.0", features = [ "all_formats" ] }

# Minimal: only table formatter
tree_fmt = { version = "0.4.0", default-features = false, features = [ "format_table" ] }
```

## Dependencies

**Runtime**:
- **Core** (with default features): Zero dependencies (pure stdlib)
- **With `format_json`**: serde, serde_json
- **With `format_yaml`**: serde, serde_yaml
- **With `format_toml`**: serde, toml

**Dev**: serde, serde_json, serde_yaml, toml (for testing)

**Portability**:
- Visual formatters: Maximum (zero dependencies)
- Data formatters: Requires serde ecosystem

## Example Usage

### Fluent RowBuilder API

```rust
use tree_fmt::{ RowBuilder, TableFormatter };

// Fluent chainable API
let tree = RowBuilder::new(vec![ "Name".into(), "Age".into() ])
  .add_row(vec![ "Alice".into(), "30".into() ])
  .add_row(vec![ "Bob".into(), "25".into() ])
  .build();

let formatter = TableFormatter::new();
println!("{}", formatter.format(&tree));
```

```text
 Name  | Age
-------+-----
 Alice |  30
 Bob   |  25
```

### Polymorphic Formatting with Trait Objects

```rust
use tree_fmt::{ RowBuilder, formatters::TableShapedFormatter, TableFormatter, ExpandedFormatter };

let tree = RowBuilder::new(vec![ "Col".into() ])
  .add_row(vec![ "Data".into() ])
  .build();

// Use trait object for polymorphism
let formatters: Vec<Box<dyn TableShapedFormatter>> = vec![
  Box::new(TableFormatter::new()),
  Box::new(ExpandedFormatter::new()),
];

for formatter in formatters {
  let output = formatter.format(&tree);
  println!("{}", output);
}
```

### Generic TableShapedView (Works with any T: Display)

```rust
use tree_fmt::{ TreeNode, TableShapedView };

// Create tree with numeric data
let mut root = TreeNode::new("root".into(), None::<u64>);

let mut row1 = TreeNode::new("row1".into(), None);
row1.children.push(TreeNode::new("A".into(), Some(100u64)));
row1.children.push(TreeNode::new("B".into(), Some(200u64)));

root.children.push(row1);

// Extract as string rows (converts via Display)
let rows = root.to_rows();
assert_eq!(rows[0], vec!["100", "200"]);
```

### Column-Aligned Tree Formatting (NEW in v0.2.0)

`TreeFormatter` supports column-aligned formatting via the `format_aligned()` method, which displays hierarchical trees with multiple attributes per node where all columns align vertically across all tree levels. This solves the problem of ragged, hard-to-scan output when displaying structured data like dependency trees.

**Problem**: Without alignment, columns are ragged:
```text
├── api_ollama  api_ollama v0.1.0 (api/ollama)
├── as_curl  as_curl v0.1.0 (module/as_curl)
│   ├── dep1  dep1 v2.0.0 (path/to/dep1)
```

**Solution**: With `TreeFormatter::format_aligned()`, columns align vertically:
```text
├── api_ollama  v0.1.0  (api/ollama)
├── as_curl     v0.1.0  (module/as_curl)
│   ├── dep1  v2.0.0  (path/to/dep1)
```

**Code Example**:

```rust
use tree_fmt::{ TreeNode, ColumnData, TreeFormatter };

let mut root = TreeNode::new("workspace".to_string(), None);

// Add nodes with multi-column data
root.children.push(TreeNode::new(
  "api_ollama".to_string(),
  Some(ColumnData::new(vec![
    "api_ollama".to_string(),
    "v0.1.0".to_string(),
    "(api/ollama)".to_string()
  ]))
));

root.children.push(TreeNode::new(
  "as_curl".to_string(),
  Some(ColumnData::new(vec![
    "as_curl".to_string(),
    "v0.1.0".to_string(),
    "(module/as_curl)".to_string()
  ]))
));

// Format with aligned columns
let formatter = TreeFormatter::new();
let output = formatter.format_aligned(&root);
println!("{}", output);
```

**Output**:
```text
├── api_ollama  v0.1.0  (api/ollama)
└── as_curl     v0.1.0  (module/as_curl)
```

**Key Features**:
- Automatic column width calculation across entire tree
- Works with any number of columns
- Preserves tree structure (├──, │, └──)
- Configurable column separator (default: 2 spaces)
- Supports unicode and ANSI colors
- Two-pass algorithm: calculates widths, then formats

**Formatter Parameters**:
```rust
use tree_fmt::{ TreeFormatter, TreeConfig };

let config = TreeConfig::new()
  .column_separator(" | ".to_string())  // Pipe-separated columns
  .min_column_width(10);                // Minimum width per column

let formatter = TreeFormatter::with_config(config);
let output = formatter.format_aligned(&tree);
```

**Use Cases**:
- Package dependency trees (name, version, path)
- File trees (name, size, permissions, date)
- Process trees (name, PID, CPU%, memory)
- Any hierarchical data with multiple aligned attributes

### Expanded Format Styles (NEW in v0.2.3)

The `ExpandedFormatter` supports two distinct styles through the `PaddingSide` enum.

#### PaddingSide Enum

```rust
/// Where to place alignment padding in key-value pairs
pub enum PaddingSide
{
  /// Pad keys before separator: "Name   | Value"
  BeforeSeparator,

  /// Pad values after separator: "Name: Value"
  AfterSeparator,
}
```

#### PostgreSQL Style (Default)

**Usage**:
```rust
use tree_fmt::{ RowBuilder, ExpandedFormatter, ExpandedConfig };

let tree = RowBuilder::new(vec![ "Name".into(), "Status".into() ])
  .add_row(vec![ "server1".into(), "online".into() ])
  .build();

let formatter = ExpandedFormatter::new();
// or
let formatter = ExpandedFormatter::with_config( ExpandedConfig::postgres_style() );
let output = formatter.format(&tree);
```

**Output**:
```text
-[ RECORD 1 ]
Name   | server1
Status | online
```

**Features**:
- Record separator headers: `-[ RECORD N ]`
- Pipe separator: ` | `
- Keys padded before separator
- Values start immediately after separator

#### Property List Style

**Usage**:
```rust
use tree_fmt::{ RowBuilder, ExpandedFormatter, ExpandedConfig };

let tree = RowBuilder::new(vec![ "Command".into(), "Status".into(), "Duration".into() ])
  .add_row(vec![ "sleep 10".into(), "Completed".into(), "10 seconds".into() ])
  .build();

let formatter = ExpandedFormatter::with_config( ExpandedConfig::property_style() );
let output = formatter.format(&tree);
```

**Output**:
```text
Command:  sleep 10
Status:   Completed
Duration: 10 seconds
```

**Features**:
- No record separator headers (blank lines between records)
- Colon separator: `: `
- Separators follow keys immediately
- Values padded after separator for alignment

#### Colored Keys

Both styles support optional ANSI coloring for keys:

**PostgreSQL style with gray keys**:
```rust
let formatter = ExpandedFormatter::with_config(
  ExpandedConfig::postgres_style()
    .colorize_keys(true)
);
```

**Property style with gray keys**:
```rust
let formatter = ExpandedFormatter::with_config(
  ExpandedConfig::property_style()
    .colorize_keys(true)
);
```

**Output** (property style with colors):
```text
Command:  sleep 10      # "Command:" in gray
Status:   Completed     # "Status:" in gray
Duration: 10 seconds    # "Duration:" in gray
```

**Custom colors**:
```rust
let formatter = ExpandedFormatter::with_config(
  ExpandedConfig::property_style()
    .colorize_keys(true)
    .key_color("\x1b[36m".to_string())  // Cyan
);
```

**Common ANSI Colors**:
- Gray: `\x1b[90m` (default)
- Blue: `\x1b[34m`
- Cyan: `\x1b[36m`
- Yellow: `\x1b[33m`

#### Custom Styles

Mix and match configuration options:

```rust
use tree_fmt::{ ExpandedConfig, PaddingSide };

let formatter = ExpandedFormatter::with_config(
  ExpandedConfig::new()
    .record_separator("=== Entry {} ===".to_string())
    .key_value_separator(" = ".to_string())
    .padding_side(PaddingSide::AfterSeparator)
    .colorize_keys(true)
);
```

**Output**:
```text
=== Entry 1 ===
Name     = Alice
Location = New York
```

### Write Trait Support (Zero-Allocation Output)

```rust
use tree_fmt::{ RowBuilder, TableFormatter };
use std::io::Cursor;

let tree = RowBuilder::new(vec![ "Col".into() ])
  .add_row(vec![ "Data".into() ])
  .build();

let formatter = TableFormatter::new();
let mut buffer = Cursor::new(Vec::new());

// Write directly to io::Write without intermediate String
formatter.write_to(&tree, &mut buffer).unwrap();

let output = String::from_utf8(buffer.into_inner()).unwrap();
assert!(output.contains("Data"));
```

### Config Builder Pattern

```rust
use tree_fmt::{ TreeConfig, TreeFormatter, TreeBuilder };

let config = TreeConfig::new()
  .show_branches(false)
  .show_root(true)
  .indent_size(2)
  .max_depth(Some(3));

let tree = TreeBuilder::new("root")
  .insert(&["dir", "file.txt"], 100)
  .build();

let formatter = TreeFormatter::with_config(config);
let output = formatter.format(&tree, |n| format!("{}", n));
```

### Customizable Tree Flattening

```rust
use tree_fmt::{ TreeBuilder, conversions::{ flatten_to_table_tree_with_config, FlattenConfig }, TableFormatter };

let tree = TreeBuilder::new("project")
  .insert(&["src", "main.rs"], 150)
  .insert(&["src", "lib.rs"], 200)
  .build();

// Only include name and data columns with custom names
let config = FlattenConfig::new()
  .include_path(false)
  .include_depth(false)
  .column_names("ignored".into(), "File".into(), "ignored2".into(), "Lines".into());

let flattened = flatten_to_table_tree_with_config(&tree, &config);
let formatter = TableFormatter::new();
let output = formatter.format(&flattened);

// Output contains only "File" and "Lines" columns
assert!(output.contains("File"));
assert!(output.contains("Lines"));
assert!(!output.contains("project/src")); // path excluded
```

### Hierarchical Data Example

```rust
use tree_fmt::{ TreeBuilder, TreeFormatter, TableFormatter, ExpandedFormatter };

// Create tree data
let tree = TreeBuilder::new("project")
  .insert(&["src", "main.rs"], 1024u64)
  .insert(&["src", "lib.rs"], 2048u64)
  .insert(&["Cargo.toml"], 256u64)
  .build();
```

#### Tree Format Output

```rust
let tree_fmt = TreeFormatter::new();
let output = tree_fmt.format(&tree, |bytes| format!("{} bytes", bytes));
println!("{}", output);
```

```text
project
├── src
│   ├── main.rs (1024 bytes)
│   └── lib.rs (2048 bytes)
└── Cargo.toml (256 bytes)
```

#### Table Format Output (Flattened)

```rust
let table_fmt = TableFormatter::new();
println!("{}", table_fmt.format_tree(&tree));
```

```text
 path                 | name       | depth | data
----------------------+------------+-------+------
 project              | project    | 0     |
 project/src          | src        | 1     |
 project/src/main.rs  | main.rs    | 2     | 1024
 project/src/lib.rs   | lib.rs     | 2     | 2048
 project/Cargo.toml   | Cargo.toml | 1     | 256
```

#### Expanded Format Output (Flattened)

```rust
let expanded_fmt = ExpandedFormatter::new();
println!("{}", expanded_fmt.format_tree(&tree));
```

```text
-[ RECORD 1 ]
path  | project
name  | project
depth | 0
data  |
-[ RECORD 2 ]
path  | project/src
name  | src
depth | 1
data  |
-[ RECORD 3 ]
path  | project/src/main.rs
name  | main.rs
depth | 2
data  | 1024
```

## Versioning

**Current**: v0.4.0 (unified format interface with granular feature flags)

**Semantic Versioning**:
- MAJOR: Breaking API changes
- MINOR: New features (formats, conversions)
- PATCH: Bug fixes, optimizations

## Changes in v0.2.0

**Architecture Refactoring**:
1. **Modular structure** - Split monolithic implementation into 11 focused modules
2. **Removed DataTable** - Replaced with RowBuilder + TableShapedView trait
3. **Removed PhantomData** - TreeFormatter now uses method-level generics
4. **Added TableShapedFormatter trait** - Polymorphic formatter interface
5. **Generic TableShapedView** - Works with TreeNode<T: Display>
6. **Fluent RowBuilder API** - Chainable builder methods
7. **Write trait support** - All formatters support write_to()
8. **Config builder pattern** - All configs have fluent APIs
9. **FlattenConfig** - Customizable tree-to-table conversion

**New Features**:
1. `RowBuilder` - Fluent builder for table-shaped trees
2. `TableShapedView` trait - Generic trait for table operations
3. `TableShapedFormatter` trait - Polymorphic formatter interface
4. `FlattenConfig` - Customizable flattening configuration
5. `flatten_to_table_tree_with_config()` - Custom column selection
6. `write_to()` methods - Zero-allocation io::Write output
7. Config builder methods - Fluent APIs for all configs
8. Generic TableShapedView - Works with any T: Display

**Breaking Changes from Legacy**:
- DataTable removed (use RowBuilder)
- format_with_row_names() removed (row naming handled by builder)
- TreeFormatter no longer generic over struct (method-level generics)
- All configs now have builder pattern

**Migration Guide**:
```rust
// Legacy (pre-refactor)
let mut data = DataTable::new(headers);
data.add_row(row);

// v0.2.0 (current)
let tree = RowBuilder::new(headers)
  .add_row(row)
  .build();
```

## Version History

**v0.1.0** (Linter improvements):
- Added ANSI-aware helper functions
- `visual_len()` - Calculate visible length
- `pad_to_width()` - Pad with ANSI support
- Enhanced table alignment with colors

**v0.2.0** (Modular refactored architecture):
- Modular file structure (11 source files)
- RowBuilder replaces DataTable
- TableShapedView trait for generic table operations
- TableShapedFormatter trait for polymorphism
- Fluent builder APIs throughout
- Write trait support for zero-allocation output
- FlattenConfig for customizable conversions
- Method-level generics in TreeFormatter
- 50 comprehensive tests across 3 test files

**v0.2.1** (Quality improvements):
- Fixed documentation accuracy in tests/readme.md to reflect actual test files
- Fixed documentation accuracy in examples/readme.md to reflect actual examples
- Removed dead code (unused traverse_and_flatten wrapper function)
- Code style improvements: all function signatures now comply with 110-char line limit
- All tests pass (50 unit tests + 30 doc tests)
- Zero clippy warnings

**v0.2.2** (Colored keys feature):
- Added ANSI color support for keys in ExpandedFormatter
- New `colorize_keys` config option (default: false for backward compatibility)
- New `key_color` config option (default: gray `\x1b[90m`)
- Builder methods: `colorize_keys()` and `key_color()`
- 4 new tests for color functionality
- Updated examples and documentation
- All tests pass (94 unit tests + 35 doc tests)
- Zero clippy warnings

**v0.2.3** (Property list style and padding parametrization):
- Added `PaddingSide` enum: `BeforeSeparator` (default) and `AfterSeparator`
- Parametrized record separator (empty string disables headers)
- New `ExpandedConfig::postgres_style()` convenience constructor
- New `ExpandedConfig::property_style()` convenience constructor (gray keys enabled by default)
- Builder method: `padding_side()`
- Updated `record_separator` to support format string with `{}` placeholder
- 10 new tests for property style and padding variations (including color defaults)
- Zero breaking changes (full backward compatibility)
- All tests pass (104 unit tests + 36 doc tests)
- Zero clippy warnings

**v0.3.0** (Table styles refactoring - comprehensive parametrization):
- Added `BorderVariant` enum: `None`, `Ascii`, `AsciiGrid`, `Unicode`, `Markdown`
- Added `HeaderSeparatorVariant` enum: `None`, `Dash`, `AsciiGrid`, `Unicode`, `Markdown`
- Added `ColumnSeparator` enum: `Spaces(usize)`, `Character(char)`, `String(String)`
- Comprehensive `TableConfig` refactoring with 11 new formatter parameters:
  - `border_variant`: Border rendering variant (replaces `show_borders`)
  - `header_separator_variant`: Header separator line variant
  - `column_separator`: Column separator configuration
  - `outer_padding`: Padding at table edges
  - `inner_padding`: Padding within cells
  - `colorize_header`: Enable header coloring
  - `header_color`: ANSI color for headers
  - `alternating_rows`: Enable alternating row colors
  - `row_color1`, `row_color2`: Colors for alternating rows
  - `min_column_width`: Minimum width per column
  - `max_column_width`: Maximum width with truncation
  - `truncation_marker`: String for truncated content ("...")
- 9 variant preset constructors for common table formats:
  - `TableConfig::plain()` - Space-separated with dash separator (CLI tools)
  - `TableConfig::minimal()` - Space-separated, no separator (maximum simplicity)
  - `TableConfig::bordered()` - Traditional pipe borders (default)
  - `TableConfig::markdown()` - GitHub-flavored Markdown tables
  - `TableConfig::grid()` - Full ASCII grid with intersections
  - `TableConfig::unicode_box()` - Unicode box-drawing characters
  - `TableConfig::csv()` - Comma-separated values
  - `TableConfig::tsv()` - Tab-separated values
  - `TableConfig::compact()` - Minimal spacing for density
- 13 new builder methods for fine-grained control
- Deprecated `show_borders()` (use `border_variant()` instead)
- Full backward compatibility (default behavior unchanged)
- 30+ new tests for all table variants and formatter parameters
- Zero breaking changes for existing code
- All tests pass (134+ unit tests + 40+ doc tests)
- Zero clippy warnings
- 2 new examples: `table_styles.rs`, `process_monitor.rs`

**v0.4.0** (Unified format interface with granular feature flags):
- Added `Format` trait - Unified interface for all formatters
- Added `TableView` struct - Canonical data format for format-agnostic code
- Added `FormatError` enum - Consistent error handling across formatters
- Added `JsonFormatter` - JSON output with pretty/compact modes (NEW)
- Added `YamlFormatter` - YAML output (NEW)
- Added `TomlFormatter` - TOML output (NEW)
- Added `TextFormatter` - Plain text output with 6 styles: bullets, numbered, sections, key-value, compact, cli-help (NEW)
- Added `RowBuilder::build_view()` - Returns TableView instead of TreeNode
- Added `TableView::to_tree_node()` - Backward compatibility converter
- Implemented `Format` trait for all formatters (Table, Expanded, Tree, JSON, YAML, TOML, Text)
- Merged `AlignedTreeFormatter` into `TreeFormatter` as `format_aligned()` method
- Added `column_separator` and `min_column_width` fields to `TreeConfig`
- Granular cargo features for zero-cost abstractions:
  - Individual formatter features: `format_table`, `format_expanded`, `format_tree`, `format_text`, `format_json`, `format_yaml`, `format_toml`
  - Feature bundles: `visual_formats` (default), `data_formats`, `all_formats`
  - Conditional serde support: `serde_support` feature
- Updated architecture to 16 source files (added 4 new formatters, merged aligned_tree.rs into tree.rs)
- Zero runtime dependencies for visual formatters
- Optional dependencies: serde, serde_json, serde_yaml, toml (only when features enabled)
- 21 new integration tests for unified format interface (`tests/unified_format_trait.rs`)
- Total: 175 tree_fmt tests + 18 will_crates tests + 43 doc tests = 236 tests
- Real-world integration: Updated will_crates to use unified format interface
- Full backward compatibility: Existing API unchanged, new `build_view()` method added alongside `build()`
- Created comprehensive 450+ line guide: `UNIFIED_FORMAT_GUIDE.md`
- Created example demonstrating unified interface: `examples/unified_formats.rs`
- Zero breaking changes for existing code
- All tests pass with -D warnings
- Zero clippy warnings

**v0.5.0** (Column truncation and multiline cells - advanced table formatting):
- **Column Truncation Feature**: Full implementation of `max_column_width` truncation
  - ANSI-aware truncation using `strs_tools::ansi::truncate()`
  - Preserves color codes in truncated output
  - Configurable `truncation_marker` (default: "...")
  - Applied during cell rendering with visual length calculation
  - Disabled by default for backward compatibility
  - Works with all table styles (plain, bordered, markdown, etc.)
  - Comprehensive test suite: 15+ tests covering basic, edge cases, ANSI, all styles
- **Multiline Cells Feature**: Automatic support for `\n` in cell content
  - Two-pass rendering algorithm: split → calculate height → render lines
  - Row height = max line count across cells in that row
  - Per-line column alignment with proper padding
  - ANSI-aware line rendering for colored multiline content
  - Border and separator support for each line
  - Backward compatible (single-line cells unchanged)
  - CSV/TSV formats: multiline disabled (literal `\n` preserved)
  - Comprehensive test suite: 20+ tests covering basic, mixed heights, ANSI, borders
- **Feature Interaction**: Truncation + multiline combined behavior
  - Per-line truncation after line splitting (preferred implementation)
  - Each line of multiline cell individually truncated
  - Maintains alignment and visual consistency
  - 5+ tests for combined scenarios
- **Helper Functions** (NEW in `src/helpers.rs`):
  - `truncate_cell()`: ANSI-aware cell truncation with marker
  - `detect_multiline()`: Check if any cell contains newlines
  - `split_into_lines()`: Split cells preserving empty lines
  - `calculate_row_heights()`: Compute line counts per row
- **Specification Updates**:
  - Added "Column Truncation" algorithm section with pseudocode
  - Added "Multiline Cells" algorithm section with two-pass description
  - Added "Feature Interaction" section for combined behavior
  - Added "Feature Flags and Backward Compatibility" section
- **TDD Workflow**: Strict RED → GREEN → REFACTOR discipline
  - Phase 1: Truncation (tests → implementation → refactor)
  - Phase 2: Multiline (tests → implementation → refactor)
  - All tests written before implementation (TDD-first)
- **Quality Assurance**:
  - 40+ new tests total (truncation + multiline + interaction)
  - All tests pass with RUSTFLAGS="-D warnings"
  - Zero clippy warnings (--all-targets --all-features)
  - Full rustdoc validation (--all-features)
  - Pattern migration tracking (old → new patterns verified)
  - Rulebook compliance verified (2-space indent, no cargo fmt, etc.)
- **Documentation**:
  - Updated `spec.md` with detailed algorithms and examples
  - Added doc comments for all new helper functions
  - Updated module-level documentation in `src/formatters/table.rs`
  - Added examples in doc comments for truncation and multiline features
- **Zero Breaking Changes**:
  - All existing tests pass unchanged
  - Default behavior identical (truncation disabled, multiline auto-enabled)
  - API fully backward compatible
  - No deprecations introduced