croft-software 0.2.232

VSCode-style TUI written in Rust
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
use std::path::Path;

/// An xlsx grid's edited cell as hot exit keeps it (#1593):
/// `(sheet name, row, col, value)`. The worksheet goes by its name, which
/// a workbook keeps unique, so a reorder since the backup does not put the
/// value on another worksheet.
pub type SheetCellEdit = (String, usize, usize, String);

pub(crate) const CSV_BYTES_CAP: u64 = 25 * 1024 * 1024;

/// A sheet refused at a deliberate size cap (the file's bytes, or the cells
/// its grid would hold), not one that failed to parse: the open reports it
/// instead of falling through to the text editor, which would get around the
/// cap. It travels inside the `io::Error`, so callers tell the two apart by
/// type ([`is_size_refusal`]).
#[derive(Debug)]
pub struct PastSheetCap(String);

impl std::fmt::Display for PastSheetCap {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.0)
    }
}

impl std::error::Error for PastSheetCap {}

/// A [`PastSheetCap`] refusal saying `message`.
fn past_sheet_cap(message: String) -> std::io::Error {
    std::io::Error::other(PastSheetCap(message))
}

/// Whether a sheet open was refused for its size rather than failing to
/// parse: one of this module's caps ([`PastSheetCap`]). An error from the
/// workbook readers that only says "too large", such as the zip reader's
/// "Archive header is too large" for a damaged archive, is a parse failure,
/// and the file falls through to the hex viewer like any other unreadable
/// workbook (#2709).
pub fn is_size_refusal(e: &std::io::Error) -> bool {
    e.get_ref().is_some_and(|inner| inner.is::<PastSheetCap>())
}
const XLSX_BYTES_CAP: u64 = 50 * 1024 * 1024;
/// The most cells one sheet's grid is built from, counting the dense
/// rectangle between its outermost values. The compressed-size cap above
/// doesn't bound this: repeat attributes, or two values at opposite
/// corners, expand a few hundred bytes to gigabytes (#1156).
const MAX_SHEET_CELLS: u64 = 10_000_000;
const MAX_COL_DISPLAY_W: u16 = 40;
const MIN_COL_DISPLAY_W: u16 = 3;

/// Source format the spreadsheet view was loaded from. Drives the small
/// header-line label and the parser dispatch.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SheetKind {
    Csv,
    Tsv,
    Xlsx,
    Xls,
    Ods,
    Xlsb,
    /// Read-only SQLite browser (#182): tables page as worksheets.
    Sqlite,
}

impl SheetKind {
    pub fn label(self) -> &'static str {
        match self {
            SheetKind::Csv => "CSV",
            SheetKind::Tsv => "TSV",
            SheetKind::Xlsx => "XLSX",
            SheetKind::Xls => "XLS",
            SheetKind::Ods => "ODS",
            SheetKind::Xlsb => "XLSB",
            SheetKind::Sqlite => "SQLITE",
        }
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SheetView {
    pub kind: SheetKind,
    /// Raw file size on disk, for the header line.
    pub source_byte_size: u64,
    /// One entry per worksheet (single entry for CSV/TSV).
    pub sheets: Vec<SheetData>,
    pub current_sheet: usize,
    /// Unsaved cell/row/column changes (#177). Mirrored into the
    /// editor's dirty flag so tab dots, close guards, and the FS-sync
    /// conflict contract all behave exactly like text tabs.
    pub dirty: bool,
    /// The in-grid cell editor when a cell is being typed into.
    pub editing: Option<CellEdit>,
    /// Cells the user edited since the last save (#178): (sheet, body
    /// row, col). The xlsx save path applies EXACTLY these through umya,
    /// so untouched cells (formulas included) are never rewritten from
    /// calamine's formatted strings. CSV saves ignore it (whole-file
    /// serialisation).
    pub cell_edits: Vec<(usize, usize, usize)>,
    /// Frame-truth layout for mouse hit-testing, written by the render.
    pub grid: SheetGridLayout,
    /// SQLite paging state (#182/#201): per-sheet (table name, page).
    /// Empty for every other kind.
    pub sqlite_pages: Vec<(String, usize)>,
}

impl SheetView {
    /// Commit the cell being typed into at the current sheet's caret: the
    /// value goes in the cell, the cell joins `cell_edits` and the view turns
    /// dirty. Every commit (Enter, Tab, a click elsewhere, a save) goes
    /// through here, so none can skip the record the xlsx save writes from
    /// (#1140, #1141). Returns the committed cell, or None with no edit open.
    pub fn commit_edit(&mut self) -> Option<(usize, usize)> {
        let current = self.current_sheet;
        let data = self.sheets.get_mut(current)?;
        let edit = self.editing.take()?;
        let (r, c) = (data.cur_row, data.cur_col);
        data.set_cell(r, c, edit.value);
        if !self.cell_edits.contains(&(current, r, c)) {
            self.cell_edits.push((current, r, c));
        }
        self.dirty = true;
        Some((r, c))
    }

    /// Whether the grid takes edits: CSV, TSV and xlsx.
    pub fn editable(&self) -> bool {
        matches!(self.kind, SheetKind::Csv | SheetKind::Tsv | SheetKind::Xlsx)
    }
}

/// In-grid cell input state (#177): plain value + char cursor.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CellEdit {
    pub value: String,
    pub cursor: usize,
}

/// Geometry of the last painted grid frame (mouse hit-testing).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct SheetGridLayout {
    pub data_top: u16,
    pub data_rows: u16,
    pub body_x: u16,
    pub body_w: u16,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SheetData {
    pub name: String,
    pub headers: Vec<String>,
    pub rows: Vec<Vec<String>>,
    /// Pre-computed display widths in cells (clamped to
    /// `[MIN_COL_DISPLAY_W..=MAX_COL_DISPLAY_W]`). Stored so render can lay
    /// out columns without re-walking every row each frame.
    pub col_widths: Vec<u16>,
    pub scroll_row: usize,
    pub scroll_col: usize,
    /// Selected cell (#177): body-row and column indices. Arrow keys
    /// move it; the viewport follows.
    pub cur_row: usize,
    pub cur_col: usize,
    /// Absolute 0-based (row, col) of the used range's first cell in the
    /// SOURCE sheet (#178): calamine's grid starts at the used range, not
    /// A1, so writing an edit back needs this offset. (0, 0) for CSV.
    pub origin: (u32, u32),
    /// Rows of the source above this batch (#1222): a SQLite page holds
    /// rows `row_base + 1 ..` of its table, and is numbered so. 0 elsewhere.
    pub row_base: usize,
    /// Bumped by every edit of the data (#1593), so hot exit, which backs
    /// up only what changed since its last write, sees a grid change
    /// without comparing the cells.
    pub revision: u64,
    /// `(row, col)` of the cells holding SQL NULL (#1002), drawn as a
    /// dimmed `NULL` rather than as the empty string they store. Only a
    /// SQLite page has any, and its rows never move: sorting and row edits
    /// are CSV/TSV only.
    pub null_cells: std::collections::HashSet<(usize, usize)>,
}

impl SheetData {
    pub fn col_count(&self) -> usize {
        self.col_widths.len()
    }
    pub fn row_count(&self) -> usize {
        self.rows.len()
    }
}

/// Assemble a SheetData from parts (the SQLite browser's tables).
pub fn sheet_data_from_parts(
    name: String,
    headers: Vec<String>,
    rows: Vec<Vec<String>>,
) -> SheetData {
    let col_widths = compute_col_widths((!headers.is_empty()).then_some(&headers), &rows);
    SheetData {
        name,
        headers,
        rows,
        col_widths,
        scroll_row: 0,
        scroll_col: 0,
        cur_row: 0,
        cur_col: 0,
        origin: (0, 0),
        row_base: 0,
        revision: 0,
        null_cells: Default::default(),
    }
}

/// Assemble a view over pre-built sheets (the SQLite browser).
pub fn view_from_sheets(
    kind: SheetKind,
    source_byte_size: u64,
    sheets: Vec<SheetData>,
) -> SheetView {
    SheetView {
        kind,
        source_byte_size,
        sheets,
        current_sheet: 0,
        dirty: false,
        editing: None,
        cell_edits: Vec::new(),
        grid: SheetGridLayout::default(),
        sqlite_pages: Vec::new(),
    }
}

pub fn extension_is_sheet(ext: &str) -> bool {
    matches!(
        ext.to_ascii_lowercase().as_str(),
        "csv" | "tsv" | "xlsx" | "xls" | "ods" | "xlsb"
    )
}

pub fn sheet_kind_from_ext(ext: &str) -> Option<SheetKind> {
    Some(match ext.to_ascii_lowercase().as_str() {
        "csv" => SheetKind::Csv,
        "tsv" => SheetKind::Tsv,
        "xlsx" => SheetKind::Xlsx,
        "xls" => SheetKind::Xls,
        "ods" => SheetKind::Ods,
        "xlsb" => SheetKind::Xlsb,
        _ => return None,
    })
}

pub fn open_sheet(path: &Path) -> std::io::Result<SheetView> {
    let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("");
    let kind = sheet_kind_from_ext(ext)
        .ok_or_else(|| std::io::Error::other("unsupported sheet extension"))?;
    open_sheet_with_kind(path, kind)
}

/// Open with an explicit kind, bypassing the extension: the content
/// router (#174) lands extensionless / misnamed workbooks here.
pub fn open_sheet_with_kind(path: &Path, kind: SheetKind) -> std::io::Result<SheetView> {
    let meta = std::fs::metadata(path)?;
    match kind {
        SheetKind::Csv | SheetKind::Tsv => {
            if meta.len() > CSV_BYTES_CAP {
                return Err(past_sheet_cap(format!(
                    "CSV/TSV too large ({} bytes)",
                    meta.len()
                )));
            }
            let bytes = std::fs::read(path)?;
            let delim = if matches!(kind, SheetKind::Tsv) {
                b'\t'
            } else {
                b','
            };
            let sheet = parse_delimited(&bytes, delim, "Sheet1")
                .map_err(|e| std::io::Error::other(format!("CSV parse: {e}")))?;
            Ok(SheetView {
                kind,
                source_byte_size: meta.len(),
                sheets: vec![sheet],
                current_sheet: 0,
                dirty: false,
                editing: None,
                cell_edits: Vec::new(),
                grid: SheetGridLayout::default(),
                sqlite_pages: Vec::new(),
            })
        }
        SheetKind::Sqlite => Err(std::io::Error::other(
            "SQLite opens through the database browser, not the sheet parser",
        )),
        SheetKind::Xlsx | SheetKind::Xls | SheetKind::Ods | SheetKind::Xlsb => {
            if meta.len() > XLSX_BYTES_CAP {
                return Err(past_sheet_cap(format!(
                    "Spreadsheet too large ({} bytes)",
                    meta.len()
                )));
            }
            // calamine expands an ODS's repeats while opening the workbook,
            // before any sheet is asked for, so its extent is measured from
            // the XML first.
            if kind == SheetKind::Ods {
                for (name, rows, cols) in ods_extents(path)? {
                    check_sheet_extent(&name, rows, cols)?;
                }
            }
            let sheets = read_calamine_workbook(path, kind).map_err(|e| match e {
                WorkbookError::TooLarge(e) => e,
                WorkbookError::Calamine(e) => std::io::Error::other(format!("workbook open: {e}")),
            })?;
            if sheets.is_empty() {
                return Err(std::io::Error::other("workbook has no sheets"));
            }
            Ok(SheetView {
                kind,
                source_byte_size: meta.len(),
                sheets,
                current_sheet: 0,
                dirty: false,
                editing: None,
                cell_edits: Vec::new(),
                grid: SheetGridLayout::default(),
                sqlite_pages: Vec::new(),
            })
        }
    }
}

pub fn parse_delimited(bytes: &[u8], delim: u8, sheet_name: &str) -> Result<SheetData, csv::Error> {
    // TSV has no quoting (#1136): `psql`, `mysql -B` and `cut` write a `"`
    // as a plain character, and reading one as a quote swallowed every row
    // after a cell that started with it.
    let mut reader = csv::ReaderBuilder::new()
        .has_headers(false)
        .flexible(true)
        .delimiter(delim)
        .quoting(delim != b'\t')
        .from_reader(bytes);
    let mut rows: Vec<Vec<String>> = Vec::new();
    // The reader skips blank lines, so a single-column file lost every
    // empty value on the first save. They come back as empty rows. A
    // record's position is where the reader started looking for it, before
    // the blank lines it skipped, so those are the line breaks it opens with.
    for record in reader.records() {
        let r = record?;
        let start = r.position().map_or(0, |p| p.byte() as usize);
        let mut rest = bytes.get(start..).unwrap_or_default();
        // After a CRLF record the reader stops past the `\r`, so the `\n`
        // it starts on still belongs to that record's terminator.
        if start > 0 && bytes[start - 1] == b'\r' {
            rest = rest.strip_prefix(b"\n").unwrap_or(rest);
        }
        let mut blanks = 0usize;
        while let Some(tail) = rest
            .strip_prefix(b"\r\n")
            .or_else(|| rest.strip_prefix(b"\n"))
        {
            rest = tail;
            blanks += 1;
        }
        // Not before the first record, which becomes the header row.
        if !rows.is_empty() {
            rows.extend(std::iter::repeat_n(Vec::new(), blanks));
        }
        rows.push(r.iter().map(|s| s.to_string()).collect());
    }
    let (headers, body) = split_header(rows);
    let col_widths = compute_col_widths(headers.as_ref(), &body);
    Ok(SheetData {
        name: sheet_name.to_string(),
        headers: headers.unwrap_or_default(),
        rows: body,
        col_widths,
        scroll_row: 0,
        scroll_col: 0,
        cur_row: 0,
        cur_col: 0,
        origin: (0, 0),
        row_base: 0,
        revision: 0,
        null_cells: Default::default(),
    })
}

impl SheetData {
    /// Sort the body rows by column `col` (#578, a sortable results
    /// table): ascending, or descending when they already are ascending,
    /// so sorting the same column again reverses it. Cells that read as
    /// numbers compare as numbers and come before the rest, which compare
    /// as text without case. The sort is stable, and the cursor stays on
    /// the row it was on. Returns whether the order is now ascending.
    pub fn sort_by_column(&mut self, col: usize) -> bool {
        self.revision += 1;
        // Numbers sort before text. Comparing a mixed pair as text instead
        // made the order cyclic (2 < 10 < "1a" < 2), and the standard sort
        // panics on a comparator that is not a total order (#1134). Each
        // cell is parsed and lowercased once, not on every comparison.
        enum Key {
            Num(f64),
            Text(String),
        }
        fn cmp(a: &Key, b: &Key) -> std::cmp::Ordering {
            use std::cmp::Ordering::{Greater, Less};
            match (a, b) {
                (Key::Num(x), Key::Num(y)) => x.total_cmp(y),
                (Key::Num(_), Key::Text(_)) => Less,
                (Key::Text(_), Key::Num(_)) => Greater,
                (Key::Text(a), Key::Text(b)) => a.cmp(b),
            }
        }
        let keys: Vec<Key> = self
            .rows
            .iter()
            .map(|r| {
                let cell = r.get(col).map_or("", String::as_str);
                match cell.trim().parse::<f64>() {
                    Ok(x) => Key::Num(x),
                    Err(_) => Key::Text(cell.to_lowercase()),
                }
            })
            .collect();
        let ascending = !keys.windows(2).all(|w| cmp(&w[0], &w[1]).is_le());
        let mut order: Vec<usize> = (0..self.rows.len()).collect();
        order.sort_by(|&i, &j| {
            let o = cmp(&keys[i], &keys[j]);
            if ascending { o } else { o.reverse() }
        });
        let cursor = order.iter().position(|&i| i == self.cur_row);
        let mut old: Vec<Option<Vec<String>>> = std::mem::take(&mut self.rows)
            .into_iter()
            .map(Some)
            .collect();
        self.rows = order.iter().filter_map(|&i| old[i].take()).collect();
        if let Some(c) = cursor {
            self.cur_row = c;
        }
        ascending
    }

    /// Overwrite one body cell (#177), growing a short row (the csv
    /// reader is `flexible`, so ragged rows are real) and refreshing the
    /// column widths so the grid re-lays-out immediately.
    pub fn set_cell(&mut self, row: usize, col: usize, value: String) {
        self.revision += 1;
        let Some(r) = self.rows.get_mut(row) else {
            return;
        };
        if r.len() <= col {
            r.resize(col + 1, String::new());
        }
        r[col] = value;
        self.recompute_widths();
    }

    pub fn cell(&self, row: usize, col: usize) -> &str {
        self.rows
            .get(row)
            .and_then(|r| r.get(col))
            .map(String::as_str)
            .unwrap_or("")
    }

    pub fn insert_row(&mut self, at: usize) {
        self.revision += 1;
        let cols = self.col_count().max(1);
        let at = at.min(self.rows.len());
        self.rows.insert(at, vec![String::new(); cols]);
        self.recompute_widths();
    }

    pub fn delete_row(&mut self, at: usize) -> bool {
        self.revision += 1;
        if at >= self.rows.len() {
            return false;
        }
        self.rows.remove(at);
        self.recompute_widths();
        true
    }

    pub fn insert_col(&mut self, at: usize) {
        self.revision += 1;
        // A fully EMPTY sheet gains its header cell too (#193 review):
        // without one, the first saved body row would be re-read as the
        // header on reopen and vanish from the editable grid.
        if self.headers.is_empty() && self.rows.is_empty() {
            self.headers.push(String::new());
            self.recompute_widths();
            return;
        }
        if !self.headers.is_empty() {
            let hat = at.min(self.headers.len());
            self.headers.insert(hat, String::new());
        }
        for r in &mut self.rows {
            let rat = at.min(r.len());
            r.insert(rat, String::new());
        }
        self.recompute_widths();
    }

    pub fn delete_col(&mut self, at: usize) -> bool {
        self.revision += 1;
        if at >= self.col_count() {
            return false;
        }
        if at < self.headers.len() {
            self.headers.remove(at);
        }
        for r in &mut self.rows {
            if at < r.len() {
                r.remove(at);
            }
        }
        self.recompute_widths();
        true
    }

    fn recompute_widths(&mut self) {
        let headers = (!self.headers.is_empty()).then_some(&self.headers);
        self.col_widths = compute_col_widths(headers, &self.rows);
    }
}

/// Serialize the sheet back to delimited bytes: the header row first
/// (it is the file's own row 0, split off at parse), then the body, with
/// the delimiter the file was READ with. `crlf` keeps a CRLF file CRLF:
/// rewritten with LF, editing one cell made the whole file a diff.
///
/// `original` is the file as it is on disk (empty for a new file). A row
/// whose values match one of its records goes back as that record's own
/// bytes, so an edit changes its own line only, whatever quoting the file
/// was written with (#1375). A changed or new row is quoted the way the
/// file is: every field (R `write.csv`, Python `QUOTE_ALL`), every field
/// but numbers (`QUOTE_NONNUMERIC`), or only where csv needs it.
pub fn serialize_delimited(data: &SheetData, delim: u8, crlf: bool, original: &[u8]) -> Vec<u8> {
    let records = raw_records(original, delim);
    // The file's record terminator, read from its first record rather than
    // its first `\n`, which may sit inside a quoted field.
    let terminator: &[u8] = match records.first() {
        Some(r) if !r.term.is_empty() => &original[r.term.clone()],
        _ if crlf => b"\r\n",
        _ => b"\n",
    };
    // Never quoted for TSV, as it was read (#1136).
    let quote_style = if delim == b'\t' {
        csv::QuoteStyle::Never
    } else {
        file_quote_style(&records, original, delim)
    };
    // Record indexes by values, in file order. A row takes the record at
    // its own position when that one has its values, so of two equal rows
    // written differently each keeps its own bytes; a moved row (a sort)
    // takes the first one left.
    let mut unchanged: std::collections::HashMap<&[String], Vec<usize>> =
        std::collections::HashMap::new();
    for (i, r) in records.iter().enumerate() {
        unchanged.entry(r.fields.as_slice()).or_default().push(i);
    }
    let mut out = Vec::new();
    let mut at = 0usize;
    let mut write = |record: &[String]| {
        // A row with no fields is a blank line the file had (see
        // `parse_delimited`); the writer would emit `""` for it instead.
        if record.is_empty() {
            out.extend_from_slice(terminator);
            return;
        }
        let pos = at;
        at += 1;
        let reused = unchanged.get_mut(record).and_then(|q| {
            let k = q.iter().position(|&i| i == pos).unwrap_or(0);
            (!q.is_empty()).then(|| q.remove(k))
        });
        if let Some(i) = reused {
            let r = &records[i];
            out.extend_from_slice(&original[r.span.clone()]);
            // Its own line ending; none only for the file's last line.
            out.extend_from_slice(if r.term.is_empty() {
                terminator
            } else {
                &original[r.term.clone()]
            });
            return;
        }
        let mut w = csv::WriterBuilder::new()
            .delimiter(delim)
            .flexible(true)
            .terminator(if terminator == b"\r\n" {
                csv::Terminator::CRLF
            } else {
                csv::Terminator::Any(terminator[0])
            })
            .quote_style(quote_style)
            .from_writer(&mut out);
        let _ = w.write_record(record);
        let _ = w.flush();
    };
    if !data.headers.is_empty() {
        write(&data.headers);
    }
    for r in &data.rows {
        write(r);
    }
    // A file that ended without a line ending still does, unless its last
    // row is a blank line, which is nothing but its line ending.
    let unterminated = original.last().is_some_and(|b| !matches!(b, b'\r' | b'\n'));
    if unterminated && data.rows.last().is_none_or(|r| !r.is_empty()) {
        let cut = if out.ends_with(b"\r\n") {
            2
        } else {
            usize::from(matches!(out.last(), Some(b'\r' | b'\n')))
        };
        out.truncate(out.len() - cut);
    }
    out
}

/// One record of a delimited file as it is on disk (#1375).
struct RawRecord {
    /// Its values, as the grid shows them.
    fields: Vec<String>,
    /// Its bytes, line ending and blank lines around it left out.
    span: std::ops::Range<usize>,
    /// Its line ending: `\r\n`, `\n`, `\r`, or empty at the end of a file
    /// with none.
    term: std::ops::Range<usize>,
}

/// Every record of a delimited file with the bytes it was read from (#1375).
/// Read as [`parse_delimited`] reads, so a record's values are the ones the
/// grid shows. A file that does not parse yields none.
fn raw_records(bytes: &[u8], delim: u8) -> Vec<RawRecord> {
    let mut reader = csv::ReaderBuilder::new()
        .has_headers(false)
        .flexible(true)
        .delimiter(delim)
        .quoting(delim != b'\t')
        .from_reader(bytes);
    let mut out: Vec<RawRecord> = Vec::new();
    for record in reader.records() {
        let Ok(r) = record else {
            return Vec::new();
        };
        // Where the reader began looking for this record: the end of the
        // previous one, line ending included.
        let at = r.position().map_or(0, |p| p.byte() as usize);
        if let Some(prev) = out.last_mut() {
            prev.span.end = at;
        }
        // Past the blank lines (and a CRLF's `\n`) the reader skipped.
        let mut start = at;
        while matches!(bytes.get(start), Some(b'\r' | b'\n')) {
            start += 1;
        }
        out.push(RawRecord {
            fields: r.iter().map(str::to_string).collect(),
            span: start..bytes.len(),
            term: 0..0,
        });
    }
    for r in &mut out {
        let span = &mut r.span;
        while span.end > span.start && matches!(bytes[span.end - 1], b'\r' | b'\n') {
            span.end -= 1;
        }
        let rest = &bytes[span.end..];
        let len = if rest.starts_with(b"\r\n") {
            2
        } else {
            usize::from(matches!(rest.first(), Some(b'\r' | b'\n')))
        };
        r.term = span.end..span.end + len;
    }
    out
}

/// The quoting a delimited file was written with, read from its records:
/// every field quoted, or exactly the fields that are not numbers, or
/// neither (quote where needed). A number is what the csv writer's
/// `NonNumeric` style takes as one, so that style writes such a file back.
fn file_quote_style(records: &[RawRecord], bytes: &[u8], delim: u8) -> csv::QuoteStyle {
    let is_number = |s: &str| s.parse::<f64>().is_ok() || s.parse::<i128>().is_ok();
    let (mut quoted, mut bare_numbers, mut bare_other) = (0usize, 0usize, 0usize);
    for RawRecord { fields, span, .. } in records {
        let raw = &bytes[span.clone()];
        // The reader drops a UTF-8 BOM from the first value; a quote after
        // it still opens that field.
        let raw = if span.start == 0 {
            raw.strip_prefix(b"\xEF\xBB\xBF").unwrap_or(raw)
        } else {
            raw
        };
        let flags = quoted_fields(raw, delim);
        if flags.len() != fields.len() {
            return csv::QuoteStyle::Necessary;
        }
        for (field, was_quoted) in fields.iter().zip(flags) {
            match (was_quoted, is_number(field)) {
                (true, _) => quoted += 1,
                (false, true) => bare_numbers += 1,
                (false, false) => bare_other += 1,
            }
        }
    }
    match (quoted, bare_numbers, bare_other) {
        (1.., 0, 0) => csv::QuoteStyle::Always,
        (1.., 1.., 0) => csv::QuoteStyle::NonNumeric,
        _ => csv::QuoteStyle::Necessary,
    }
}

/// For each field of one raw record, whether it was written in quotes.
fn quoted_fields(raw: &[u8], delim: u8) -> Vec<bool> {
    let mut flags = Vec::new();
    let mut i = 0;
    loop {
        let quoted = raw.get(i) == Some(&b'"');
        flags.push(quoted);
        if quoted {
            // Past the closing quote; `""` inside is an escaped quote.
            i += 1;
            while i < raw.len() {
                if raw[i] == b'"' {
                    if raw.get(i + 1) == Some(&b'"') {
                        i += 2;
                        continue;
                    }
                    break;
                }
                i += 1;
            }
        }
        match raw[i.min(raw.len())..].iter().position(|&b| b == delim) {
            Some(off) => i += off + 1,
            None => return flags,
        }
    }
}

/// Outcome of an xlsx edit save (#178).
pub struct XlsxSaveReport {
    pub written: usize,
    /// A1-style coordinates of formula cells left untouched because the
    /// caller did not consent to overwriting formulas.
    pub formula_skipped: Vec<String>,
}

/// Write grid cell edits back into the workbook through umya (#178):
/// the file is re-read (styles, widths, and untouched cells preserved),
/// each edited cell's grid value is applied (numbers as numbers, all
/// else as strings), and the workbook is written in place. A cell that
/// holds a FORMULA is skipped unless `overwrite_formulas`, since the
/// grid shows calamine's cached value and writing it back would destroy
/// the formula silently.
pub fn save_xlsx_edits(
    path: &Path,
    sheets: &[SheetData],
    edits: &[(usize, usize, usize)],
    overwrite_formulas: bool,
) -> Result<XlsxSaveReport, String> {
    let mut book = umya_spreadsheet::reader::xlsx::read(path).map_err(|e| e.to_string())?;
    let mut written = 0usize;
    let mut formula_skipped: Vec<String> = Vec::new();
    for &(si, r, c) in edits {
        let Some(data) = sheets.get(si) else {
            continue;
        };
        let value = data.cell(r, c).to_string();
        let Ok(ws) = book.sheet_by_name_mut(&data.name) else {
            continue;
        };
        // Grid body row r sits below the header (one range row) inside
        // the used range at `origin`; umya coordinates are 1-based.
        let col = data.origin.1 + c as u32 + 1;
        let row = data.origin.0 + r as u32 + 2;
        let cell = ws.cell_mut((col, row));
        if cell.is_formula() && !overwrite_formulas {
            // Sheet-QUALIFIED (#194 review): a bare A1 key would pin an
            // ordinary edit at the same coordinates on another sheet.
            formula_skipped.push(format!("{}!{}{row}", data.name, column_letters(col)));
            continue;
        }
        // Typed writes (#194 review): calamine formats booleans as
        // lowercase true/false, which set_value would store as STRINGS.
        if value.eq_ignore_ascii_case("true") {
            cell.set_value_bool(true);
        } else if value.eq_ignore_ascii_case("false") {
            cell.set_value_bool(false);
        } else if let Some(n) = xlsx_number(&value) {
            cell.set_value_number(n);
        } else {
            cell.set_value_string(value);
        }
        written += 1;
    }
    umya_spreadsheet::writer::xlsx::write(&book, path).map_err(|e| e.to_string())?;
    Ok(XlsxSaveReport {
        written,
        formula_skipped,
    })
}

/// The number an edited cell's text is stored as, or None to store it as
/// text. `f64::from_str` alone is too eager: it takes `nan` and `inf`
/// (and `1e400` becomes infinity), which Excel reports as a corrupt file,
/// and a zip code like `02134` would lose its leading zero.
fn xlsx_number(value: &str) -> Option<f64> {
    let digits = value.strip_prefix('-').unwrap_or(value);
    let plain = !digits.is_empty()
        && digits.starts_with(|c: char| c.is_ascii_digit())
        && digits
            .chars()
            .all(|c| c.is_ascii_digit() || matches!(c, '.' | 'e' | 'E' | '-' | '+'));
    let leading_zero = digits.len() > 1 && digits.starts_with('0') && !digits.starts_with("0.");
    if !plain || leading_zero {
        return None;
    }
    value.parse::<f64>().ok().filter(|n| n.is_finite())
}

/// 1-based column index to A1 letters (1 -> A, 27 -> AA).
pub fn column_letters_pub(col: u32) -> String {
    column_letters(col)
}

fn column_letters(mut col: u32) -> String {
    let mut s = String::new();
    while col > 0 {
        let rem = ((col - 1) % 26) as u8;
        s.insert(0, (b'A' + rem) as char);
        col = (col - 1) / 26;
    }
    s
}

fn split_header(mut rows: Vec<Vec<String>>) -> (Option<Vec<String>>, Vec<Vec<String>>) {
    if rows.is_empty() {
        return (None, Vec::new());
    }
    let header = rows.remove(0);
    (Some(header), rows)
}

fn compute_col_widths(headers: Option<&Vec<String>>, rows: &[Vec<String>]) -> Vec<u16> {
    let header_cols = headers.map(|h| h.len()).unwrap_or(0);
    let max_cols = rows
        .iter()
        .map(|r| r.len())
        .max()
        .unwrap_or(0)
        .max(header_cols);
    let mut widths = vec![MIN_COL_DISPLAY_W; max_cols];
    if let Some(h) = headers {
        for (i, cell) in h.iter().enumerate() {
            widths[i] = widths[i].max(display_width(cell));
        }
    }
    for row in rows {
        for (i, cell) in row.iter().enumerate() {
            if i >= widths.len() {
                continue;
            }
            widths[i] = widths[i].max(display_width(cell));
        }
    }
    for w in widths.iter_mut() {
        *w = (*w).clamp(MIN_COL_DISPLAY_W, MAX_COL_DISPLAY_W);
    }
    widths
}

/// The columns a grid body `body_w` wide shows from `scroll_col`: each one's
/// index, x offset and drawn width, with a one-column gap after each. The
/// renderer and mouse hit-testing both lay out with this, so a click lands
/// on the cell drawn under it. A first column wider than the whole body is
/// drawn clipped to it rather than left out: a narrow pane never shows an
/// empty grid because one value is long (a 20-character CJK value is 40
/// columns wide).
pub fn visible_columns(widths: &[u16], scroll_col: usize, body_w: u16) -> Vec<(usize, u16, u16)> {
    let mut out = Vec::new();
    let mut x_off = 0u16;
    for (c, &w) in widths.iter().enumerate().skip(scroll_col) {
        if x_off.saturating_add(w).saturating_add(1) > body_w {
            if out.is_empty() && body_w > 0 {
                out.push((c, 0, body_w));
            }
            break;
        }
        out.push((c, x_off, w));
        x_off += w + 1;
    }
    out
}

/// Screen columns a cell's text needs, capped at the widest a column gets.
/// Counted the way the grid draws it (#1138): CJK, Hangul and emoji take
/// two columns, so a count of chars gave `서울특별시` half its width and the
/// next column painted over it.
fn display_width(s: &str) -> u16 {
    use unicode_segmentation::UnicodeSegmentation;
    let mut w = 0;
    for g in s.graphemes(true) {
        w += grapheme_width(g);
        if w >= MAX_COL_DISPLAY_W as usize {
            break;
        }
    }
    w.min(MAX_COL_DISPLAY_W as usize) as u16
}

/// Columns one grapheme of a cell takes in the grid. A control character
/// is drawn as one visible glyph (`⏎`, `→`, `␀`), so it is one column each;
/// anything else is as wide as the terminal draws it.
pub(crate) fn grapheme_width(g: &str) -> usize {
    if g.contains(char::is_control) {
        g.chars().count()
    } else {
        unicode_width::UnicodeWidthStr::width(g)
    }
}

/// Columns `s` takes in the grid: [`grapheme_width`] summed.
pub(crate) fn text_width(s: &str) -> usize {
    use unicode_segmentation::UnicodeSegmentation;
    s.graphemes(true).map(grapheme_width).sum()
}

/// Refuse a sheet whose dense extent is over [`MAX_SHEET_CELLS`], as a
/// [`PastSheetCap`] so the open is not rerouted to the text editor.
fn check_sheet_extent(name: &str, rows: u64, cols: u64) -> std::io::Result<()> {
    if rows.saturating_mul(cols) > MAX_SHEET_CELLS {
        return Err(past_sheet_cap(format!(
            "Sheet too large: {name} is {rows}x{cols} cells (max {}M)",
            MAX_SHEET_CELLS / 1_000_000
        )));
    }
    Ok(())
}

/// Each table's `(name, rows, columns)` as calamine will expand it: the
/// rectangle from the first to the last row and column holding a value,
/// with `number-rows-repeated` / `number-columns-repeated` counted inside
/// it. Repeated EMPTY rows and cells past the last value (LibreOffice pads
/// every sheet with them) expand to nothing, as in calamine. A cell holds a
/// value when calamine reads one from it: any `office:*value` attribute, or
/// a string value type (its text, even none). A value type alone, a comment
/// or a formula is empty. Streams content.xml, keeping only running bounds.
fn ods_extents(path: &Path) -> std::io::Result<Vec<(String, u64, u64)>> {
    use quick_xml::events::{BytesStart, Event};
    let file = std::fs::File::open(path)?;
    let mut zip = zip::ZipArchive::new(file).map_err(std::io::Error::other)?;
    let content = zip
        .by_name("content.xml")
        .map_err(|e| std::io::Error::other(format!("content.xml: {e}")))?;
    let mut reader = quick_xml::Reader::from_reader(std::io::BufReader::new(content));
    let xml_err = |e: quick_xml::Error| std::io::Error::other(format!("content.xml: {e}"));
    // calamine adds nothing for a repeat of 0, so neither does the count.
    let repeat = |e: &BytesStart, key: &[u8]| -> u64 {
        e.try_get_attribute(key)
            .ok()
            .flatten()
            .and_then(|a| std::str::from_utf8(&a.value).ok()?.trim().parse().ok())
            .unwrap_or(1)
    };
    let valued = |e: &BytesStart| {
        e.attributes().flatten().any(|a| match a.key.as_ref() {
            b"office:value"
            | b"office:string-value"
            | b"office:date-value"
            | b"office:time-value"
            | b"office:boolean-value" => true,
            b"office:value-type" => &*a.value == b"string",
            _ => false,
        })
    };
    let mut out = Vec::new();
    let mut buf = Vec::new();
    let mut skip = Vec::new();
    let mut table: Option<String> = None;
    // Rows seen so far (repeats counted), the first valued row's start, the
    // last valued row's end, and the valued columns' span over all rows.
    let (mut row_at, mut first, mut last, mut cols) = (0u64, None::<u64>, 0u64, None::<(u64, u64)>);
    // The open row: its repeat count, next column, and valued columns.
    let (mut row_repeat, mut col, mut span) = (1u64, 0u64, None::<(u64, u64)>);
    loop {
        let ev = reader.read_event_into(&mut buf).map_err(xml_err)?;
        let empty = matches!(ev, Event::Empty(_));
        match ev {
            Event::Start(e) | Event::Empty(e)
                if table.is_none() && e.name().as_ref() == b"table:table" =>
            {
                let name = e
                    .try_get_attribute(b"table:name")
                    .ok()
                    .flatten()
                    .map(|a| String::from_utf8_lossy(&a.value).into_owned())
                    .unwrap_or_default();
                table = Some(name);
                (row_at, first, last, cols) = (0, None, 0, None);
            }
            Event::Start(e) if e.name().as_ref() == b"table:table-row" => {
                (row_repeat, col, span) = (repeat(&e, b"table:number-rows-repeated"), 0, None);
            }
            Event::Empty(e) if e.name().as_ref() == b"table:table-row" => {
                row_at = row_at.saturating_add(repeat(&e, b"table:number-rows-repeated"));
            }
            Event::End(e) if e.name().as_ref() == b"table:table-row" => {
                if let Some((a, b)) = span
                    && row_repeat > 0
                {
                    first.get_or_insert(row_at);
                    last = row_at.saturating_add(row_repeat);
                    cols = Some(cols.map_or((a, b), |(lo, hi)| (lo.min(a), hi.max(b))));
                }
                row_at = row_at.saturating_add(row_repeat);
            }
            Event::Start(e) | Event::Empty(e)
                if matches!(
                    e.name().as_ref(),
                    b"table:table-cell" | b"table:covered-table-cell"
                ) =>
            {
                let n = repeat(&e, b"table:number-columns-repeated");
                if n > 0 && valued(&e) {
                    let end = col.saturating_add(n - 1);
                    span = Some(span.map_or((col, end), |(a, _)| (a, end)));
                }
                col = col.saturating_add(n);
                // The cell's text, comments and anything nested in it are
                // not cells of this table.
                if !empty {
                    let name = e.name().as_ref().to_vec();
                    reader
                        .read_to_end_into(quick_xml::name::QName(&name), &mut skip)
                        .map_err(xml_err)?;
                    skip.clear();
                }
            }
            Event::End(e) if e.name().as_ref() == b"table:table" => {
                let name = table.take().unwrap_or_default();
                match (first, cols) {
                    (Some(first), Some((lo, hi))) => out.push((name, last - first, hi - lo + 1)),
                    _ => out.push((name, 0, 0)),
                }
            }
            Event::Eof => break,
            _ => {}
        }
        buf.clear();
    }
    Ok(out)
}

/// Why a workbook did not load: refused for its extent, or calamine's own
/// error.
enum WorkbookError {
    TooLarge(std::io::Error),
    Calamine(calamine::Error),
}

impl From<calamine::Error> for WorkbookError {
    fn from(e: calamine::Error) -> Self {
        WorkbookError::Calamine(e)
    }
}

/// The dense extent `(rows, columns)` of a sheet's values, from its cells
/// streamed one at a time, so measuring it allocates nothing per cell.
/// calamine builds the range from the first to the last non-empty cell.
fn streamed_extent<E>(
    mut next: impl FnMut() -> Result<Option<(u32, u32, bool)>, E>,
) -> Result<(u64, u64), E> {
    let mut bounds: Option<(u32, u32, u32, u32)> = None;
    while let Some((r, c, empty)) = next()? {
        if empty {
            continue;
        }
        bounds = Some(match bounds {
            None => (r, r, c, c),
            Some((r0, r1, c0, c1)) => (r0.min(r), r1.max(r), c0.min(c), c1.max(c)),
        });
    }
    Ok(bounds.map_or((0, 0), |(r0, r1, c0, c1)| {
        ((r1 - r0) as u64 + 1, (c1 - c0) as u64 + 1)
    }))
}

/// Open a workbook with calamine. `open_workbook_auto` resolves the reader
/// from the file EXTENSION, so a content-routed file without one (#174)
/// needs the explicit reader for its sniffed kind.
fn open_calamine(
    path: &Path,
    kind: SheetKind,
) -> Result<calamine::Sheets<std::io::BufReader<std::fs::File>>, calamine::Error> {
    Ok(match calamine::open_workbook_auto(path) {
        Ok(w) => w,
        Err(auto_err) => match kind {
            SheetKind::Xlsx => calamine::Sheets::Xlsx(calamine::open_workbook(path)?),
            SheetKind::Xls => calamine::Sheets::Xls(calamine::open_workbook(path)?),
            SheetKind::Ods => calamine::Sheets::Ods(calamine::open_workbook(path)?),
            SheetKind::Xlsb => calamine::Sheets::Xlsb(calamine::open_workbook(path)?),
            SheetKind::Csv | SheetKind::Tsv | SheetKind::Sqlite => return Err(auto_err),
        },
    })
}

fn read_calamine_workbook(path: &Path, kind: SheetKind) -> Result<Vec<SheetData>, WorkbookError> {
    use calamine::{Data, Reader};
    let mut workbook = open_calamine(path, kind)?;
    let sheet_names = workbook.sheet_names();
    let mut out: Vec<SheetData> = Vec::with_capacity(sheet_names.len());
    for name in sheet_names {
        // xlsx and xlsb build a dense range from sparse cells, so two values
        // at opposite corners ask for the whole grid between them.
        // A sheet whose cells cannot be streamed (a chart sheet, a broken
        // part) is skipped rather than built unmeasured, as one whose range
        // cannot be read is below.
        let extent = match &mut workbook {
            calamine::Sheets::Xlsx(x) => {
                let Ok(mut r) = x.worksheet_cells_reader(&name) else {
                    continue;
                };
                let Ok(extent) = streamed_extent(|| {
                    r.next_cell().map(|c| {
                        c.map(|c| {
                            let (row, col) = c.get_position();
                            (row, col, matches!(c.get_value(), calamine::DataRef::Empty))
                        })
                    })
                }) else {
                    continue;
                };
                Some(extent)
            }
            calamine::Sheets::Xlsb(x) => {
                let Ok(mut r) = x.worksheet_cells_reader(&name) else {
                    continue;
                };
                let Ok(extent) = streamed_extent(|| {
                    r.next_cell().map(|c| {
                        c.map(|c| {
                            let (row, col) = c.get_position();
                            (row, col, matches!(c.get_value(), calamine::DataRef::Empty))
                        })
                    })
                }) else {
                    continue;
                };
                Some(extent)
            }
            _ => None,
        };
        if let Some((rows, cols)) = extent {
            check_sheet_extent(&name, rows, cols).map_err(WorkbookError::TooLarge)?;
        }
        let range = match workbook.worksheet_range(&name) {
            Ok(r) => r,
            Err(_) => continue,
        };
        let origin = range.start().unwrap_or((0, 0));
        let mut rows: Vec<Vec<String>> = Vec::with_capacity(range.height());
        for row in range.rows() {
            rows.push(row.iter().map(format_cell).collect());
        }
        let (headers, body) = split_header(rows);
        let col_widths = compute_col_widths(headers.as_ref(), &body);
        out.push(SheetData {
            name,
            headers: headers.unwrap_or_default(),
            rows: body,
            col_widths,
            scroll_row: 0,
            scroll_col: 0,
            cur_row: 0,
            cur_col: 0,
            origin,
            row_base: 0,
            revision: 0,
            null_cells: Default::default(),
        });
    }
    let _ = Data::Empty; // keeps the import explicit even if unused above
    Ok(out)
}

fn format_cell(d: &calamine::Data) -> String {
    match d {
        calamine::Data::Empty => std::string::String::new(),
        calamine::Data::String(s) => s.clone(),
        calamine::Data::Float(f) => format_float(*f),
        calamine::Data::Int(i) => i.to_string(),
        calamine::Data::Bool(b) => b.to_string(),
        calamine::Data::DateTime(dt) => dt.to_string(),
        calamine::Data::DateTimeIso(s) | calamine::Data::DurationIso(s) => s.clone(),
        // The code the file stores and every spreadsheet shows (`#DIV/0!`,
        // `#N/A`), not the Rust variant name (`#Div0`, `#NA`) (#1144).
        // calamine's `Display` spells error 0x2B `#DATA!`; Excel's code for it
        // is `#GETTING_DATA`.
        calamine::Data::Error(calamine::CellErrorType::GettingData) => {
            String::from("#GETTING_DATA")
        }
        calamine::Data::Error(e) => e.to_string(),
    }
}

/// A float as a spreadsheet shows a number with no format of its own:
/// positional while that reads well, exponent notation for the very small
/// and the very large (#1143). Positional `1e-50` is 52 characters, cut at
/// the column width to a row of zeros that reads as zero.
pub(crate) fn format_float(f: f64) -> String {
    let a = f.abs();
    if f.fract() == 0.0 && a < 1e15 {
        format!("{}", f as i64)
    } else if f.is_finite() && a != 0.0 && !(1e-4..1e15).contains(&a) {
        format!("{f:e}")
    } else {
        format!("{f}")
    }
}

#[cfg(test)]
pub(crate) mod tests {
    use std::io::Write as _;
    use std::path::Path;

    /// A damaged zip (#2709): 16 bytes of junk in front shift every offset
    /// the archive records, and its one entry claims, through its zip64
    /// extra field, a local header at the last offset a u64 holds. Adding
    /// the shift overflows, and the zip reader fails with its own "Archive
    /// header is too large".
    pub(crate) fn overflowing_zip(p: &Path) {
        let mut buf = std::io::Cursor::new(Vec::new());
        {
            let mut z = zip::ZipWriter::new(&mut buf);
            let o = zip::write::SimpleFileOptions::default()
                .compression_method(zip::CompressionMethod::Stored);
            z.start_file("xl/workbook.xml", o).unwrap();
            z.write_all(b"<workbook/>").unwrap();
            z.finish().unwrap();
        }
        let mut bytes = buf.into_inner();
        let cd = bytes
            .windows(4)
            .position(|w| w == [0x50, 0x4b, 0x01, 0x02])
            .expect("a central directory entry");
        let name_len = u16::from_le_bytes([bytes[cd + 28], bytes[cd + 29]]) as usize;
        let extra_len = u16::from_le_bytes([bytes[cd + 30], bytes[cd + 31]]) as usize;
        // The local header offset becomes the zip64 sentinel, so the reader
        // takes it from the extra field instead.
        bytes[cd + 42..cd + 46].copy_from_slice(&u32::MAX.to_le_bytes());
        let mut zip64 = vec![0x01, 0x00, 0x08, 0x00];
        zip64.extend_from_slice(&u64::MAX.to_le_bytes());
        let at = cd + 46 + name_len + extra_len;
        bytes.splice(at..at, zip64.iter().copied());
        bytes[cd + 30..cd + 32].copy_from_slice(&((extra_len + 12) as u16).to_le_bytes());
        let eocd = bytes
            .windows(4)
            .rposition(|w| w == [0x50, 0x4b, 0x05, 0x06])
            .expect("an end of central directory");
        let cd_size = u32::from_le_bytes(bytes[eocd + 12..eocd + 16].try_into().unwrap()) + 12;
        bytes[eocd + 12..eocd + 16].copy_from_slice(&cd_size.to_le_bytes());
        let mut out = vec![0u8; 16];
        out.extend_from_slice(&bytes);
        std::fs::write(p, out).unwrap();
    }

    /// A damaged workbook whose zip reader says "too large" failed to
    /// parse; it was not refused for its size (#2709).
    #[test]
    fn a_damaged_workbook_is_not_refused_for_its_size() {
        let tmp = tempfile::tempdir().unwrap();
        let p = tmp.path().join("damaged.xlsx");
        overflowing_zip(&p);
        let e = super::open_sheet(&p).unwrap_err();
        assert!(
            e.to_string().contains("Archive header is too large"),
            "staging: the zip reader's own wording: {e}"
        );
        assert!(!super::is_size_refusal(&e), "{e}");
    }
    #[test]
    fn formula_errors_read_as_the_codes_spreadsheets_show() {
        use calamine::{CellErrorType as E, Data};
        for (e, code) in [
            (E::Div0, "#DIV/0!"),
            (E::NA, "#N/A"),
            (E::Name, "#NAME?"),
            (E::Null, "#NULL!"),
            (E::Num, "#NUM!"),
            (E::Ref, "#REF!"),
            (E::Value, "#VALUE!"),
            (E::GettingData, "#GETTING_DATA"),
        ] {
            assert_eq!(super::format_cell(&Data::Error(e)), code);
        }
    }

    #[test]
    fn sorting_a_column_orders_numbers_as_numbers_and_toggles() {
        let mut d = super::parse_delimited(b"name,count\nb,10\nA,9\nc,100\n", b',', "s").unwrap();
        d.cur_row = 2; // on "c"
        assert!(d.sort_by_column(1), "ascending first");
        let col = |d: &super::SheetData, c: usize| -> Vec<String> {
            d.rows.iter().map(|r| r[c].clone()).collect()
        };
        assert_eq!(col(&d, 1), ["9", "10", "100"], "as numbers, not text");
        assert_eq!(d.rows[d.cur_row][0], "c", "the cursor keeps its row");
        assert!(!d.sort_by_column(1), "again: descending");
        assert_eq!(col(&d, 1), ["100", "10", "9"]);
        assert!(d.sort_by_column(0));
        assert_eq!(col(&d, 0), ["A", "b", "c"], "text without case");
        assert_eq!(d.headers, ["name", "count"], "the header stays put");
    }

    #[test]
    fn a_first_column_wider_than_the_body_is_clipped_not_dropped() {
        // Columns that fit keep their width with a gap after each.
        assert_eq!(
            super::visible_columns(&[5, 8, 4], 0, 19),
            vec![(0, 0, 5), (1, 6, 8)]
        );
        // One 40-wide column in a 30-wide body: drawn at 30, not left out.
        assert_eq!(super::visible_columns(&[40, 5], 0, 30), vec![(0, 0, 30)]);
        // Scrolled onto it, the same.
        assert_eq!(super::visible_columns(&[3, 40], 1, 30), vec![(1, 0, 30)]);
        // Only the FIRST column is clipped; a later one that does not fit
        // waits for a scroll.
        assert_eq!(super::visible_columns(&[5, 40], 0, 30), vec![(0, 0, 5)]);
        assert!(super::visible_columns(&[5], 0, 0).is_empty());
    }

    #[test]
    fn a_cell_width_never_passes_the_column_cap() {
        // 39 narrow columns then a wide glyph would be 41.
        let s = format!("{}表", "x".repeat(super::MAX_COL_DISPLAY_W as usize - 1));
        assert_eq!(super::display_width(&s), super::MAX_COL_DISPLAY_W);
        assert_eq!(super::display_width("表表"), 4);
    }

    /// Write a zip of `(name, text)` members.
    fn zip_of(path: &std::path::Path, members: &[(&str, &str)]) {
        use std::io::Write as _;
        let mut z = zip::ZipWriter::new(std::fs::File::create(path).unwrap());
        let o = zip::write::SimpleFileOptions::default()
            .compression_method(zip::CompressionMethod::Deflated);
        for (name, text) in members {
            z.start_file(*name, o).unwrap();
            z.write_all(text.as_bytes()).unwrap();
        }
        z.finish().unwrap();
    }

    /// A one-table .ods whose `table:table` body is `rows`.
    fn ods_with(path: &std::path::Path, rows: &str) {
        let content = format!(
            r#"<?xml version="1.0" encoding="UTF-8"?><office:document-content xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0" xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0" office:version="1.2"><office:body><office:spreadsheet><table:table table:name="Sheet1">{rows}</table:table></office:spreadsheet></office:body></office:document-content>"#
        );
        zip_of(
            path,
            &[
                ("mimetype", "application/vnd.oasis.opendocument.spreadsheet"),
                (
                    "META-INF/manifest.xml",
                    r#"<?xml version="1.0" encoding="UTF-8"?><manifest:manifest xmlns:manifest="urn:oasis:names:tc:opendocument:xmlns:manifest:1.0" manifest:version="1.2"><manifest:file-entry manifest:full-path="/" manifest:media-type="application/vnd.oasis.opendocument.spreadsheet"/><manifest:file-entry manifest:full-path="content.xml" manifest:media-type="text/xml"/></manifest:manifest>"#,
                ),
                ("content.xml", &content),
            ],
        );
    }

    /// A one-sheet .xlsx whose `sheetData` is `data`.
    fn xlsx_with(path: &std::path::Path, data: &str) {
        let sheet = format!(
            r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><sheetData>{data}</sheetData></worksheet>"#
        );
        zip_of(
            path,
            &[
                (
                    "[Content_Types].xml",
                    r#"<?xml version="1.0"?><Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/><Override PartName="/xl/worksheets/sheet1.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/></Types>"#,
                ),
                (
                    "_rels/.rels",
                    r#"<?xml version="1.0"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/></Relationships>"#,
                ),
                (
                    "xl/workbook.xml",
                    r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?><workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><sheets><sheet name="Sheet1" sheetId="1" r:id="rId1"/></sheets></workbook>"#,
                ),
                (
                    "xl/_rels/workbook.xml.rels",
                    r#"<?xml version="1.0"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/></Relationships>"#,
                ),
                ("xl/worksheets/sheet1.xml", &sheet),
            ],
        );
    }

    #[test]
    fn an_ods_whose_repeats_expand_past_the_cell_budget_is_refused() {
        // #1156: a few hundred bytes of repeat attributes expand to more
        // cells than a grid holds; calamine expands them when the workbook
        // opens, so the size has to be known before that.
        let tmp = tempfile::tempdir().unwrap();
        let p = tmp.path().join("budget.ods");
        ods_with(
            &p,
            r#"<table:table-row table:number-rows-repeated="700"><table:table-cell office:value-type="string" table:number-columns-repeated="16384"><text:p>x</text:p></table:table-cell></table:table-row>"#,
        );
        assert!(std::fs::metadata(&p).unwrap().len() < 2048);
        let Err(err) = super::open_sheet(&p) else {
            panic!("must be refused");
        };
        let err = err.to_string();
        assert!(err.contains("too large"), "{err}");
        assert!(err.contains("700") && err.contains("16384"), "{err}");
    }

    #[test]
    fn an_ods_value_without_a_value_type_counts_toward_the_budget() {
        // #1187 review: calamine reads `office:value` as a number whatever
        // the value type says, so a repeated bare value still expands.
        let tmp = tempfile::tempdir().unwrap();
        let p = tmp.path().join("bare.ods");
        ods_with(
            &p,
            r#"<table:table-row table:number-rows-repeated="700"><table:table-cell office:value="1" table:number-columns-repeated="16384"/></table:table-row>"#,
        );
        assert_eq!(
            super::ods_extents(&p).unwrap(),
            [(String::from("Sheet1"), 700, 16384)]
        );
    }

    #[test]
    fn empty_typed_and_annotation_only_ods_cells_are_not_counted() {
        // #1187 review: a float-typed cell with no value and a cell holding
        // only a comment are empty to calamine, so a 1x1 sheet padded with
        // them is not refused as 701x16384.
        let tmp = tempfile::tempdir().unwrap();
        let p = tmp.path().join("padded.ods");
        ods_with(
            &p,
            concat!(
                r#"<table:table-row><table:table-cell office:value-type="string"><text:p>a</text:p></table:table-cell><table:table-cell table:number-columns-repeated="4"/><table:table-cell><office:annotation><text:p>note</text:p></office:annotation></table:table-cell></table:table-row>"#,
                r#"<table:table-row table:number-rows-repeated="700"><table:table-cell office:value-type="float" table:number-columns-repeated="16384"/></table:table-row>"#,
            ),
        );
        assert_eq!(
            super::ods_extents(&p).unwrap(),
            [(String::from("Sheet1"), 1, 1)]
        );
        let view = super::open_sheet(&p).unwrap();
        assert_eq!(view.sheets[0].headers, ["a"]);
    }

    #[test]
    fn a_zero_ods_repeat_covers_nothing() {
        // #1187 review: `number-columns-repeated="0"` made `col + n - 1`
        // underflow. calamine adds no cell for it.
        let tmp = tempfile::tempdir().unwrap();
        let p = tmp.path().join("zero.ods");
        ods_with(
            &p,
            concat!(
                r#"<table:table-row><table:table-cell office:value-type="string" table:number-columns-repeated="0"><text:p>gone</text:p></table:table-cell><table:table-cell office:value-type="string"><text:p>kept</text:p></table:table-cell></table:table-row>"#,
                r#"<table:table-row table:number-rows-repeated="0"><table:table-cell office:value-type="string"><text:p>none</text:p></table:table-cell></table:table-row>"#,
            ),
        );
        assert_eq!(
            super::ods_extents(&p).unwrap(),
            [(String::from("Sheet1"), 1, 1)]
        );
    }

    #[test]
    fn an_empty_string_typed_ods_cell_still_counts() {
        // Negative: calamine reads a string-typed cell with no text as an
        // empty string, which is a value, so it widens the sheet.
        let tmp = tempfile::tempdir().unwrap();
        let p = tmp.path().join("blank.ods");
        ods_with(
            &p,
            r#"<table:table-row><table:table-cell office:value-type="string"><text:p>a</text:p></table:table-cell><table:table-cell table:number-columns-repeated="2"/><table:table-cell office:value-type="string"/></table:table-row>"#,
        );
        assert_eq!(
            super::ods_extents(&p).unwrap(),
            [(String::from("Sheet1"), 1, 4)]
        );
    }

    #[test]
    fn an_xlsx_sheet_that_cannot_be_streamed_fails_to_open() {
        // #1187 review: a cells-reader error skipped the extent check and
        // went on to build the range; such a sheet is now skipped unbuilt.
        let tmp = tempfile::tempdir().unwrap();
        let p = tmp.path().join("broken.xlsx");
        xlsx_with(
            &p,
            r#"<row r="1"><c r="A1" t="inlineStr"><is><t>x</t></is></c></row><row r="2"><c r="!!" t="n"><v>1</v></c></row>"#,
        );
        assert!(super::open_sheet(&p).is_err());
    }

    #[test]
    fn an_xlsx_with_two_cells_at_opposite_corners_is_refused() {
        // #1156 (comment): A1 and XFD1048576 make calamine allocate the
        // dense 17-billion-cell rectangle between them (512 GB).
        let tmp = tempfile::tempdir().unwrap();
        let p = tmp.path().join("corner.xlsx");
        xlsx_with(
            &p,
            r#"<row r="1"><c r="A1" t="inlineStr"><is><t>corner one</t></is></c></row><row r="1048576"><c r="XFD1048576" t="inlineStr"><is><t>corner two</t></is></c></row>"#,
        );
        let Err(err) = super::open_sheet(&p) else {
            panic!("must be refused");
        };
        let err = err.to_string();
        assert!(err.contains("too large"), "{err}");
        assert!(err.contains("1048576") && err.contains("16384"), "{err}");
    }

    #[test]
    fn libreoffice_style_trailing_empty_repeats_still_open() {
        // Negative: LibreOffice pads a sheet with a huge repeated EMPTY
        // row and empty repeated cells; those expand to nothing.
        let tmp = tempfile::tempdir().unwrap();
        let p = tmp.path().join("real.ods");
        ods_with(
            &p,
            concat!(
                r#"<table:table-row><table:table-cell office:value-type="string"><text:p>name</text:p></table:table-cell><table:table-cell office:value-type="string"><text:p>qty</text:p></table:table-cell><table:table-cell table:number-columns-repeated="1022"/></table:table-row>"#,
                r#"<table:table-row table:number-rows-repeated="3"><table:table-cell office:value-type="string"><text:p>bolt</text:p></table:table-cell><table:table-cell office:value-type="float" office:value="4"><text:p>4</text:p></table:table-cell><table:table-cell table:number-columns-repeated="1022"/></table:table-row>"#,
                r#"<table:table-row table:number-rows-repeated="1048572"><table:table-cell table:number-columns-repeated="1024"/></table:table-row>"#,
            ),
        );
        let view = super::open_sheet(&p).unwrap();
        assert_eq!(view.sheets[0].headers, ["name", "qty"]);
        assert_eq!(view.sheets[0].rows.len(), 3);
        assert_eq!(view.sheets[0].cell(2, 1), "4");
    }

    #[test]
    fn an_xlsx_within_the_budget_still_opens() {
        // Negative: cells far apart but a modest rectangle between them.
        let tmp = tempfile::tempdir().unwrap();
        let p = tmp.path().join("ok.xlsx");
        xlsx_with(
            &p,
            r#"<row r="1"><c r="A1" t="inlineStr"><is><t>h</t></is></c></row><row r="5000"><c r="T5000" t="inlineStr"><is><t>far</t></is></c></row>"#,
        );
        let view = super::open_sheet(&p).unwrap();
        assert_eq!(view.sheets[0].rows.len(), 4999);
        assert_eq!(view.sheets[0].cell(4998, 19), "far");
    }

    /// The 30 house numbers from #1134: plain numbers mixed with `65a`-style
    /// values, which made the old comparator cyclic and the sort panic.
    const HOUSES: [&str; 30] = [
        "109", "114", "34", "63", "101", "62", "115", "65a", "97b", "117", "91", "116a", "94b",
        "61", "46", "79", "27", "62", "67", "104", "118b", "91", "86", "79", "112", "94", "112a",
        "31", "19", "58b",
    ];

    fn sheet_of(values: &[&str]) -> super::SheetData {
        let mut csv = String::from("name,house\n");
        for (i, v) in values.iter().enumerate() {
            csv.push_str(&format!("p{i},{v}\n"));
        }
        super::parse_delimited(csv.as_bytes(), b',', "s").unwrap()
    }

    fn column(d: &super::SheetData, c: usize) -> Vec<String> {
        d.rows.iter().map(|r| r[c].clone()).collect()
    }

    #[test]
    fn sorting_numbers_mixed_with_65a_values_neither_panics_nor_cycles() {
        let mut d = sheet_of(&HOUSES);
        assert!(d.sort_by_column(1));
        let got = column(&d, 1);
        let nums: Vec<f64> = got.iter().map_while(|v| v.parse().ok()).collect();
        assert!(
            nums.windows(2).all(|w| w[0] <= w[1]),
            "numbers ascend: {got:?}"
        );
        let rest = &got[nums.len()..];
        assert!(
            rest.iter().all(|v| v.parse::<f64>().is_err()),
            "numbers first: {got:?}"
        );
        assert!(
            rest.windows(2)
                .all(|w| w[0].to_lowercase() <= w[1].to_lowercase())
        );
        assert_eq!(got.len(), HOUSES.len(), "no row lost");
        // And back the other way: the exact reverse.
        assert!(!d.sort_by_column(1));
        let mut rev = column(&d, 1);
        rev.reverse();
        assert_eq!(rev, got);
    }

    #[test]
    fn a_column_with_no_mixed_kinds_sorts_as_before() {
        // Negative: all-text and all-number columns keep their old order.
        let mut d = sheet_of(&["b", "A", "c"]);
        d.sort_by_column(1);
        assert_eq!(column(&d, 1), ["A", "b", "c"]);
        let mut d = sheet_of(&["10", "-2.5", "9", "1e3"]);
        d.sort_by_column(1);
        assert_eq!(column(&d, 1), ["-2.5", "9", "10", "1e3"]);
    }

    #[test]
    fn very_small_and_very_large_floats_read_in_exponent_notation() {
        use super::format_float as f;
        assert_eq!(f(6.62607015e-34), "6.62607015e-34");
        assert_eq!(f(1e-50), "1e-50");
        assert_eq!(f(6.02214076e23), "6.02214076e23");
        assert_eq!(f(1e300), "1e300");
        assert_eq!(f(-2.5e-7), "-2.5e-7");
        // Everyday numbers keep their positional form.
        assert_eq!(f(0.0), "0");
        assert_eq!(f(42.0), "42");
        assert_eq!(f(1234.5678), "1234.5678");
        assert_eq!(f(0.00012), "0.00012");
        assert_eq!(f(-0.5), "-0.5");
        for v in [6.62607015e-34, 1e-50, 1e300, 6.02214076e23, 0.1 + 0.2] {
            let s = f(v);
            assert!(s.len() <= 24, "{s} fits a column");
            assert_eq!(s.parse::<f64>().unwrap(), v, "{s} reads back exactly");
        }
    }

    #[test]
    fn xlsx_edits_write_back_preserving_untouched_formulas() {
        let tmp = tempfile::tempdir().unwrap();
        let p = tmp.path().join("book.xlsx");
        // Build the fixture through umya itself: headers on row 1, data
        // below, one formula cell.
        let mut book = umya_spreadsheet::new_file();
        let ws = book.sheet_mut(0).unwrap();
        ws.cell_mut((1, 1)).set_value("name");
        ws.cell_mut((2, 1)).set_value("qty");
        ws.cell_mut((1, 2)).set_value("apples");
        ws.cell_mut((2, 2)).set_value_number(3);
        ws.cell_mut((1, 3)).set_value("pears");
        ws.cell_mut((2, 3)).set_formula("SUM(B2)");
        umya_spreadsheet::writer::xlsx::write(&book, &p).unwrap();

        let mut view = super::open_sheet_with_kind(&p, super::SheetKind::Xlsx).unwrap();
        let data = &mut view.sheets[0];
        assert_eq!(data.cell(0, 0), "apples");
        // Edit a plain cell and TRY to edit the formula cell.
        data.set_cell(0, 1, String::from("99"));
        data.set_cell(1, 1, String::from("7"));
        let edits = vec![(0usize, 0usize, 1usize), (0, 1, 1)];
        let report = super::save_xlsx_edits(&p, &view.sheets, &edits, false).unwrap();
        assert_eq!(report.written, 1, "the formula cell is skipped");
        assert_eq!(
            report.formula_skipped,
            vec![String::from("Sheet1!B3")],
            "skip keys are sheet-qualified (#194 review)"
        );

        // calamine re-read sees the new number; umya re-read still holds
        // the formula.
        let again = super::open_sheet_with_kind(&p, super::SheetKind::Xlsx).unwrap();
        assert_eq!(again.sheets[0].cell(0, 1), "99");
        let book2 = umya_spreadsheet::reader::xlsx::read(&p).unwrap();
        let ws2 = book2.sheet_by_name("Sheet1").unwrap();
        assert!(ws2.cell((2u32, 3u32)).unwrap().is_formula());

        // Explicit consent overwrites the formula with the literal.
        let report = super::save_xlsx_edits(&p, &view.sheets, &edits, true).unwrap();
        assert_eq!(report.written, 2);
        // Booleans round-trip TYPED, not as strings (#194 review).
        let data = &mut view.sheets[0];
        data.set_cell(0, 1, String::from("true"));
        data.set_cell(1, 1, String::from("FALSE"));
        let bool_edits = vec![(0usize, 0usize, 1usize), (0, 1, 1)];
        super::save_xlsx_edits(&p, &view.sheets, &bool_edits, true).unwrap();
        let again = super::open_sheet_with_kind(&p, super::SheetKind::Xlsx).unwrap();
        assert_eq!(
            again.sheets[0].cell(0, 1),
            "true",
            "typed bool re-reads as bool"
        );
        assert_eq!(again.sheets[0].cell(1, 1), "false");
        let book3 = umya_spreadsheet::reader::xlsx::read(&p).unwrap();
        let ws3 = book3.sheet_by_name("Sheet1").unwrap();
        assert!(!ws3.cell((2u32, 3u32)).unwrap().is_formula());
    }

    #[test]
    fn column_letters_cover_the_aa_rollover() {
        assert_eq!(super::column_letters(1), "A");
        assert_eq!(super::column_letters(26), "Z");
        assert_eq!(super::column_letters(27), "AA");
        assert_eq!(super::column_letters(52), "AZ");
    }

    #[test]
    fn cell_edits_grow_ragged_rows_and_serialize_with_quoting() {
        let mut d = super::parse_delimited(b"a,b,c\n1,2\n", b',', "S").unwrap();
        assert_eq!(d.headers, vec!["a", "b", "c"]);
        d.set_cell(0, 2, String::from("x,y"));
        assert_eq!(d.cell(0, 2), "x,y", "short row grew to hold the cell");
        let out = super::serialize_delimited(&d, b',', false, b"");
        assert_eq!(
            String::from_utf8(out).unwrap(),
            "a,b,c\n1,2,\"x,y\"\n",
            "delimiter-bearing cells are quoted, header row survives"
        );
    }

    /// The #1136 repro: TSV as `psql`, `mysql -B` and `cut` write it, with
    /// `"` as a plain character.
    const PRODUCTS_TSV: &[u8] = b"sku\tname\tsize\tqty\nA1\tDeluxe widget\t5\"\t10\nA2\t\"Pro\" ruler\t12in\t4\nA3\t\"12 inch ruler\t12in\t7\nA4\tnut\tM6\t100\nA5\tbolt\tM6\t50\n";

    /// #1136: a TSV cell starting with `"` doesn't swallow the rows after it.
    #[test]
    fn a_tsv_quote_is_a_plain_character() {
        let d = super::parse_delimited(PRODUCTS_TSV, b'\t', "S").unwrap();
        let skus: Vec<&str> = d.rows.iter().map(|r| r[0].as_str()).collect();
        assert_eq!(skus, vec!["A1", "A2", "A3", "A4", "A5"]);
        assert_eq!(d.cell(1, 1), "\"Pro\" ruler");
        assert_eq!(d.cell(2, 1), "\"12 inch ruler");
    }

    /// #1136: a one-cell edit to a TSV leaves every other line as it was.
    #[test]
    fn a_tsv_cell_edit_rewrites_only_that_cell() {
        let mut d = super::parse_delimited(PRODUCTS_TSV, b'\t', "S").unwrap();
        d.set_cell(0, 3, String::from("12"));
        let out = super::serialize_delimited(&d, b'\t', false, b"");
        let want = String::from_utf8(PRODUCTS_TSV.to_vec())
            .unwrap()
            .replacen("5\"\t10", "5\"\t12", 1);
        assert_eq!(String::from_utf8(out).unwrap(), want);
    }

    /// CSV keeps its quoting: a quoted field holds a comma or a line break,
    /// and a cell that needs quotes gets them on save.
    #[test]
    fn csv_quoting_is_unchanged() {
        let d = super::parse_delimited(b"a,b\n\"x,y\",\"two\nlines\"\n", b',', "S").unwrap();
        assert_eq!(
            d.rows,
            vec![vec!["x,y".to_string(), "two\nlines".to_string()]]
        );
        let out = super::serialize_delimited(&d, b',', false, b"");
        assert_eq!(out, b"a,b\n\"x,y\",\"two\nlines\"\n".to_vec());
    }

    /// A TSV with no quotes in it still round-trips byte for byte.
    #[test]
    fn a_plain_tsv_round_trips() {
        let src = b"h1\th2\n1\t2\n\n3\t\n";
        let d = super::parse_delimited(src, b'\t', "S").unwrap();
        assert_eq!(
            super::serialize_delimited(&d, b'\t', false, b""),
            src.to_vec()
        );
    }

    #[test]
    fn blank_lines_survive_a_save() {
        let src = b"name\nann\n\nbob\n\n\n\"x\ny\"\n";
        let d = super::parse_delimited(src, b',', "S").unwrap();
        assert_eq!(d.rows.len(), 6, "{:?}", d.rows);
        let out = super::serialize_delimited(&d, b',', false, b"");
        assert_eq!(out, src.to_vec(), "{}", String::from_utf8_lossy(&out));
        let lead = super::parse_delimited(b"\n\nh\n1\n", b',', "S").unwrap();
        assert_eq!(lead.headers, vec!["h"]);
        let crlf = b"a,b\r\n1,2\r\n\r\n3,4\r\n";
        let d = super::parse_delimited(crlf, b',', "S").unwrap();
        assert_eq!(
            super::serialize_delimited(&d, b',', true, b""),
            crlf.to_vec()
        );
    }

    /// #1375: the repro, R `write.csv` / Python `QUOTE_ALL` style.
    const QUOTED_CSV: &[u8] = b"\"id\",\"name\",\"city\",\"score\"\n\"1\",\"Ada\",\"London\",\"91\"\n\"2\",\"Grace\",\"New York\",\"88\"\n\"3\",\"Linus\",\"Helsinki\",\"79\"\n";

    fn changed_lines(before: &[u8], after: &[u8]) -> Vec<(usize, String)> {
        let before = String::from_utf8_lossy(before);
        let after = String::from_utf8_lossy(after);
        let (b, a): (Vec<&str>, Vec<&str>) = (before.lines().collect(), after.lines().collect());
        assert_eq!(b.len(), a.len(), "line count changed:\n{after}");
        a.iter()
            .zip(&b)
            .enumerate()
            .filter(|(_, (a, b))| a != b)
            .map(|(i, (a, _))| (i, a.to_string()))
            .collect()
    }

    /// #1375: one cell edited in a fully quoted file changes that line only,
    /// and the line stays fully quoted.
    #[test]
    fn a_quote_all_csv_edit_rewrites_only_that_line_and_keeps_its_quotes() {
        let mut d = super::parse_delimited(QUOTED_CSV, b',', "S").unwrap();
        d.set_cell(0, 3, String::from("95"));
        let out = super::serialize_delimited(&d, b',', false, QUOTED_CSV);
        assert_eq!(
            changed_lines(QUOTED_CSV, &out),
            vec![(1, String::from("\"1\",\"Ada\",\"London\",\"95\""))]
        );
    }

    /// #1375: a `QUOTE_NONNUMERIC` file keeps numbers bare and text quoted
    /// on the edited line.
    #[test]
    fn a_quote_nonnumeric_csv_edit_keeps_numbers_bare_and_text_quoted() {
        let src = b"\"id\",\"name\",\"score\"\n1,\"Ada\",91\n2,\"Grace\",88.5\n";
        let mut d = super::parse_delimited(src, b',', "S").unwrap();
        d.set_cell(1, 1, String::from("Grace H"));
        let out = super::serialize_delimited(&d, b',', false, src);
        assert_eq!(
            changed_lines(src, &out),
            vec![(2, String::from("2,\"Grace H\",88.5"))]
        );
    }

    /// #1375: a row added to a fully quoted file is quoted like the rest,
    /// its empty cells included.
    #[test]
    fn a_row_inserted_into_a_quote_all_csv_is_quoted_too() {
        let mut d = super::parse_delimited(QUOTED_CSV, b',', "S").unwrap();
        d.insert_row(3);
        d.set_cell(3, 1, String::from("Ken"));
        let out =
            String::from_utf8(super::serialize_delimited(&d, b',', false, QUOTED_CSV)).unwrap();
        assert!(
            out.starts_with(std::str::from_utf8(QUOTED_CSV).unwrap()),
            "{out}"
        );
        assert!(out.ends_with("\"\",\"Ken\",\"\",\"\"\n"), "{out}");
    }

    /// #1375: sorting moves rows but each keeps its own bytes.
    #[test]
    fn sorted_rows_keep_their_original_bytes() {
        let mut d = super::parse_delimited(QUOTED_CSV, b',', "S").unwrap();
        d.sort_by_column(3);
        let out =
            String::from_utf8(super::serialize_delimited(&d, b',', false, QUOTED_CSV)).unwrap();
        assert_eq!(
            out,
            "\"id\",\"name\",\"city\",\"score\"\n\"3\",\"Linus\",\"Helsinki\",\"79\"\n\"2\",\"Grace\",\"New York\",\"88\"\n\"1\",\"Ada\",\"London\",\"91\"\n"
        );
    }

    /// #1375 negative: an unquoted file saves as it always has, quoting only
    /// a cell that needs it.
    #[test]
    fn an_unquoted_csv_edit_still_quotes_only_when_needed() {
        let src = b"id,name,city\n1,Ada,London\n2,Grace,Paris\n";
        let mut d = super::parse_delimited(src, b',', "S").unwrap();
        d.set_cell(0, 2, String::from("London, UK"));
        let out = super::serialize_delimited(&d, b',', false, src);
        assert_eq!(
            String::from_utf8(out).unwrap(),
            "id,name,city\n1,Ada,\"London, UK\"\n2,Grace,Paris\n"
        );
    }

    /// #1375 negative: a file that mixes styles (R's bare `NA`) leaves its
    /// untouched lines alone and writes the edited one with the minimal
    /// quoting, rather than guessing a style the file does not have.
    #[test]
    fn a_mixed_quoting_csv_keeps_untouched_lines_and_quotes_the_edit_minimally() {
        let src = b"\"id\",\"name\",\"score\"\n1,\"Ada\",NA\n2,\"Grace\",88\n";
        let mut d = super::parse_delimited(src, b',', "S").unwrap();
        d.set_cell(1, 2, String::from("90"));
        let out = super::serialize_delimited(&d, b',', false, src);
        assert_eq!(
            changed_lines(src, &out),
            vec![(2, String::from("2,Grace,90"))]
        );
    }

    /// #1375 negative: a saved file the grid did not touch is byte-identical,
    /// odd spacing and a CRLF ending included.
    #[test]
    fn an_untouched_csv_saves_byte_for_byte() {
        let src = b"\"a\" ,b\r\n\"1\",2\r\n";
        let d = super::parse_delimited(src, b',', "S").unwrap();
        assert_eq!(
            super::serialize_delimited(&d, b',', true, src),
            src.to_vec()
        );
    }

    /// #1375: of two equal rows written differently, the untouched one
    /// keeps its own bytes when the other is edited.
    #[test]
    fn equal_rows_written_differently_each_keep_their_bytes() {
        let src = b"h\n\"x\"\nx\n";
        let mut d = super::parse_delimited(src, b',', "S").unwrap();
        d.set_cell(0, 0, String::from("y"));
        let out = super::serialize_delimited(&d, b',', false, src);
        assert_eq!(String::from_utf8(out).unwrap(), "h\ny\nx\n");
    }

    /// #1375: each untouched record keeps its own line ending, and a file
    /// without a final one still has none.
    #[test]
    fn untouched_records_keep_their_own_line_endings() {
        let src = b"h\na\nb";
        let mut d = super::parse_delimited(src, b',', "S").unwrap();
        d.set_cell(0, 0, String::from("z"));
        let out = super::serialize_delimited(&d, b',', false, src);
        assert_eq!(String::from_utf8(out).unwrap(), "h\nz\nb");
        let src = b"h\r\na\nb\r\n";
        let mut d = super::parse_delimited(src, b',', "S").unwrap();
        d.set_cell(1, 0, String::from("c"));
        let out = super::serialize_delimited(&d, b',', true, src);
        assert_eq!(String::from_utf8(out).unwrap(), "h\r\na\nc\r\n");
    }

    /// #1375: a CRLF file whose first field holds a newline is still CRLF
    /// for an edited row, whatever the caller guessed from its first `\n`.
    #[test]
    fn a_quoted_newline_does_not_set_the_line_ending() {
        let src = b"\"first\nsecond\",b\r\n1,2\r\n";
        let mut d = super::parse_delimited(src, b',', "S").unwrap();
        d.set_cell(0, 0, String::from("3"));
        let out = super::serialize_delimited(&d, b',', false, src);
        assert_eq!(
            String::from_utf8(out).unwrap(),
            "\"first\nsecond\",b\r\n3,2\r\n"
        );
    }

    /// #1375: a UTF-8 BOM before a fully quoted header does not hide that
    /// the file quotes every field.
    #[test]
    fn a_bom_does_not_hide_quote_all() {
        let mut src = b"\xEF\xBB\xBF".to_vec();
        src.extend_from_slice(QUOTED_CSV);
        let mut d = super::parse_delimited(&src, b',', "S").unwrap();
        d.set_cell(0, 3, String::from("95"));
        let out = super::serialize_delimited(&d, b',', false, &src);
        assert!(out.starts_with(&src[..3]), "the BOM stays");
        assert_eq!(
            changed_lines(&src, &out),
            vec![(1, String::from("\"1\",\"Ada\",\"London\",\"95\""))]
        );
    }

    #[test]
    fn a_crlf_file_saves_as_crlf() {
        let d = super::parse_delimited(b"a,b\r\n1,2\r\n", b',', "S").unwrap();
        let out = super::serialize_delimited(&d, b',', true, b"");
        assert_eq!(String::from_utf8(out).unwrap(), "a,b\r\n1,2\r\n");
    }

    #[test]
    fn only_plain_finite_numbers_are_stored_as_xlsx_numbers() {
        assert_eq!(super::xlsx_number("42"), Some(42.0));
        assert_eq!(super::xlsx_number("-0.5"), Some(-0.5));
        assert_eq!(super::xlsx_number("0"), Some(0.0));
        assert_eq!(super::xlsx_number("1.5e3"), Some(1500.0));
        for text in [
            "02134",
            "nan",
            "inf",
            "-infinity",
            "1e400",
            "+5",
            "",
            ".5",
            "1-2",
        ] {
            assert_eq!(super::xlsx_number(text), None, "{text}");
        }
    }

    #[test]
    fn row_and_column_ops_keep_headers_and_widths_in_step() {
        let mut d = super::parse_delimited(b"a,b\n1,2\n3,4\n", b',', "S").unwrap();
        d.insert_row(1);
        assert_eq!(d.rows.len(), 3);
        assert_eq!(d.cell(1, 0), "");
        assert!(d.delete_row(1));
        d.insert_col(1);
        assert_eq!(d.headers, vec!["a", "", "b"]);
        assert_eq!(d.cell(0, 2), "2");
        assert_eq!(d.col_count(), 3);
        assert!(d.delete_col(1));
        assert_eq!(d.headers, vec!["a", "b"]);
        assert_eq!(d.cell(1, 1), "4");
        assert!(!d.delete_col(9), "out of range refuses");
        let out = super::serialize_delimited(&d, b',', false, b"");
        assert_eq!(String::from_utf8(out).unwrap(), "a,b\n1,2\n3,4\n");
    }

    #[test]
    fn empty_sheet_grows_structure_that_survives_a_save_round_trip() {
        // #193 review: on a fully empty sheet, insert column + row, edit,
        // save, reopen - the body row must NOT be swallowed as the header.
        let mut d = super::parse_delimited(b"", b',', "S").unwrap();
        d.insert_col(0);
        assert_eq!(d.headers, vec![String::new()], "the header cell exists");
        d.insert_row(0);
        d.set_cell(0, 0, String::from("v"));
        let out = super::serialize_delimited(&d, b',', false, b"");
        let again = super::parse_delimited(&out, b',', "S").unwrap();
        assert_eq!(again.rows.len(), 1, "the body row survives the reopen");
        assert_eq!(again.cell(0, 0), "v");
    }

    #[test]
    fn tsv_round_trips_with_its_own_delimiter() {
        let mut d = super::parse_delimited(b"x\ty\n1\t2\n", b'\t', "S").unwrap();
        d.set_cell(0, 0, String::from("9"));
        let out = super::serialize_delimited(&d, b'\t', false, b"");
        assert_eq!(String::from_utf8(out).unwrap(), "x\ty\n9\t2\n");
    }

    use super::*;

    #[test]
    fn parse_csv_picks_up_header_and_rows() {
        let csv = b"name,age,city\nAlice,30,NYC\nBob,25,SFO\n";
        let s = parse_delimited(csv, b',', "Sheet1").unwrap();
        assert_eq!(s.headers, vec!["name", "age", "city"]);
        assert_eq!(s.rows.len(), 2);
        assert_eq!(s.rows[0], vec!["Alice", "30", "NYC"]);
        assert_eq!(s.col_widths.len(), 3);
        assert!(s.col_widths[0] >= "Alice".len() as u16);
    }

    #[test]
    fn parse_csv_handles_quoted_fields_with_embedded_commas() {
        let csv = b"a,b\n\"hello, world\",2\n";
        let s = parse_delimited(csv, b',', "Sheet1").unwrap();
        assert_eq!(s.rows[0], vec!["hello, world", "2"]);
    }

    #[test]
    fn parse_tsv_uses_tab_delimiter() {
        let tsv = b"col1\tcol2\nval1\tval2\n";
        let s = parse_delimited(tsv, b'\t', "Sheet1").unwrap();
        assert_eq!(s.headers, vec!["col1", "col2"]);
        assert_eq!(s.rows[0], vec!["val1", "val2"]);
    }

    #[test]
    fn parse_csv_tolerates_ragged_rows() {
        // Flexible mode: a short row doesn't kill the parse.
        let csv = b"a,b,c\nshort\nx,y,z\n";
        let s = parse_delimited(csv, b',', "Sheet1").unwrap();
        assert_eq!(s.rows.len(), 2);
        assert_eq!(s.rows[0], vec!["short"]);
        assert_eq!(s.rows[1], vec!["x", "y", "z"]);
    }

    #[test]
    fn col_widths_clamp_to_max() {
        let very_long: String = "x".repeat(200);
        let csv = format!("a,b\n{very_long},2\n");
        let s = parse_delimited(csv.as_bytes(), b',', "Sheet1").unwrap();
        assert_eq!(s.col_widths[0], MAX_COL_DISPLAY_W);
    }

    #[test]
    fn empty_csv_produces_empty_sheet() {
        let s = parse_delimited(b"", b',', "Sheet1").unwrap();
        assert!(s.headers.is_empty());
        assert!(s.rows.is_empty());
        assert!(s.col_widths.is_empty());
    }

    #[test]
    fn extension_classifier() {
        for ext in ["csv", "CSV", "tsv", "xlsx", "XLSX", "xls", "ods", "xlsb"] {
            assert!(extension_is_sheet(ext), "should accept: {ext}");
        }
        for ext in ["txt", "md", "rs", ""] {
            assert!(!extension_is_sheet(ext));
        }
    }
}