bigtext 0.14.0

Free editor for huge text and log files (1-50+ GB): opens them without loading them into memory, 4 GB/s search, atomic save
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
//! Table view for CSV / TSV documents.
//!
//! Virtualized like the text view: only the rows on screen are read (each bounded by the
//! segment length, see `bigtext::text::rows`) and only the visible columns are decoded. A row
//! is a line, so a quoted field that spans lines shows as several rows; the text itself is
//! never changed by the view.

use std::collections::BTreeSet;
use std::ops::Range;

use egui::{
    pos2, vec2, Align, Align2, Color32, CursorIcon, Event, EventFilter, FontId, Key, Layout,
    Painter, Rect, Sense, Stroke, Ui, UiBuilder,
};

use std::sync::{Arc, Mutex};

use bigtext::csv::{self, Dialect, DELIMITERS};
use bigtext::csv_rows::{self, RecordIndex};
use bigtext::jobs::CancelToken;
use bigtext::text::rows::{self, Pending, Row};
use bigtext::text::TextBuf;

use super::highlight::Lang;
use super::text_view;
use crate::app::document::Document;
use crate::app::i18n::{tr, trf as tr_f};

const SCROLLBAR: f32 = 14.0;
const TOOLBAR_H: f32 = 30.0;
/// Columns size themselves to their content up to this many characters; drag the border in
/// the header for more.
const MAX_AUTO_CHARS: usize = 40;
const MIN_CHARS: usize = 3;
/// Width of a column that has not been on screen yet, in characters.
const DEFAULT_CHARS: usize = 12;
const PAD: f32 = 6.0;

pub struct TableState {
    /// Detected from the file the first time the table is shown.
    pub dialect: Option<Dialect>,
    /// The first row holds the column names.
    pub header: bool,
    /// Column widths in points (0 = not measured yet). They grow to fit what has been on
    /// screen, except for columns whose border the user dragged (`fixed`).
    pub widths: Vec<f32>,
    pub fixed: Vec<bool>,
    pub scroll_x: f32,
    /// Selected columns: click a header; Ctrl+click adds or removes one, Shift+click a range.
    pub selected: BTreeSet<usize>,
    anchor: Option<usize>,
    /// Hash of the first line. When it changes (an edit, undo, another delimiter) the columns
    /// may have moved, so the layout and the selection start over.
    first_line: Option<u64>,
    /// Header cells drawn in the last frame (the self-test clicks them).
    pub header_cells: Vec<(usize, Rect)>,
    /// The rows drawn in the last frame as (gutter label, second cell), for the self-test.
    pub shown: Vec<(String, String)>,
    /// Lines before the table (`sep=;`, comments, a title); `dialect.start` is where it begins.
    pub skip: usize,
    /// Columns 0..frozen stay on the left while the others scroll.
    pub frozen: usize,
    /// Columns left out of the view (the file is not changed).
    pub hidden: BTreeSet<usize>,
    /// The layout remembered for the file, put back once its first line is read and the same.
    pub pending: Option<TableLayout>,
    /// The user changed the delimiter, the header switch or a width (the app saves it).
    pub layout_changed: bool,
    /// The layout was chosen (or put back), so it is worth remembering.
    custom: bool,
}

/// A table's layout as BigText remembers it for a file.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct TableLayout {
    pub delim: u8,
    pub header: bool,
    /// FNV-1a of the table's first line: when it changed, the columns may have moved.
    pub sig: u64,
    /// The widths of the columns whose border was dragged.
    pub fixed: Vec<(u16, f32)>,
    pub scroll_x: f32,
}

/// Dragged widths kept per file.
pub const LAYOUT_COLUMNS_MAX: usize = 64;

/// FNV-1a (stable across builds, unlike `DefaultHasher`).
pub fn fnv1a(b: &[u8]) -> u64 {
    b.iter().fold(0xcbf2_9ce4_8422_2325, |h, &x| {
        (h ^ x as u64).wrapping_mul(0x0000_0100_0000_01b3)
    })
}

impl Default for TableState {
    fn default() -> Self {
        TableState {
            dialect: None,
            header: true,
            widths: Vec::new(),
            fixed: Vec::new(),
            scroll_x: 0.0,
            selected: BTreeSet::new(),
            anchor: None,
            first_line: None,
            header_cells: Vec::new(),
            shown: Vec::new(),
            skip: 0,
            frozen: 0,
            hidden: BTreeSet::new(),
            pending: None,
            layout_changed: false,
            custom: false,
        }
    }
}

impl TableState {
    /// Forgets the column layout and the selection.
    pub fn reset_columns(&mut self) {
        self.widths.clear();
        self.fixed.clear();
        self.scroll_x = 0.0;
        self.selected.clear();
        self.anchor = None;
        self.frozen = 0;
        self.hidden.clear();
    }

    /// The layout to remember for the file: `None` while it is the detected one.
    pub fn layout(&self) -> Option<TableLayout> {
        if let Some(p) = &self.pending {
            return Some(p.clone());
        }
        let (d, sig) = (self.dialect?, self.first_line?);
        if !self.custom {
            return None;
        }
        let fixed = self
            .widths
            .iter()
            .zip(&self.fixed)
            .enumerate()
            .filter(|(_, (_, &f))| f)
            .map(|(c, (&w, _))| (c as u16, w))
            .take(LAYOUT_COLUMNS_MAX)
            .collect();
        Some(TableLayout {
            delim: d.delim,
            header: self.header,
            sig,
            fixed,
            scroll_x: self.scroll_x,
        })
    }

    /// Splits the columns at `delim` instead (the toolbar's Delimiter).
    pub fn set_delim(&mut self, delim: u8) {
        let cur = self.dialect.unwrap_or(Dialect::new(b','));
        self.dialect = Some(Dialect { delim, ..cur });
        self.reset_columns();
        self.changed();
    }

    /// The user changed the layout.
    fn changed(&mut self) {
        self.custom = true;
        self.layout_changed = true;
    }

    /// After the header was edited on purpose (a rename): keep the layout.
    pub fn keep_layout(&mut self) {
        self.first_line = None;
    }

    /// After columns `a` and `b` were exchanged in the document: their widths go with them.
    pub fn columns_swapped(&mut self, a: usize, b: usize) {
        if a.max(b) < self.widths.len() {
            self.widths.swap(a, b);
            self.fixed.swap(a, b);
        }
        self.selected.clear();
        self.selected.insert(b);
        self.anchor = Some(b);
        self.first_line = None;
        let (ha, hb) = (self.hidden.remove(&a), self.hidden.remove(&b));
        if ha {
            self.hidden.insert(b);
        }
        if hb {
            self.hidden.insert(a);
        }
    }

    /// After `cols` were deleted from the document: the other columns keep their widths.
    pub fn columns_deleted(&mut self, cols: &[usize]) {
        for &c in cols.iter().rev() {
            if c < self.widths.len() {
                self.widths.remove(c);
                self.fixed.remove(c);
            }
        }
        self.selected.clear();
        self.anchor = None;
        // The first line changed on purpose; take the new one as it is.
        self.first_line = None;
        let gone = |c: usize| cols.iter().filter(|&&d| d < c).count();
        self.hidden = self
            .hidden
            .iter()
            .filter(|c| !cols.contains(c))
            .map(|&c| c - gone(c))
            .collect();
        self.frozen -= gone(self.frozen);
    }

    fn click_header(&mut self, col: usize, m: egui::Modifiers) {
        match self.anchor {
            Some(a) if m.shift => {
                if !m.command {
                    self.selected.clear();
                }
                self.selected.extend(a.min(col)..=a.max(col));
            }
            _ if m.command => {
                if !self.selected.remove(&col) {
                    self.selected.insert(col);
                }
                self.anchor = Some(col);
            }
            _ => {
                let only = self.selected.len() == 1 && self.selected.contains(&col);
                self.selected.clear();
                if !only {
                    self.selected.insert(col);
                }
                self.anchor = Some(col);
            }
        }
    }
}

pub enum TableAction {
    /// Delete these columns (sorted) with their values from every row, after asking.
    DeleteColumns {
        cols: Vec<usize>,
        names: Vec<String>,
    },
    Sort {
        col: usize,
        desc: bool,
    },
    Stats {
        col: usize,
    },
    Filter {
        col: usize,
        name: String,
    },
    Rename {
        col: usize,
        name: String,
    },
    /// Exchange column `col` with its neighbour.
    Move {
        col: usize,
        right: bool,
    },
    /// Write these columns (sorted) to a new file.
    Export {
        cols: Vec<usize>,
    },
    /// Write these columns (all when `None`) as JSON, JSON Lines, Markdown or Excel.
    ExportAs {
        cols: Option<Vec<usize>>,
        format: bigtext::table_export::Format,
    },
    /// Count (and sum) the rows per value of this column.
    GroupBy {
        col: usize,
    },
    /// Rows that meet several conditions, starting with one on this column.
    Conditions {
        col: usize,
    },
    /// Check every row (field counts, quotes, numbers).
    CheckRows,
    /// A pivot table with this column's values as rows.
    Pivot {
        col: usize,
    },
    /// Compare with another table by this column as the key.
    CompareBy {
        col: usize,
    },
    /// A new last column computed by an expression.
    AddColumn,
    /// The distribution of a column's values, under the table.
    Chart {
        col: usize,
    },
    /// Keep columns 0..upto on the left (0: none).
    Freeze {
        upto: usize,
    },
    /// Leave these columns out of the view.
    Hide {
        cols: Vec<usize>,
    },
}

pub struct TableEnv<'a> {
    pub font_size: &'a mut f32,
    pub focus: bool,
    /// Row numbers on the left.
    pub show_gutter: bool,
    pub actions: &'a mut Vec<TableAction>,
}

/// One visible row split into fields.
struct Line {
    row: Row,
    /// Document offset of `bytes[0]` (after the BOM on the first line).
    base: u64,
    bytes: Vec<u8>,
    fields: Vec<Range<usize>>,
}

impl Line {
    fn value(&self, codec: &bigtext::encoding::Codec, d: Dialect, col: usize) -> Option<String> {
        let r = self.fields.get(col)?;
        Some(display(&csv::field_value(codec, d, &self.bytes[r.clone()])))
    }

    /// Index of the field holding document offset `off`.
    fn field_at(&self, off: u64) -> Option<usize> {
        let rel = off.checked_sub(self.base)? as usize;
        self.fields
            .iter()
            .position(|r| rel >= r.start && rel <= r.end)
    }
}

/// Control characters (tabs, line breaks inside quotes) show as spaces.
fn display(s: &str) -> String {
    s.chars()
        .map(|c| if c.is_control() { ' ' } else { c })
        .collect()
}

fn is_number(s: &str) -> bool {
    let t = s.trim();
    t.bytes().any(|b| b.is_ascii_digit())
        && t.bytes()
            .all(|b| b.is_ascii_digit() || b"+-.eE".contains(&b))
        && t.parse::<f64>().is_ok()
}

fn read_line(doc: &Document, d: Dialect, row: Row) -> Option<Line> {
    let base = row.start.max(doc.min_caret());
    let bytes = doc.buf.read(base..row.end.max(base))?.to_vec();
    let mut fields = Vec::new();
    csv::split_fields(&doc.buf.codec, d, &bytes, &mut fields);
    Some(Line {
        row,
        base,
        bytes,
        fields,
    })
}

fn detect_dialect(doc: &mut Document) {
    if !doc.is_ready() {
        return;
    }
    let start = doc.min_caret();
    let end = (start + 64 * 1024).min(doc.buf.len());
    // Not loaded yet (slow drive): try again on the next frame.
    let Some(sample) = doc.buf.read(start..end) else {
        return;
    };
    let preferred = match doc.effective_lang() {
        Lang::Csv(sep) => sep,
        _ => b',',
    };
    let g = csv::detect_table(
        &doc.buf.codec,
        &sample,
        end == doc.buf.len(),
        preferred,
        start,
    );
    let st = &mut doc.table_state;
    st.dialect = Some(g.dialect);
    st.header = g.header;
    st.skip = g.skip;
}

/// Starts the table after `skip` lines (from the menu), keeping the delimiter and quote.
fn set_skip(doc: &mut Document, skip: usize) {
    let Some(mut d) = doc.table_state.dialect else {
        return;
    };
    let start = doc.min_caret();
    let Some(sample) = doc.buf.read(start..(start + (1 << 20)).min(doc.buf.len())) else {
        return;
    };
    let codec = doc.buf.codec;
    let unit = codec.unit();
    let mut at = 0;
    for _ in 0..skip {
        match codec.find_nl(&sample[at..], start + at as u64) {
            Some(i) => at += i + unit,
            None => {
                at = sample.len();
                break;
            }
        }
    }
    d.start = if skip == 0 { 0 } else { start + at as u64 };
    let st = &mut doc.table_state;
    st.dialect = Some(d);
    st.skip = skip;
    st.reset_columns();
}

/// The record index being read for a document shown as a table (`App::records_tick` starts it).
pub struct RecordsJob {
    pub version: u64,
    pub dialect: Dialect,
    pub data: Arc<Mutex<Arc<RecordIndex>>>,
    pub cancel: CancelToken,
}

/// The record index of `doc` when it is current and some record spans lines; otherwise the
/// rows are lines, as they always were.
fn record_index(doc: &Document) -> Option<Arc<RecordIndex>> {
    let r = doc.records.as_ref()?;
    if r.version != doc.version || Some(r.dialect) != doc.table_state.dialect {
        return None;
    }
    let idx = r.data.lock().unwrap().clone();
    idx.multiline.then_some(idx)
}

/// The table's rows: whole records where the record index has been read (a quoted field may
/// hold line breaks), lines elsewhere.
struct TableRows<'a> {
    buf: &'a TextBuf,
    idx: Option<&'a RecordIndex>,
}

fn table_rows<'a>(buf: &'a TextBuf, idx: &'a Option<Arc<RecordIndex>>) -> TableRows<'a> {
    TableRows {
        buf,
        idx: idx.as_deref(),
    }
}

impl TableRows<'_> {
    fn rec(&self, p: u64) -> Option<&RecordIndex> {
        self.idx.filter(|i| i.covers(p))
    }

    fn row_at(&self, off: u64) -> Result<Row, Pending> {
        match self.rec(off) {
            Some(i) => csv_rows::row_at(self.buf, i, off),
            None => rows::row_at(self.buf, off, None),
        }
    }

    fn next_row(&self, r: &Row) -> Result<Option<Row>, Pending> {
        match self.rec(r.start) {
            Some(i) if r.seg.has_nl || i.covers(r.seg.next) => csv_rows::next_row(self.buf, i, r),
            _ => rows::next_row(self.buf, r, None),
        }
    }

    fn prev_row(&self, r: &Row) -> Result<Option<Row>, Pending> {
        match self.idx {
            Some(i) if r.start > i.first && i.covers(r.start - 1) => {
                csv_rows::prev_row(self.buf, i, r)
            }
            _ => rows::prev_row(self.buf, r, None),
        }
    }

    /// Moves `n` rows down (positive) or up; stops at the document's edges.
    fn step_rows(&self, row: Row, n: i64) -> Result<Row, Pending> {
        let mut r = row;
        for _ in 0..n.unsigned_abs() {
            let next = if n > 0 {
                self.next_row(&r)?
            } else {
                self.prev_row(&r)?
            };
            match next {
                Some(x) => r = x,
                None => break,
            }
        }
        Ok(r)
    }

    /// The `n` rows shown from `top`.
    fn layout(&self, top: u64, n: usize) -> Result<Vec<Row>, Pending> {
        let mut v = Vec::with_capacity(n + 1);
        v.push(self.row_at(top)?);
        while v.len() < n {
            match self.next_row(v.last().unwrap())? {
                Some(r) => v.push(r),
                None => break,
            }
        }
        Ok(v)
    }
}

/// Puts back the layout remembered for the file when its first line is still the one it was
/// saved with; otherwise the columns may have moved, and it is dropped.
fn apply_pending(doc: &mut Document) {
    let Some(d) = doc.table_state.dialect else {
        return;
    };
    let start = d.first(&doc.buf).max(doc.min_caret());
    let idx = record_index(doc);
    let Ok(head) = table_rows(&doc.buf, &idx).row_at(start) else {
        return;
    };
    let Some(first) = doc.buf.read(head.start..head.end) else {
        return;
    };
    let Some(p) = doc.table_state.pending.take() else {
        return;
    };
    let sig = fnv1a(&first);
    if p.sig != sig {
        return;
    }
    let st = &mut doc.table_state;
    st.reset_columns();
    st.dialect = Some(Dialect {
        delim: p.delim,
        ..d
    });
    st.header = p.header;
    for &(c, w) in p.fixed.iter().take(LAYOUT_COLUMNS_MAX) {
        let c = c as usize;
        if st.widths.len() <= c {
            st.widths.resize(c + 1, 0.0);
            st.fixed.resize(c + 1, false);
        }
        st.widths[c] = w;
        st.fixed[c] = true;
    }
    st.scroll_x = p.scroll_x;
    st.first_line = Some(sig);
    st.custom = true;
}

/// Moves the first visible row by `n` rows.
fn step(doc: &mut Document, n: i64) {
    let idx = record_index(doc);
    let tr = table_rows(&doc.buf, &idx);
    if let Ok(top) = tr.row_at(doc.view.top) {
        if let Ok(r) = tr.step_rows(top, n) {
            doc.view.top = r.start;
        }
    }
}

pub fn show(ui: &mut Ui, doc: &mut Document, env: &mut TableEnv) {
    let font = FontId::monospace(*env.font_size / ui.ctx().zoom_factor());
    let (cw, fh) = ui
        .ctx()
        .fonts_mut(|f| (f.glyph_width(&font, 'M'), f.row_height(&font)));
    let cw = cw.max(1.0);
    let rh = (fh + 8.0).round();
    let full = ui.available_rect_before_wrap();
    let id = ui.id().with(("tableview", doc.id));
    let visuals = ui.visuals().clone();
    if doc.table_state.dialect.is_none() {
        detect_dialect(doc);
    }
    if doc.table_state.pending.is_some() {
        apply_pending(doc);
    }
    let dialect = doc.table_state.dialect.unwrap_or(Dialect::new(b','));
    let codec = doc.buf.codec;
    let len = doc.buf.len();

    let toolbar_rect = Rect::from_min_max(full.min, pos2(full.right(), full.top() + TOOLBAR_H));
    let area = Rect::from_min_max(pos2(full.left(), toolbar_rect.bottom()), full.max);
    let (line_est, _) = doc.buf.line_count();
    let gutter_w = if env.show_gutter {
        text_view::digits(line_est).max(3) as f32 * cw + 16.0
    } else {
        0.0
    };
    let header_rect = Rect::from_min_max(
        pos2(area.left() + gutter_w, area.top()),
        pos2(area.right() - SCROLLBAR, area.top() + rh),
    );
    let body = Rect::from_min_max(
        pos2(header_rect.left(), header_rect.bottom()),
        pos2(header_rect.right(), area.bottom() - SCROLLBAR),
    );
    let gutter = Rect::from_min_max(area.min, pos2(header_rect.left(), body.bottom()));
    let vbar = Rect::from_min_max(
        pos2(body.right(), area.top()),
        pos2(area.right(), body.bottom()),
    );
    let hbar = Rect::from_min_max(
        pos2(body.left(), body.bottom()),
        pos2(body.right(), area.bottom()),
    );
    let n_rows = ((body.height() / rh).ceil() as usize).max(1);

    let mut pending = false;
    let table_start = dialect.first(&doc.buf).max(doc.min_caret());
    let rec_idx = record_index(doc);
    let head = match table_rows(&doc.buf, &rec_idx).row_at(table_start) {
        Ok(r) => Some(r),
        Err(Pending) => {
            pending = true;
            None
        }
    };
    let data_start = match (doc.table_state.header, head) {
        (true, Some(h)) if h.seg.is_last(len) => len,
        (true, Some(h)) => h.seg.next,
        _ => table_start,
    };
    if let Some(first) = head.and_then(|h| doc.buf.read(h.start..h.end)) {
        let sig = Some(fnv1a(&first));
        let st = &mut doc.table_state;
        if st.first_line.is_some() && st.first_line != sig {
            let scroll_x = st.scroll_x;
            st.reset_columns();
            st.scroll_x = scroll_x;
        }
        st.first_line = sig;
    }

    // Input, against the current layout.
    let resp = ui.interact(body, id, Sense::click_and_drag());
    if env.focus
        && (resp.clicked()
            || resp.is_pointer_button_down_on()
            || ui.memory(|m| m.focused().is_none()))
    {
        resp.request_focus();
    }
    ui.memory_mut(|m| {
        m.set_focus_lock_filter(
            id,
            EventFilter {
                tab: false,
                horizontal_arrows: true,
                vertical_arrows: true,
                escape: false,
            },
        )
    });
    let mut delete_key = false;
    if doc.is_ready() {
        if ui.rect_contains_pointer(area) {
            handle_wheel(ui, doc, rh, env);
        }
        if resp.has_focus() {
            delete_key = handle_keys(ui, doc, n_rows, data_start, cw);
        }
        if doc.view.scroll_to_caret || doc.view.center_caret {
            match scroll_to_caret(doc, n_rows) {
                Ok(()) => {
                    doc.view.scroll_to_caret = false;
                    doc.view.center_caret = false;
                }
                Err(Pending) => pending = true,
            }
        }
        doc.view.top = doc.view.top.max(data_start);
        // Never scroll past the last row (an empty line after the final line break is not one).
        if len > 0 && doc.view.top >= len && data_start < len {
            if let Ok(r) = table_rows(&doc.buf, &rec_idx).row_at(len - 1) {
                doc.view.top = r.start.max(data_start);
            }
        }
    }

    // Rows on screen.
    let rows: Vec<Row> = if doc.is_ready() && doc.view.top < len {
        match table_rows(&doc.buf, &rec_idx).layout(doc.view.top, n_rows) {
            Ok(r) => r.into_iter().filter(|r| r.start < len).collect(),
            Err(Pending) => {
                pending = true;
                Vec::new()
            }
        }
    } else {
        Vec::new()
    };
    let mut lines = Vec::with_capacity(rows.len());
    for &row in &rows {
        match read_line(doc, dialect, row) {
            Some(l) => lines.push(l),
            None => {
                pending = true;
                break;
            }
        }
    }
    let head_line = if doc.table_state.header {
        head.and_then(|h| read_line(doc, dialect, h))
    } else {
        None
    };

    // Columns: measure the visible ones, then lay out.
    let ncols = lines
        .iter()
        .chain(head_line.as_ref())
        .map(|l| l.fields.len())
        .max()
        .unwrap_or(0)
        .max(doc.table_state.widths.len());
    let st = &mut doc.table_state;
    st.widths.resize(ncols, 0.0);
    st.fixed.resize(ncols, false);
    let default_w = (DEFAULT_CHARS as f32 + 1.0) * cw + 2.0 * PAD;
    let name = |col: usize| -> String {
        match &head_line {
            Some(h) => h
                .value(&codec, dialect, col)
                .filter(|s| !s.trim().is_empty())
                .unwrap_or_else(|| format!("({})", col + 1)),
            None => tr_f("Column {n}", &[("n", &(col + 1).to_string())]),
        }
    };
    st.hidden.retain(|&c| c < ncols);
    let measure: Vec<usize> =
        visible_columns(&st.widths, default_w, st.scroll_x, body.width()).collect();
    for col in measure {
        if st.fixed[col] || st.hidden.contains(&col) {
            continue;
        }
        let chars = lines
            .iter()
            .filter_map(|l| l.value(&codec, dialect, col))
            .map(|v| v.chars().count())
            .chain([name(col).chars().count() + 1])
            .max()
            .unwrap_or(0);
        let want = (chars.clamp(MIN_CHARS, MAX_AUTO_CHARS) as f32 + 1.0) * cw + 2.0 * PAD;
        st.widths[col] = st.widths[col].max(want);
    }
    let width = |st: &TableState, col: usize| {
        if st.widths[col] > 0.0 {
            st.widths[col]
        } else {
            default_w
        }
    };
    let shown_w = |st: &TableState, col: usize| {
        if st.hidden.contains(&col) {
            0.0
        } else {
            width(st, col)
        }
    };
    let mut xs = Vec::with_capacity(ncols + 1);
    xs.push(0.0f32);
    for col in 0..ncols {
        xs.push(xs[col] + shown_w(st, col));
    }
    // Frozen columns, at most two thirds of the width.
    let mut frozen = st.frozen.min(ncols);
    while frozen > 0 && xs[frozen] > body.width() * 0.66 {
        frozen -= 1;
    }
    let strip = xs[frozen];
    let total = xs[ncols];
    let max_scroll = (total - body.width() + 2.0 * cw).max(0.0);
    st.scroll_x = st.scroll_x.clamp(0.0, max_scroll);
    let scroll_x = st.scroll_x;
    let shift = |col: usize| if col < frozen { 0.0 } else { scroll_x };
    // Left and right edges of a column on screen; frozen columns do not scroll.
    let left = |col: usize| body.left() + xs[col] - shift(col);
    let right = |col: usize| body.left() + xs[col + 1] - shift(col);
    let split = body.left() + strip;
    // The part of `r` a column may paint in: the frozen strip, or right of it.
    let clip_of = |col: usize, r: Rect| {
        if col < frozen {
            Rect::from_min_max(r.min, pos2(r.right().min(split), r.bottom()))
        } else {
            Rect::from_min_max(pos2(r.left().max(split), r.top()), r.max)
        }
    };
    let visible: Vec<usize> = (0..ncols)
        .filter(|&c| {
            !st.hidden.contains(&c) && (c < frozen || (right(c) > split && left(c) < body.right()))
        })
        .collect();
    st.selected.retain(|&c| c < ncols);
    let selected = st.selected.clone();

    // Toolbar (it may ask to delete the selected columns), and the Delete key.
    ui.painter()
        .rect_filled(toolbar_rect, 0.0, visuals.faint_bg_color);
    let can_delete = !selected.is_empty() && selected.len() < ncols && doc.editable();
    let request = toolbar(ui, doc, toolbar_rect, ncols, can_delete) || (delete_key && can_delete);
    if request {
        let cols: Vec<usize> = selected.iter().copied().collect();
        let names = cols.iter().map(|&c| name(c)).collect();
        env.actions.push(TableAction::DeleteColumns { cols, names });
    }

    // Paint.
    let painter = ui.painter_at(area);
    let grid = visuals.widgets.noninteractive.bg_stroke.color;
    let zebra = if visuals.dark_mode {
        Color32::from_white_alpha(6)
    } else {
        Color32::from_black_alpha(8)
    };
    let text_color = visuals.text_color();
    let weak = visuals.weak_text_color();
    painter.rect_filled(area, 0.0, visuals.extreme_bg_color);
    painter.rect_filled(gutter, 0.0, visuals.faint_bg_color);
    painter.rect_filled(
        header_rect.union(Rect::from_min_max(
            pos2(gutter.left(), header_rect.top()),
            header_rect.max,
        )),
        0.0,
        visuals.faint_bg_color,
    );
    let body_painter = painter.with_clip_rect(body);
    let sel_tint = visuals.selection.bg_fill.gamma_multiply(0.35);
    for &col in visible.iter().filter(|c| selected.contains(c)) {
        let r = Rect::from_min_max(
            pos2(left(col), body.top()),
            pos2(right(col), body.top() + lines.len() as f32 * rh),
        );
        body_painter
            .with_clip_rect(clip_of(col, body))
            .rect_filled(r, 0.0, sel_tint);
    }
    let caret = doc.view.caret;
    let (mut line, line_exact) = lines
        .first()
        .map(|l| doc.buf.line_of(l.row.start))
        .unwrap_or((0, true));
    // Line breaks inside the rows since the last row that started a line (a record whose
    // quoted fields hold line breaks covers several lines).
    let mut inner = 0;
    let mut shown = Vec::with_capacity(lines.len());
    for (i, l) in lines.iter().enumerate() {
        let y = body.top() + i as f32 * rh;
        let row_rect = Rect::from_min_max(pos2(body.left(), y), pos2(body.right(), y + rh));
        let starts_line = l.row.is_first_in_seg() && l.row.seg.line_start;
        if i > 0 && starts_line {
            line += 1 + inner;
            inner = 0;
        }
        if rec_idx.is_some() {
            inner += codec.count_nl(&l.bytes, l.base);
        }
        if i % 2 == 1 {
            body_painter.rect_filled(row_rect, 0.0, zebra);
        }
        for &col in &visible {
            let Some(v) = l.value(&codec, dialect, col) else {
                continue;
            };
            let cell = Rect::from_min_max(pos2(left(col), y), pos2(right(col), y + rh));
            paint_text(
                &body_painter.with_clip_rect(clip_of(col, cell.intersect(body))),
                cell,
                &v,
                &font,
                text_color,
                cw,
                is_number(&v),
            );
        }
        if caret >= l.row.start && caret <= l.row.end.max(l.row.start) {
            if let Some(col) = l.field_at(caret) {
                let cell =
                    Rect::from_min_max(pos2(left(col), y), pos2(right(col), y + rh)).shrink(1.0);
                body_painter.with_clip_rect(clip_of(col, body)).rect_stroke(
                    cell,
                    2.0,
                    Stroke::new(1.5, visuals.selection.stroke.color),
                    egui::StrokeKind::Inside,
                );
            }
        }
        let label = match (starts_line, line_exact, l.row.seg.line_start) {
            (true, true, _) => format!("{}", line + 1),
            (true, false, _) => format!("~{}", line + 1),
            (false, _, false) if l.row.is_first_in_seg() => "↪".into(),
            _ => String::new(),
        };
        shown.push((
            label.clone(),
            l.value(&codec, dialect, 1).unwrap_or_default(),
        ));
        painter.text(
            pos2(gutter.right() - 8.0, y + rh / 2.0),
            Align2::RIGHT_CENTER,
            label,
            font.clone(),
            weak,
        );
        body_painter.hline(body.x_range(), y + rh, Stroke::new(0.5, grid));
    }
    doc.table_state.shown = shown;
    for &col in &visible {
        let x = right(col);
        painter
            .with_clip_rect(clip_of(col, header_rect.union(body)).expand2(vec2(1.0, 0.0)))
            .vline(
                x,
                header_rect.top()..=body.top() + lines.len() as f32 * rh,
                Stroke::new(1.0, grid),
            );
    }
    painter.hline(
        gutter.left()..=header_rect.right(),
        header_rect.bottom(),
        Stroke::new(1.0, grid),
    );
    painter.text(
        pos2(gutter.right() - 8.0, header_rect.center().y),
        Align2::RIGHT_CENTER,
        "#",
        font.clone(),
        weak,
    );

    // Header cells: names, selection, tooltips and resize handles.
    let header_painter = painter.with_clip_rect(header_rect);
    let strong = visuals.strong_text_color();
    let mut header_cells = Vec::with_capacity(visible.len());
    for &col in &visible {
        let cell = Rect::from_min_max(
            pos2(left(col), header_rect.top()),
            pos2(right(col), header_rect.bottom()),
        );
        let on = selected.contains(&col);
        if on {
            header_painter.rect_filled(
                cell.shrink2(vec2(0.5, 0.0)),
                0.0,
                visuals.selection.bg_fill,
            );
        }
        let n = name(col);
        let color = if on {
            visuals.selection.stroke.color
        } else {
            strong
        };
        let hit = clip_of(col, cell.intersect(header_rect));
        paint_text(
            &header_painter.with_clip_rect(hit),
            cell,
            &n,
            &font,
            color,
            cw,
            false,
        );
        let r = ui.interact(hit, id.with(("head", col)), Sense::click());
        r.widget_info(|| {
            egui::WidgetInfo::selected(egui::WidgetType::SelectableLabel, true, on, &n)
        });
        if r.clicked() {
            let m = ui.input(|i| i.modifiers);
            doc.table_state.click_header(col, m);
            resp.request_focus();
        }
        let editable = doc.editable();
        // The menu acts on the selected columns when it opens on one of them.
        r.context_menu(|ui| {
            let cols: Vec<usize> = if selected.contains(&col) {
                selected.iter().copied().collect()
            } else {
                vec![col]
            };
            let names: Vec<String> = cols.iter().map(|&c| name(c)).collect();
            column_menu(ui, env.actions, col, &n, ncols, cols, names, editable);
            ui.separator();
            let unfreeze = frozen == col + 1;
            if ui
                .button(tr(if unfreeze {
                    "Unfreeze columns"
                } else {
                    "Freeze columns up to here"
                }))
                .clicked()
            {
                env.actions.push(TableAction::Freeze {
                    upto: if unfreeze { 0 } else { col + 1 },
                });
                ui.close();
            }
            if ui.button(tr("Hide from the view")).clicked() {
                let cols: Vec<usize> = if selected.contains(&col) {
                    selected.iter().copied().collect()
                } else {
                    vec![col]
                };
                env.actions.push(TableAction::Hide { cols });
                ui.close();
            }
        });
        r.on_hover_text(format!(
            "{n}\n{}\n{}",
            tr_f("Column {n}", &[("n", &(col + 1).to_string())]),
            tr("Click to select; Ctrl+click adds, Shift+click selects a range; right-click for more")
        ));
        header_cells.push((col, hit));
    }
    doc.table_state.header_cells = header_cells;
    for &col in &visible {
        let x = right(col);
        let handle = Rect::from_min_max(
            pos2(x - 4.0, header_rect.top()),
            pos2(x + 4.0, header_rect.bottom()),
        );
        if !header_rect.intersects(handle) {
            continue;
        }
        let r = ui.interact(handle, id.with(("resize", col)), Sense::click_and_drag());
        if r.hovered() || r.dragged() {
            ui.ctx().set_cursor_icon(CursorIcon::ResizeColumn);
        }
        let st = &mut doc.table_state;
        if r.dragged() {
            st.widths[col] = (width(st, col) + r.drag_delta().x).max((MIN_CHARS as f32 + 1.0) * cw);
            st.fixed[col] = true;
        }
        if r.double_clicked() {
            // Back to fitting the content.
            st.widths[col] = 0.0;
            st.fixed[col] = false;
        }
        if r.drag_stopped() || r.double_clicked() {
            st.changed();
        }
    }

    // Clicks in the body: a click puts the caret in the cell, a double click opens it in the
    // text view.
    if let Some(pos) = resp
        .interact_pointer_pos()
        .filter(|_| resp.clicked() || resp.double_clicked())
    {
        let double = resp.double_clicked();
        let i = ((pos.y - body.top()) / rh).floor().max(0.0) as usize;
        let col = visible
            .iter()
            .copied()
            .find(|&c| pos.x >= left(c) && pos.x < right(c) && (c < frozen || pos.x >= split));
        if let (Some(l), Some(col)) = (lines.get(i), col) {
            let off = l
                .fields
                .get(col)
                .map(|r| l.base + r.start as u64)
                .unwrap_or(l.row.end);
            doc.set_caret(off, false);
            doc.view.desired_cell = None;
            if double {
                doc.table = false;
                doc.view.center();
            } else {
                doc.view.scroll_to_caret = false;
            }
        }
    }

    doc.view.text_rect = Some(body);
    doc.view.cell = vec2(cw, rh);
    if doc.view.first_paint.is_none() && !lines.is_empty() {
        doc.view.first_paint = Some(std::time::Instant::now());
    }
    if lines.is_empty() && !pending && doc.is_ready() {
        let msg = tr(if len == 0 {
            "Empty file"
        } else {
            "No data rows"
        });
        painter.text(
            body.center(),
            Align2::CENTER_CENTER,
            msg,
            FontId::proportional(16.0),
            weak,
        );
    }
    if pending {
        painter.text(
            body.right_top() + vec2(-8.0, 4.0),
            Align2::RIGHT_TOP,
            tr("Loading…"),
            FontId::proportional(13.0),
            weak,
        );
        ui.ctx()
            .request_repaint_after(std::time::Duration::from_millis(30));
    }

    if doc.is_ready() {
        text_view::vertical_scrollbar(ui, doc, id, vbar, &rows, None);
        horizontal_scrollbar(ui, doc, id, hbar, total, body.width(), max_scroll);
    }
}

/// Right-click menu of a column header.
#[allow(clippy::too_many_arguments)]
fn column_menu(
    ui: &mut Ui,
    actions: &mut Vec<TableAction>,
    col: usize,
    name: &str,
    ncols: usize,
    cols: Vec<usize>,
    names: Vec<String>,
    editable: bool,
) {
    let mut act = |ui: &mut Ui, enabled: bool, label: &str, a: TableAction| {
        if ui.add_enabled(enabled, egui::Button::new(label)).clicked() {
            actions.push(a);
            ui.close();
        }
    };
    act(
        ui,
        editable,
        tr("Sort ascending (A → Z, 1 → 9)"),
        TableAction::Sort { col, desc: false },
    );
    act(
        ui,
        editable,
        tr("Sort descending (Z → A, 9 → 1)"),
        TableAction::Sort { col, desc: true },
    );
    ui.separator();
    act(ui, true, tr("Statistics…"), TableAction::Stats { col });
    act(ui, true, tr("Chart…"), TableAction::Chart { col });
    act(
        ui,
        true,
        tr("Filter rows by this column…"),
        TableAction::Filter {
            col,
            name: name.to_string(),
        },
    );
    act(
        ui,
        true,
        tr("Filter rows by conditions…"),
        TableAction::Conditions { col },
    );
    act(
        ui,
        true,
        tr("Group rows by this column…"),
        TableAction::GroupBy { col },
    );
    act(
        ui,
        true,
        tr("Pivot by this column…"),
        TableAction::Pivot { col },
    );
    act(
        ui,
        true,
        tr("Compare table by this column…"),
        TableAction::CompareBy { col },
    );
    act(ui, true, tr("Check rows…"), TableAction::CheckRows);
    ui.separator();
    act(
        ui,
        editable,
        tr("Rename…"),
        TableAction::Rename {
            col,
            name: name.to_string(),
        },
    );
    act(ui, editable, tr("Add column…"), TableAction::AddColumn);
    act(
        ui,
        editable && col > 0,
        tr("Move left"),
        TableAction::Move { col, right: false },
    );
    act(
        ui,
        editable && col + 1 < ncols,
        tr("Move right"),
        TableAction::Move { col, right: true },
    );
    ui.separator();
    let label = if cols.len() == 1 {
        tr("Export this column")
    } else {
        tr("Export selected columns")
    };
    ui.menu_button(label, |ui| {
        act(ui, true, "CSV…", TableAction::Export { cols: cols.clone() });
        for format in bigtext::table_export::Format::ALL {
            act(
                ui,
                true,
                &format!("{}…", tr(format.name())),
                TableAction::ExportAs {
                    cols: Some(cols.clone()),
                    format,
                },
            );
        }
    });
    act(
        ui,
        editable && cols.len() < ncols,
        tr("Delete…"),
        TableAction::DeleteColumns { names, cols },
    );
}

/// Columns that overlap the visible width.
fn visible_columns(
    widths: &[f32],
    default_w: f32,
    scroll_x: f32,
    view_w: f32,
) -> impl Iterator<Item = usize> + '_ {
    let mut x = 0.0f32;
    widths.iter().enumerate().filter_map(move |(col, &w)| {
        let w = if w > 0.0 { w } else { default_w };
        let (a, b) = (x, x + w);
        x = b;
        (b > scroll_x && a < scroll_x + view_w).then_some(col)
    })
}

/// Draws `text` in `cell`, cut to fit with an ellipsis; numbers align right.
#[allow(clippy::too_many_arguments)]
fn paint_text(
    painter: &Painter,
    cell: Rect,
    text: &str,
    font: &FontId,
    color: Color32,
    cw: f32,
    right: bool,
) {
    let max = ((cell.width() - 2.0 * PAD) / cw).floor().max(1.0) as usize;
    let shown: String = if text.chars().count() > max {
        text.chars()
            .take(max.saturating_sub(1))
            .chain(['…'])
            .collect()
    } else {
        text.to_string()
    };
    if shown.is_empty() {
        return;
    }
    crate::app::fonts::note_missing(painter.ctx(), font, &shown);
    let y = cell.center().y;
    if right {
        painter.text(
            pos2(cell.right() - PAD, y),
            Align2::RIGHT_CENTER,
            shown,
            font.clone(),
            color,
        );
    } else {
        painter.text(
            pos2(cell.left() + PAD, y),
            Align2::LEFT_CENTER,
            shown,
            font.clone(),
            color,
        );
    }
}

/// Delimiter, header switch, column selection. Returns true when "Delete columns" was clicked.
fn toolbar(ui: &mut Ui, doc: &mut Document, rect: Rect, ncols: usize, can_delete: bool) -> bool {
    let doc_id = doc.id;
    let read_only = doc.read_only;
    let mut delete = false;
    let mut set_skip_later = None;
    ui.scope_builder(
        UiBuilder::new()
            .max_rect(rect.shrink2(vec2(8.0, 3.0)))
            .layout(Layout::left_to_right(Align::Center)),
        |ui| {
            let st = &mut doc.table_state;
            let cur = st.dialect.unwrap_or(Dialect::new(b','));
            ui.label(tr("Delimiter"));
            egui::ComboBox::from_id_salt(("delimiter", doc_id))
                .selected_text(tr(cur.name()))
                .show_ui(ui, |ui| {
                    for delim in DELIMITERS {
                        if ui
                            .selectable_label(cur.delim == delim, tr(Dialect::new(delim).name()))
                            .clicked()
                            && cur.delim != delim
                        {
                            st.set_delim(delim);
                        }
                    }
                });
            if ui
                .checkbox(&mut st.header, tr("First row is header"))
                .changed()
            {
                st.changed();
            }
            let mut skip = st.skip;
            ui.menu_button(tr("Table…"), |ui| {
                ui.horizontal(|ui| {
                    ui.label(tr("Skip lines before the table"));
                    ui.add(egui::DragValue::new(&mut skip).range(0..=1000));
                });
                ui.horizontal(|ui| {
                    ui.label(tr("Quote"));
                    for (q, name) in [(b'"', "\""), (b'\'', "'")] {
                        if ui.selectable_label(cur.quote == q, name).clicked() && cur.quote != q {
                            st.dialect = Some(Dialect { quote: q, ..cur });
                            st.reset_columns();
                        }
                    }
                });
            });
            if skip != st.skip {
                set_skip_later = Some(skip);
            }
            if !st.hidden.is_empty()
                && ui
                    .button(tr_f(
                        "{n} hidden · Show all",
                        &[("n", &st.hidden.len().to_string())],
                    ))
                    .on_hover_text(tr("Show the columns hidden from the view"))
                    .clicked()
            {
                st.hidden.clear();
            }
            ui.separator();
            if st.selected.is_empty() {
                ui.weak(tr_f(
                    "{n} columns · click a column header to select it",
                    &[("n", &ncols.to_string())],
                ));
            } else {
                let n = st.selected.len();
                ui.label(tr_f(
                    "{n} of {total} columns selected",
                    &[("n", &n.to_string()), ("total", &ncols.to_string())],
                ));
                let label = tr(if n == 1 {
                    "Delete column"
                } else {
                    "Delete columns"
                });
                let tip = tr(if read_only {
                    "The document is read-only"
                } else if n >= ncols {
                    "Keep at least one column"
                } else {
                    "Delete the selected columns and their values from every row (Delete key)"
                });
                let button = egui::Button::new(
                    egui::RichText::new(label).color(ui.visuals().error_fg_color),
                );
                if ui
                    .add_enabled(can_delete, button)
                    .on_hover_text(tip)
                    .on_disabled_hover_text(tip)
                    .clicked()
                {
                    delete = true;
                }
                if ui
                    .button(tr("Clear selection"))
                    .on_hover_text("Esc")
                    .clicked()
                {
                    st.selected.clear();
                }
            }
            ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
                if ui
                    .button(tr("Text view"))
                    .on_hover_text(tr("Show the file as text (Ctrl+T)"))
                    .clicked()
                {
                    doc.table = false;
                }
            });
        },
    );
    if let Some(skip) = set_skip_later {
        set_skip(doc, skip);
    }
    delete
}

fn handle_wheel(ui: &mut Ui, doc: &mut Document, rh: f32, env: &mut TableEnv) {
    let (delta, zoom) = ui.input(|i| (i.smooth_scroll_delta(), i.zoom_delta()));
    if zoom != 1.0 {
        *env.font_size = (*env.font_size * zoom).clamp(6.0, 72.0);
        return;
    }
    if delta.y != 0.0 {
        let rows_f = -delta.y / rh + doc.view.wheel_rem;
        let n = rows_f.trunc() as i64;
        doc.view.wheel_rem = rows_f - n as f32;
        if n != 0 {
            step(doc, n);
        }
    }
    if delta.x != 0.0 {
        doc.table_state.scroll_x = (doc.table_state.scroll_x - delta.x).max(0.0);
    }
}

/// Scrolling, undo / redo and the column selection keys. Returns true for Delete.
fn handle_keys(ui: &mut Ui, doc: &mut Document, n_rows: usize, data_start: u64, cw: f32) -> bool {
    let page = n_rows.saturating_sub(2).max(1) as i64;
    let events = ui.input(|i| i.events.clone());
    let mut delete = false;
    for ev in events {
        let Event::Key {
            key,
            pressed: true,
            modifiers,
            ..
        } = ev
        else {
            continue;
        };
        match key {
            Key::Z if modifiers.command && modifiers.shift => doc.redo(),
            Key::Z if modifiers.command => doc.undo(),
            Key::Y if modifiers.command => doc.redo(),
            Key::Delete => delete = true,
            Key::Escape => doc.table_state.selected.clear(),
            Key::ArrowDown => step(doc, 1),
            Key::ArrowUp => step(doc, -1),
            Key::PageDown => step(doc, page),
            Key::PageUp => step(doc, -page),
            Key::ArrowRight => doc.table_state.scroll_x += 8.0 * cw,
            Key::ArrowLeft => {
                doc.table_state.scroll_x = (doc.table_state.scroll_x - 8.0 * cw).max(0.0)
            }
            Key::Home if modifiers.command => {
                doc.view.top = data_start;
                doc.table_state.scroll_x = 0.0;
            }
            Key::End if modifiers.command => {
                let len = doc.buf.len();
                let idx = record_index(doc);
                let tr = table_rows(&doc.buf, &idx);
                if let Ok(last) = tr.row_at(len.saturating_sub(1)) {
                    if let Ok(r) = tr.step_rows(last, -page) {
                        doc.view.top = r.start;
                    }
                }
            }
            Key::Home => doc.table_state.scroll_x = 0.0,
            Key::End => doc.table_state.scroll_x = f32::MAX,
            _ => {}
        }
    }
    delete
}

/// Brings the row with the caret on screen (after go to line, find next, a click elsewhere).
fn scroll_to_caret(doc: &mut Document, n_rows: usize) -> Result<(), Pending> {
    let idx = record_index(doc);
    let tr = table_rows(&doc.buf, &idx);
    let row = tr.row_at(doc.view.caret)?;
    let top = doc.view.top;
    let on_screen = row.start >= top && {
        let shown = tr.layout(top, n_rows.saturating_sub(1).max(1))?;
        shown.iter().any(|r| r.start == row.start)
    };
    if doc.view.center_caret || !on_screen {
        let back = if doc.view.center_caret || row.start < top {
            (n_rows / 2) as i64
        } else {
            n_rows.saturating_sub(2) as i64
        };
        doc.view.top = tr.step_rows(row, -back)?.start;
    }
    Ok(())
}

fn horizontal_scrollbar(
    ui: &mut Ui,
    doc: &mut Document,
    id: egui::Id,
    bar: Rect,
    content: f32,
    view_w: f32,
    max_scroll: f32,
) {
    let painter = ui.painter_at(bar);
    let v = ui.visuals();
    painter.rect_filled(bar, 0.0, v.faint_bg_color);
    if max_scroll <= 0.0 {
        return;
    }
    let st = &mut doc.table_state;
    let track_w = bar.width();
    let thumb_w = (track_w * view_w / content.max(1.0)).clamp(24.0_f32.min(track_w), track_w);
    let x = bar.left() + (track_w - thumb_w) * (st.scroll_x / max_scroll).clamp(0.0, 1.0);
    let thumb = Rect::from_min_max(
        pos2(x, bar.top() + 2.0),
        pos2(x + thumb_w, bar.bottom() - 2.0),
    );
    let r = ui.interact(bar, id.with("hbar"), Sense::click_and_drag());
    let color = if r.dragged() || r.hovered() {
        v.widgets.hovered.bg_fill
    } else {
        v.widgets.inactive.bg_fill
    };
    painter.rect_filled(thumb, 4.0, color);
    if r.dragged() || r.is_pointer_button_down_on() {
        if let Some(p) = r.interact_pointer_pos() {
            let f =
                ((p.x - bar.left() - thumb_w / 2.0) / (track_w - thumb_w).max(1.0)).clamp(0.0, 1.0);
            st.scroll_x = f * max_scroll;
        }
    }
}