bigtext 0.7.3

Fast text editor for huge files (1-50+ GB): opens instantly, never freezes, streaming search/replace and 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
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
//! Custom virtualized text view.
//!
//! Only the rows on screen are read and decoded, and of each row only the horizontal slice that
//! is visible. Rows come from [`bigtext::text::rows`], so every computation is bounded no matter
//! how long a line is. All positions are byte offsets; nothing here touches the whole file.

use std::collections::HashMap;
use std::ops::Range;

use egui::text::{CCursor, LayoutJob, TextFormat};
use egui::{pos2, Align2, Color32, CursorIcon, Event, EventFilter, FontId, Key, Modifiers, PointerButton, Pos2, Rect, Sense, Ui};

use bigtext::text::rows::{self, CellKind, Pending, Row};
use bigtext::text::TextBuf;

use super::block::{block_rows, block_text, edit_block, Block, BlockEdit};
use crate::app::theme::{role, Tone};
use crate::app::document::Document;

const SCROLLBAR: f32 = 14.0;
/// Selections up to this size are copied synchronously; larger ones go through a worker.
pub const SYNC_COPY_MAX: u64 = 4 * 1024 * 1024;

pub enum ViewAction {
    /// Copy (or cut) a selection too large for the UI thread.
    CopyLarge { cut: bool, len: u64 },
    /// Esc with nothing to collapse (it leaves zen mode).
    Escape,
}

/// Ranges to paint behind the text, with their colours.
pub type Highlights = Vec<(u64, u64, Color32)>;

pub struct ViewEnv<'a> {
    pub font_size: &'a mut f32,
    /// Returns ranges to highlight within the given (visible) range, with their colours, in
    /// painting order.
    pub highlight: &'a dyn Fn(&TextBuf, Range<u64>) -> Highlights,
    pub actions: &'a mut Vec<ViewAction>,
    pub focus: bool,
    /// Syntax highlighting for the visible rows.
    pub lang: super::highlight::Lang,
    /// Which split pane this is (0 = primary).
    pub pane: u8,
    /// Spaces, tabs and line breaks shown as `·`, `→` and `↓` / `↵` / `←`.
    pub show_ws: ShowWs,
    /// Line numbers in the gutter.
    pub show_gutter: bool,
    /// View → Wrap at: a fixed column (`None`: the pane's width).
    pub wrap_column: Option<usize>,
    /// View → Ruler at column.
    pub ruler: Option<usize>,
    /// The lines a comparison marks in this pane (side by side).
    pub diff: Option<DiffOverlay<'a>>,
}

/// One pane's side of a comparison: its removed (A) or added (B) lines.
pub struct DiffOverlay<'a> {
    /// The marked line ranges within the given (visible) range; an empty range marks where the
    /// other side has lines this one lacks.
    pub spans: &'a dyn Fn(Range<u64>) -> Vec<Range<u64>>,
    pub added: bool,
}

/// View → Show whitespace, kept apart for code (where the indentation shows as guides) and for
/// other text.
#[derive(Clone, Copy, Default)]
pub struct ShowWs {
    pub text: bool,
    pub code: bool,
}

impl ShowWs {
    pub fn for_lang(self, lang: super::highlight::Lang) -> bool {
        if lang.is_code() {
            self.code
        } else {
            self.text
        }
    }
}

/// What an input method is composing (Chinese pinyin before it becomes characters). It is
/// drawn at the caret; only the text the input method commits goes into the document.
#[derive(Clone, Default)]
pub struct Preedit {
    pub text: String,
    /// The input method's cursor in `text` (characters; `None`: at the end).
    pub cursor: Option<usize>,
    /// The caret it is composed at; moving the caret ends the composition.
    pub at: u64,
}

/// A cluster (a character with its combining marks) painted apart from the rest of its row, on
/// its own cells: one not as wide as its cells (a Chinese character from a fallback font, an
/// emoji), which inline would push the text after it away from the cells the caret and the
/// selection are drawn at.
struct Loose {
    /// Where its cells are (as spaces) in the row's painted text.
    at: usize,
    cell: u32,
    width: u32,
    /// Painted on its own, never with alike neighbours: several characters (the shaper might
    /// space them apart), or right-to-left ones (it would turn them around).
    alone: bool,
    text: String,
    /// How far it advances as egui draws it.
    adv: f32,
}

/// Rows of code are this much taller than the font's line, as in code editors.
const CODE_LINE_SPACING: f32 = 1.2;

#[derive(Clone, Copy)]
struct Metrics {
    cw: f32,
    rh: f32,
    /// Space above the text in a row (rows of code are taller than the text).
    pad: f32,
}

/// The colours of the text area: the theme's, or a code editor's for code.
struct Look {
    bg: Color32,
    gutter: Color32,
    fg: Color32,
    line_no: Color32,
    line_no_active: Color32,
    cur_line: Color32,
    guide: Color32,
    caret: Color32,
    /// Code colours on a dark background (the code theme can differ from the interface's).
    dark: bool,
    /// Tokens take the code theme's colours.
    code: bool,
}

impl Look {
    fn new(v: &egui::Visuals, code: bool) -> Look {
        if code && !crate::app::theme::high_contrast_on() {
            let c = crate::app::theme::code_colors(v.dark_mode);
            return Look { bg: c.bg, gutter: c.bg, fg: c.fg, line_no: c.line_no, line_no_active: c.line_no_active, cur_line: c.cur_line, guide: c.guide, caret: c.caret, dark: c.dark, code: true };
        }
        let weak = v.weak_text_color();
        Look {
            bg: v.extreme_bg_color,
            gutter: v.faint_bg_color,
            fg: v.text_color(),
            line_no: weak,
            line_no_active: v.text_color(),
            cur_line: if v.dark_mode { Color32::from_white_alpha(8) } else { Color32::from_black_alpha(10) },
            guide: weak.gamma_multiply(0.4),
            caret: v.text_cursor.stroke.color,
            dark: v.dark_mode,
            code: false,
        }
    }

    /// The colour of a token.
    fn token(&self, k: super::highlight::Kind) -> Color32 {
        let plain = crate::app::theme::cvd() || crate::app::theme::high_contrast_on();
        self.code.then(|| crate::app::theme::code_token(k, self.dark)).flatten().filter(|_| !plain).unwrap_or_else(|| super::highlight::color(k, self.dark))
    }
}

/// The width rows wrap at (`None`: not wrapping): the column of View → Wrap at, or the pane's.
pub(crate) fn wrap_cols(view: &crate::app::document::ViewState) -> Option<usize> {
    view.wrap.then(|| view.wrap_column.unwrap_or(view.text_cols.saturating_sub(1)).max(1))
}

/// Rows scroll sideways: not wrapping, or wrapping wider than the pane.
fn h_scroll(view: &crate::app::document::ViewState) -> bool {
    wrap_cols(view).is_none_or(|w| w >= view.text_cols)
}

pub(crate) fn layout_rows(buf: &TextBuf, top: u64, n: usize, wrap: Option<usize>) -> Result<Vec<Row>, Pending> {
    layout_rows_folded(buf, top, n, wrap, &[])
}

/// The `n` rows shown from `top`, folded lines left out.
pub(crate) fn layout_rows_folded(buf: &TextBuf, top: u64, n: usize, wrap: Option<usize>, folds: &[super::folds::Fold]) -> Result<Vec<Row>, Pending> {
    let mut v = Vec::with_capacity(n + 1);
    v.push(rows::row_at(buf, top, wrap)?);
    while v.len() < n {
        match super::folds::next_row(buf, v.last().unwrap(), wrap, folds)? {
            Some(r) => v.push(r),
            None => break,
        }
    }
    Ok(v)
}

pub(crate) fn digits(n: u64) -> usize {
    n.max(1).ilog10() as usize + 1
}

pub fn show(ui: &mut Ui, doc: &mut Document, env: &mut ViewEnv) {
    let code = env.lang.is_code();
    let show_ws = env.show_ws.for_lang(env.lang);
    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 fh = fh.max(1.0);
    let rh = if code { (fh * CODE_LINE_SPACING).round() } else { fh };
    let m = Metrics { cw: cw.max(1.0), rh, pad: ((rh - fh) / 2.0).round() };

    let full = ui.available_rect_before_wrap();
    let id = ui.id().with(("textview", doc.id, env.pane));
    let resp = ui.interact(full, id, Sense::click_and_drag());
    if env.focus && (resp.clicked() || resp.drag_started() || resp.is_pointer_button_down_on() || (env.pane == doc.active_pane && ui.memory(|mem| mem.focused().is_none()))) {
        resp.request_focus();
    }
    if resp.is_pointer_button_down_on() || resp.has_focus() {
        doc.active_pane = env.pane;
    }
    let active_pane = doc.active_pane == env.pane;
    ui.memory_mut(|mem| {
        mem.set_focus_lock_filter(id, EventFilter { tab: true, horizontal_arrows: true, vertical_arrows: true, escape: false })
    });
    let focused = resp.has_focus();
    if resp.hovered() {
        ui.ctx().set_cursor_icon(CursorIcon::Text);
    }

    let (line_est, _) = doc.buf.line_count();
    // Without line numbers a strip stays for the bookmark marks.
    let gutter_w = if env.show_gutter { digits(line_est).max(3) as f32 * m.cw + 24.0 } else { 6.0 };
    doc.view.wrap_column = env.wrap_column;
    let pane_cols = ((full.width() - gutter_w - 6.0 - SCROLLBAR) / m.cw).floor().max(4.0) as usize;
    let show_h = !doc.view.wrap || env.wrap_column.is_some_and(|c| c >= pane_cols);
    if !show_h {
        doc.view.scroll_x = 0.0;
    }
    let text_rect = Rect::from_min_max(
        pos2(full.left() + gutter_w + 6.0, full.top()),
        pos2(full.right() - SCROLLBAR, full.bottom() - if show_h { SCROLLBAR } else { 0.0 }),
    );
    let gutter_rect = Rect::from_min_max(full.min, pos2(full.left() + gutter_w, text_rect.bottom()));
    let vbar = Rect::from_min_max(pos2(text_rect.right(), full.top()), pos2(full.right(), text_rect.bottom()));
    let hbar = Rect::from_min_max(pos2(text_rect.left(), text_rect.bottom()), pos2(text_rect.right(), full.bottom()));
    doc.view.text_rect = Some(text_rect);
    doc.view.cell = egui::vec2(m.cw, m.rh);
    doc.view.rows_on_screen = ((text_rect.height() / m.rh).floor() as usize).max(1);
    doc.view.text_cols = ((text_rect.width() / m.cw).floor() as usize).max(4);
    let wrap = wrap_cols(&doc.view);
    // Folds are for the text they were made on; the caret and the top are never hidden.
    if !doc.view.folds.is_empty() {
        if doc.view.folds_version != doc.version {
            doc.view.folds.clear();
        }
        let caret = doc.view.caret;
        doc.view.folds.retain(|f| !(f.hide_from <= caret && caret < f.end));
        if let Some(f) = super::folds::hidden_by(&doc.view.folds, doc.view.top) {
            doc.view.top = f.start;
        }
    }
    if doc.view.width_cache_version != doc.version {
        doc.view.width_cache.clear();
        doc.view.width_cache_version = doc.version;
    }
    // A block selection needs rows that are lines, and rows that still start where they did.
    if let Some(b) = doc.view.block {
        let stale = |at: u64| !matches!(rows::row_at(&doc.buf, at.min(doc.buf.len()), None), Ok(r) if r.start == at);
        if wrap.is_some() || !doc.is_ready() || stale(b.anchor) || stale(b.caret) || !doc.view.folds.is_empty() {
            doc.view.block = None;
            doc.view.block_drag = false;
        }
    }

    if doc.view.extra_version != doc.version {
        doc.view.extra.clear();
    }
    let mut pending = false;
    if doc.is_ready() {
        // Input is handled against the current layout, then the layout is rebuilt for painting.
        if let Ok(rows) = layout_rows_folded(&doc.buf, doc.view.top, doc.view.rows_on_screen + 1, wrap, &doc.view.folds) {
            handle_wheel(ui, doc, &resp, m, wrap, env);
            handle_mouse(ui, doc, &resp, text_rect, m, wrap, &rows, active_pane);
            epoch_tooltip(ui, doc, &resp, text_rect, m, &rows);
            if focused {
                handle_keys(ui, doc, wrap, env);
            }
        } else {
            pending = true;
        }
        if active_pane && (doc.view.scroll_to_caret || doc.view.center_caret) {
            let center = doc.view.center_caret;
            if ensure_caret_visible(doc, wrap, center, m, text_rect.width()).is_ok() {
                doc.view.scroll_to_caret = false;
                doc.view.center_caret = false;
            } else {
                pending = true;
            }
        }
    }
    // Moving the caret (a click, a key) or the focus ends a composition.
    let interrupt = active_pane && !doc.view.preedit.text.is_empty() && (!focused || resp.gained_focus() || doc.view.preedit.at != doc.view.caret);
    if interrupt {
        doc.view.preedit = Preedit::default();
    }

    let painter = ui.painter_at(full);
    let visuals = ui.visuals().clone();
    let look = Look::new(&visuals, code);
    let unit = if code && doc.is_ready() { indent_unit(doc) } else { 4 };
    painter.rect_filled(full, 0.0, look.bg);
    painter.rect_filled(gutter_rect, 0.0, look.gutter);

    let rows = if doc.is_ready() {
        match layout_rows_folded(&doc.buf, doc.view.top, doc.view.rows_on_screen + 1, wrap, &doc.view.folds) {
            Ok(r) => r,
            Err(Pending) => {
                pending = true;
                Vec::new()
            }
        }
    } else {
        Vec::new()
    };
    if let Some(first) = rows.first() {
        doc.view.top = first.start;
    }

    let text_color = look.fg;
    let weak = visuals.weak_text_color();
    let sel_color = visuals.selection.bg_fill;
    let cur_line_bg = look.cur_line;

    let first_cell = (doc.view.scroll_x / m.cw).floor().max(0.0) as u32;
    let vis_cells = doc.view.text_cols as u32 + 2;
    let x_of = |cell: u32| text_rect.left() + cell as f32 * m.cw - doc.view.scroll_x;
    let text_painter = painter.with_clip_rect(text_rect);
    // Indent guides go under everything else drawn on the text; they are known after the rows.
    let guide_slot = text_painter.add(egui::Shape::Noop);
    // The indentation of each row (`None`: blank, or not known), for the guides.
    let mut indents: Vec<Option<u32>> = Vec::new();
    let mut line_indent: Option<u32> = None;
    let (sel_s, sel_e) = doc.selection();
    let caret = doc.view.caret;
    let has_caret = |row: &Row| caret >= row.start && (caret < row.end || (caret == row.end && (row.is_last_in_seg() || row.end == doc.buf.len())));
    // The row with the caret's line number.
    let caret_label = rows.iter().position(has_caret).map(|mut k| {
        while k > 0 && !(rows[k].is_first_in_seg() && rows[k].seg.line_start) {
            k -= 1;
        }
        k
    });
    let extra = doc.view.extra.clone();
    let highlights = match (rows.first(), rows.last()) {
        (Some(a), Some(b)) => (env.highlight)(&doc.buf, a.start..b.seg.next.max(b.end)),
        _ => Vec::new(),
    };
    let diff_spans = match (&env.diff, rows.first(), rows.last()) {
        (Some(o), Some(a), Some(b)) => (o.spans)(a.start..b.seg.next.max(b.end)),
        _ => Vec::new(),
    };
    let hl_states = super::hl_rows::row_states(&mut doc.view.hl, &doc.buf, doc.version, env.lang, &rows);
    let stateful = env.lang.stateful();
    let diff_color = match env.diff.as_ref().map(|o| o.added) {
        Some(true) => role(Color32::from_rgba_unmultiplied(70, 190, 90, if visuals.dark_mode { 40 } else { 55 }), Tone::Ok, visuals.dark_mode),
        _ => role(Color32::from_rgba_unmultiplied(230, 70, 70, if visuals.dark_mode { 40 } else { 50 }), Tone::Bad, visuals.dark_mode),
    };

    let (mut line, line_exact) = rows.first().map(|r| doc.buf.line_of(r.start)).unwrap_or((0, true));
    let mut max_w = doc.view.max_cells;
    // Folds whose chip was clicked.
    let mut unfold: Vec<u64> = Vec::new();
    // Screen readers get the rows on screen as text runs.
    let a11y_on = super::a11y::enabled(ui.ctx(), id);
    let mut a11y_rows: Vec<super::a11y::Row> = Vec::new();
    let ctx = ui.ctx().clone();
    // How far the clusters met so far in this frame advance (see `advance`).
    let mut advances: HashMap<String, f32> = HashMap::new();
    // Where the caret was drawn, for the input method's window.
    let mut caret_rect: Option<Rect> = None;
    for (i, row) in rows.iter().enumerate() {
        let y = text_rect.top() + i as f32 * m.rh;
        if y > text_rect.bottom() {
            break;
        }
        let starts_line = row.is_first_in_seg() && row.seg.line_start;
        if i > 0 && starts_line {
            // After a fold the line number jumps.
            line = if doc.view.folds.binary_search_by_key(&row.start, |f| f.end).is_ok() { doc.buf.line_of(row.start).0 } else { line + 1 };
        }
        let Some(bytes) = doc.buf.read(row.start..row.end) else {
            pending = true;
            break;
        };

        // Visible slice of the row.
        let codec = doc.buf.codec;
        let mut job = LayoutJob::default();
        let mut vis: Vec<(u64, u32)> = Vec::new();
        let mut cur = first_cell;
        let mut reached_end = true;
        let mut end_cell = 0u32;
        // Visible text of the row plus the byte ranges of placeholder (special) glyphs.
        let mut run = String::new();
        let mut specials: Vec<(usize, usize)> = Vec::new();
        // The same characters as they are in the file (a tab, not `→   `), for highlighting, with
        // where each starts in `src` and in `run`; and the part of the row left of the screen.
        let mut src = String::new();
        let mut map: Vec<(usize, usize)> = Vec::new();
        let mut pre = String::new();
        let mut a11y_row = a11y_on.then(|| super::a11y::Row::new(row.start, row.end, Rect::from_min_max(pos2(text_rect.left(), y), pos2(text_rect.right(), y + m.rh))));
        let mut loose: Vec<Loose> = Vec::new();
        // The visible characters.
        let mut cells: Vec<rows::Cell> = Vec::new();
        // The cell the row's text starts in (`None`: blank so far).
        let mut ink: Option<u32> = None;
        rows::for_each_cell(&codec, &bytes, row.start, |c| {
            if ink.is_none() && !matches!(c.kind, CellKind::Tab | CellKind::Hidden) && !(c.kind == CellKind::Normal && c.ch == ' ') {
                ink = Some(c.cell);
            }
            end_cell = c.cell + c.width;
            if c.cell + c.width <= first_cell {
                if stateful && c.kind != CellKind::Hidden {
                    pre.push(c.ch);
                }
                return true;
            }
            // A zero-width character right of the screen still goes on the one before it.
            if c.cell >= first_cell + vis_cells && c.width > 0 {
                reached_end = false;
                return false;
            }
            cells.push(c);
            true
        });
        // A letter with its accents or vowel signs, an emoji sequence: each cluster is shaped
        // as one and fills its cells.
        let starts = cluster_starts(&cells);
        for (k, &i) in starts.iter().enumerate() {
            let group = &cells[i..starts.get(k + 1).copied().unwrap_or(cells.len())];
            let c = group[0];
            let width: u32 = group.iter().map(|x| x.width).sum();
            for x in group {
                vis.push((x.off, x.cell));
                if let Some(r) = a11y_row.as_mut().filter(|_| x.kind != CellKind::Hidden) {
                    let ch = match x.kind {
                        CellKind::Tab => '\t',
                        CellKind::Invalid => '\u{FFFD}',
                        _ => x.ch,
                    };
                    r.push(ch, x.off, (x.cell.max(first_cell) - first_cell) as f32 * m.cw, x.width as f32 * m.cw);
                }
            }
            if c.cell > cur {
                for _ in cur..c.cell {
                    run.push(' ');
                }
            }
            let shown = (c.cell + width).saturating_sub(c.cell.max(first_cell)) as usize;
            let at = run.len();
            let mut whole = false;
            let (s, sp): (String, bool) = match c.kind {
                CellKind::Normal if group.len() > 1 || !c.ch.is_ascii() => {
                    let text: String = group.iter().map(|x| x.ch).collect();
                    let adv = match advances.get(text.as_str()) {
                        Some(&a) => a,
                        None => {
                            // A script no loaded font has: a system font for it is looked for.
                            crate::app::fonts::note_missing(&ctx, &font, &text);
                            *advances.entry(text.clone()).or_insert(advance(&ctx, &font, &text))
                        }
                    };
                    let rtl = is_rtl(c.ch);
                    // Not as wide as its cells (a Chinese character from a fallback font, an
                    // accent the font lacks), cut by the left edge, or right-to-left (which the
                    // shaper would turn around with the text near it): painted apart.
                    if (adv - width as f32 * m.cw).abs() > 0.05 || c.cell < first_cell || rtl {
                        loose.push(Loose { at, cell: c.cell, width, alone: group.len() > 1 || rtl, text, adv });
                        (" ".repeat(shown), false)
                    } else {
                        whole = true;
                        (text, false)
                    }
                }
                CellKind::Tab if show_ws => {
                    let w = shown;
                    (if c.cell >= first_cell { format!("→{}", " ".repeat(w - 1)) } else { " ".repeat(w) }, true)
                }
                CellKind::Tab => (" ".repeat(shown), false),
                CellKind::Normal if show_ws && c.ch == ' ' => ("·".to_string(), true),
                CellKind::Hidden => (String::new(), false),
                CellKind::Control => (control_glyph(c.ch).to_string(), true),
                CellKind::Invalid => ('\u{FFFD}'.to_string(), true),
                CellKind::Normal => (c.ch.to_string(), false),
            };
            if sp {
                specials.push((at, at + s.len()));
            }
            // Highlighting sees every character; a cluster painted apart takes its first one's
            // colour.
            let mut r = at;
            for (n, x) in group.iter().enumerate().filter(|(_, x)| x.kind != CellKind::Hidden) {
                if n == 0 || whole {
                    map.push((src.len(), r));
                }
                src.push(x.ch);
                r += if whole { x.ch.len_utf8() } else { 0 };
            }
            run.push_str(&s);
            cur = c.cell.max(first_cell) + width;
        }
        let st = hl_states.get(i).copied().unwrap_or_default();
        let st = if pre.is_empty() { st } else { super::highlight::scan(env.lang, st, &pre, false) };
        let text = Shown { run: &run, specials: &specials, src: &src, map: &map };
        build_job(&mut job, &text, env.lang, st, &font, text_color, weak, &look);
        if code {
            // A wrapped row goes on with its line's indentation.
            let indent = if starts_line {
                line_indent = match ink {
                    Some(n) => Some(n),
                    // The empty row after the last line break ends every block.
                    None if row.start == doc.buf.len() => Some(0),
                    None if reached_end => None,
                    None => Some(first_cell + vis_cells),
                };
                line_indent
            } else {
                line_indent
            };
            indents.push(indent);
        }
        if let Some(mut r) = a11y_row.take() {
            if reached_end && row.is_last_in_seg() && row.seg.has_nl {
                r.push('\n', row.end, (end_cell.max(first_cell) - first_cell) as f32 * m.cw, 0.0);
            }
            a11y_rows.push(r);
        }

        // Row width for the horizontal scrollbar (cached; rows are bounded so this is cheap).
        if show_h {
            let w = if reached_end {
                end_cell
            } else {
                *doc.view.width_cache.entry(row.start).or_insert_with(|| rows::cell_width(&codec, &bytes, row.start))
            };
            max_w = max_w.max(w);
        }

        let cell_for = |off: u64| -> u32 {
            if off <= row.start {
                return 0;
            }
            match vis.iter().find(|(o, _)| *o >= off) {
                Some(&(_, c)) => c,
                None => {
                    if reached_end {
                        end_cell
                    } else {
                        first_cell + vis_cells
                    }
                }
            }
        };
        let row_has_caret = has_caret(row);
        let in_diff = diff_spans.iter().any(|s| s.start <= row.start && row.start < s.end);
        if in_diff {
            text_painter.rect_filled(Rect::from_min_max(pos2(text_rect.left(), y), pos2(text_rect.right(), y + m.rh)), 0.0, diff_color);
        } else if starts_line && diff_spans.iter().any(|s| s.is_empty() && s.start == row.start) {
            text_painter.hline(text_rect.x_range(), y + 0.5, egui::Stroke::new(2.0, diff_color.to_opaque()));
        }
        if row_has_caret && focused && sel_s == sel_e {
            text_painter.rect_filled(Rect::from_min_max(pos2(text_rect.left(), y), pos2(text_rect.right(), y + m.rh)), 0.0, cur_line_bg);
        }
        for &(hs, he, color) in &highlights {
            if he > row.start && hs < row.end || (hs == he && hs >= row.start && hs < row.end) {
                let x0 = x_of(cell_for(hs.max(row.start)));
                let x1 = x_of(cell_for(he.min(row.end))).max(x0 + 2.0);
                text_painter.rect_filled(Rect::from_min_max(pos2(x0, y), pos2(x1, y + m.rh)), 2.0, color);
            }
        }
        if let Some(b) = doc.view.block.filter(|b| b.contains_row(row.start)) {
            let (lo, hi) = b.cells();
            let x0 = text_rect.left() + lo as f32 * m.cw - doc.view.scroll_x;
            let x1 = text_rect.left() + hi as f32 * m.cw - doc.view.scroll_x;
            let r = Rect::from_min_max(pos2(x0 - if lo == hi { 0.5 } else { 0.0 }, y), pos2(if lo == hi { x0 + 1.5 } else { x1 }, y + m.rh));
            text_painter.rect_filled(r, 0.0, if lo == hi { look.caret } else { sel_color });
        }
        if sel_s < sel_e && sel_e > row.start && sel_s <= row.end {
            let x0 = x_of(cell_for(sel_s.max(row.start)));
            let mut x1 = x_of(cell_for(sel_e.min(row.end)));
            if sel_e > row.end && row.is_last_in_seg() && (row.seg.has_nl || !row.seg.line_start) {
                x1 += m.cw * 0.5;
            }
            if x1 > x0 {
                text_painter.rect_filled(Rect::from_min_max(pos2(x0, y), pos2(x1, y + m.rh)), 0.0, sel_color);
            }
        }
        for &(a, c) in &extra {
            let (s, e) = (a.min(c), a.max(c));
            if s < e && e > row.start && s <= row.end {
                let (x0, x1) = (x_of(cell_for(s.max(row.start))), x_of(cell_for(e.min(row.end))));
                if x1 > x0 {
                    text_painter.rect_filled(Rect::from_min_max(pos2(x0, y), pos2(x1, y + m.rh)), 0.0, sel_color);
                }
            }
        }
        if !job.text.is_empty() {
            let loose_jobs = loose_jobs(&loose, &job, &font, m.cw, fh);
            let galley = ui.ctx().fonts_mut(|f| f.layout_job(job));
            text_painter.galley(pos2(x_of(first_cell), y + m.pad), galley, text_color);
            for (cell, d, job) in loose_jobs {
                let galley = ui.ctx().fonts_mut(|f| f.layout_job(job));
                text_painter.galley(pos2(x_of(cell), y + m.pad) + d, galley, text_color);
            }
        }
        // The line break: LF, CRLF or CR.
        if show_ws && reached_end && row.is_last_in_seg() && row.seg.has_nl {
            let glyph = if row.seg.next - row.seg.content_end >= 2 * codec.unit() as u64 {
                "↵"
            } else if codec.nl == bigtext::encoding::NlByte::Cr {
                "←"
            } else {
                "↓"
            };
            text_painter.text(pos2(x_of(end_cell), y + m.pad), Align2::LEFT_TOP, glyph, font.clone(), weak);
        }
        if row_has_caret {
            let mut x = x_of(cell_for(caret));
            let preedit = &doc.view.preedit;
            if focused && active_pane && !preedit.text.is_empty() {
                // The composition goes over the text after the caret, underlined, with the
                // caret where the input method has it.
                let galley = ui.ctx().fonts_mut(|f| f.layout_no_wrap(preedit.text.clone(), font.clone(), text_color));
                let under = Rect::from_min_max(pos2(x, y), pos2(x + galley.size().x, y + m.rh));
                text_painter.rect_filled(under, 0.0, look.bg);
                if sel_s == sel_e {
                    text_painter.rect_filled(under, 0.0, cur_line_bg);
                }
                text_painter.hline(under.x_range(), text_painter.round_to_pixel_center(y + m.rh - 1.5), egui::Stroke::new(1.0, text_color));
                let n = preedit.cursor.unwrap_or(usize::MAX).min(preedit.text.chars().count());
                let dx = galley.pos_from_cursor(CCursor::new(n)).min.x;
                text_painter.galley(pos2(x, y + m.pad), galley, text_color);
                x += dx;
            }
            let color = if focused { look.caret } else { weak };
            text_painter.rect_filled(Rect::from_min_max(pos2(x - 0.5, y), pos2(x + 1.5, y + m.rh)), 0.0, color);
            caret_rect = Some(Rect::from_min_max(pos2(x, y), pos2(x + 1.0, y + m.rh)));
        }
        for &(_, c) in &extra {
            if c >= row.start && (c < row.end || (c == row.end && (row.is_last_in_seg() || row.end == doc.buf.len()))) {
                let x = x_of(cell_for(c));
                let color = if focused { look.caret } else { weak };
                text_painter.rect_filled(Rect::from_min_max(pos2(x - 0.5, y), pos2(x + 1.5, y + m.rh)), 0.0, color);
            }
        }

        let label = if starts_line {
            if line_exact {
                format!("{}", line + 1)
            } else {
                format!("~{}", line + 1)
            }
        } else if row.is_first_in_seg() && !row.seg.line_start {
            // A 64 KB piece of a huge line.
            "↪".to_string()
        } else {
            String::new()
        };
        if !label.is_empty() && env.show_gutter {
            let color = if caret_label == Some(i) { look.line_no_active } else { look.line_no };
            painter.text(pos2(gutter_rect.right() - 8.0, y + m.pad), Align2::RIGHT_TOP, label, font.clone(), color);
        } else if !row.is_first_in_seg() && env.show_gutter {
            // A wrapped row: a dim mark, so the line numbers stay readable.
            painter.text(pos2(gutter_rect.right() - 8.0, y + m.pad), Align2::RIGHT_TOP, "·", font.clone(), look.line_no.gamma_multiply(0.5));
        }
        if in_diff && starts_line && env.show_gutter {
            let glyph = if env.diff.as_ref().is_some_and(|o| o.added) { "+" } else { "−" };
            painter.text(pos2(gutter_rect.left() + 2.0, y + m.pad), Align2::LEFT_TOP, glyph, font.clone(), diff_color.to_opaque());
        }
        // A folded value: ▸ in the gutter, "… N lines …" after its opening line.
        if let Some(f) = super::folds::starting_at(&doc.view.folds, row.seg.start).filter(|_| row.seg.line_start).copied() {
            let color = visuals.weak_text_color();
            if starts_line {
                let (c, r) = (pos2(gutter_rect.right() - 3.0, y + m.rh * 0.5), (m.rh * 0.22).max(2.5));
                painter.add(egui::Shape::convex_polygon(vec![pos2(c.x - r, c.y - r), pos2(c.x + r * 0.8, c.y), pos2(c.x - r, c.y + r)], color, egui::Stroke::NONE));
            }
            if row.is_last_in_seg() {
                let chip = crate::app::i18n::trf("… {n} lines …", &[("n", &crate::app::filter_panel::fmt_count(f.lines))]);
                let galley = ui.painter().layout_no_wrap(chip, FontId::proportional((m.rh * 0.7).max(9.0)), color);
                let x = x_of(if reached_end { end_cell } else { first_cell + vis_cells }) + m.cw;
                let rect = Rect::from_min_size(pos2(x, y + (m.rh - galley.size().y - 2.0) / 2.0), galley.size() + egui::vec2(10.0, 2.0));
                text_painter.rect_filled(rect, 4.0, visuals.faint_bg_color.gamma_multiply(2.0));
                text_painter.rect_stroke(rect, 4.0, egui::Stroke::new(1.0, visuals.widgets.noninteractive.bg_stroke.color), egui::StrokeKind::Inside);
                text_painter.galley(rect.min + egui::vec2(5.0, 1.0), galley, color);
                if ui.interact(rect, id.with(("fold", f.start)), Sense::click()).on_hover_cursor(CursorIcon::PointingHand).clicked() {
                    unfold.push(f.start);
                }
            }
        }
        if starts_line && doc.time_mark == Some((doc.version, row.start)) {
            // ◆: where Go to this time in all tabs put this tab.
            let (c, r) = (pos2(gutter_rect.left() + 5.5, y + m.rh * 0.5), (m.rh * 0.32).max(3.0));
            let points = vec![pos2(c.x, c.y - r), pos2(c.x + r, c.y), pos2(c.x, c.y + r), pos2(c.x - r, c.y)];
            painter.add(egui::Shape::convex_polygon(points, role(Color32::from_rgb(230, 180, 30), Tone::Found, visuals.dark_mode), egui::Stroke::NONE));
        }
        if starts_line && doc.bookmarks.binary_search(&row.start).is_ok() {
            let r = Rect::from_min_size(pos2(gutter_rect.left() + 3.0, y + m.rh * 0.2), egui::vec2(5.0, m.rh * 0.6));
            painter.rect_filled(r, 2.0, visuals.selection.stroke.color);
        }
    }
    doc.view.max_cells = max_w;
    doc.view.guides = 0;
    if code && !indents.is_empty() {
        let indents = super::indent::fill_blanks(&indents);
        let stroke = egui::Stroke::new(1.0, look.guide);
        let mut lines = Vec::new();
        // One line per level and run of rows indented deeper than it.
        for cell in super::indent::guide_cells(indents.iter().copied().max().unwrap_or(0), unit) {
            // Just inside the cell, so the first level is not cut off at the text's left edge.
            let x = text_painter.round_to_pixel_center(x_of(cell) + 0.5);
            if x < text_rect.left() {
                continue;
            }
            let mut from = None;
            for (i, &n) in indents.iter().chain(std::iter::once(&0)).enumerate() {
                if n > cell {
                    from.get_or_insert(i);
                } else if let Some(s) = from.take() {
                    let (y0, y1) = (text_rect.top() + s as f32 * m.rh, text_rect.top() + i as f32 * m.rh);
                    lines.push(egui::Shape::vline(x, y0..=y1, stroke));
                }
            }
        }
        doc.view.guides = lines.len();
        text_painter.set(guide_slot, egui::Shape::Vec(lines));
    }
    if !unfold.is_empty() {
        doc.view.folds.retain(|f| !unfold.contains(&f.start));
    }
    if let Some(col) = env.ruler {
        let x = x_of(col as u32);
        if text_rect.x_range().contains(x) {
            text_painter.vline(x, text_rect.y_range(), egui::Stroke::new(1.0, weak.gamma_multiply(0.45)));
        }
    }
    if focused && doc.is_ready() {
        // The input method puts its candidate window next to the caret (kept in the text area).
        let at = caret_rect.map_or(Rect::from_min_size(text_rect.min, egui::vec2(1.0, m.rh)), |r| r.translate(egui::vec2(r.left().clamp(text_rect.left(), text_rect.right()) - r.left(), 0.0)));
        ime_output(ui, doc, at, interrupt);
    }
    if a11y_on {
        let (line, exact) = doc.buf.line_of(caret);
        let col = match doc.buf.line_start(line) {
            Some((ls, true)) if caret >= ls && caret - ls <= 128 * 1024 => doc.buf.read(ls..caret).map(|b| (rows::cell_width(&doc.buf.codec, &b, ls) + 1).to_string()),
            _ => None,
        };
        let position = crate::app::i18n::trf("Ln {line}, Col {col}", &[("line", &format!("{}{}", if exact { "" } else { "~" }, line + 1)), ("col", col.as_deref().unwrap_or("?"))]);
        let w = super::a11y::TextWidget { label: &doc.title, position, read_only: !doc.editable(), rows: &a11y_rows, anchor: doc.view.anchor, caret };
        let said = super::a11y::text_widget(ui, id, &w);
        doc.view.a11y_last = Some(said);
    }

    match &doc.state {
        crate::app::document::DocState::Loading => {
            let msg = match &doc.unpacking {
                Some((p, _)) if p.total() > 0 => {
                    ui.ctx().request_repaint_after(std::time::Duration::from_millis(100));
                    crate::app::i18n::trf("Unpacking… {pct}% of {size}", &[("pct", &format!("{:.0}", p.fraction() * 100.0)), ("size", &bigtext::jobs::human_bytes(p.total()))])
                }
                _ => crate::app::i18n::tr("Opening…").to_string(),
            };
            painter.text(text_rect.center(), Align2::CENTER_CENTER, msg, FontId::proportional(18.0), weak);
        }
        crate::app::document::DocState::Finalizing(msg) => {
            painter.text(text_rect.center(), Align2::CENTER_CENTER, msg, FontId::proportional(18.0), weak);
        }
        crate::app::document::DocState::Failed(e) => {
            painter.text(text_rect.center(), Align2::CENTER_CENTER, e, FontId::proportional(16.0), visuals.error_fg_color);
        }
        crate::app::document::DocState::Ready => {
            if pending {
                painter.text(text_rect.right_top() + egui::vec2(-8.0, 4.0), Align2::RIGHT_TOP, crate::app::i18n::tr("Loading…"), FontId::proportional(13.0), weak);
                ui.ctx().request_repaint_after(std::time::Duration::from_millis(30));
            } else if doc.view.first_paint.is_none() && !rows.is_empty() {
                doc.view.first_paint = Some(std::time::Instant::now());
            }
        }
    }

    // Scrollbars.
    if doc.is_ready() {
        vertical_scrollbar(ui, doc, id, vbar, &rows, wrap);
        if show_h {
            horizontal_scrollbar(ui, doc, id, hbar, m, text_rect.width());
        }
    }
}

/// The indentation step of the document's code, guessed again after each edit.
fn indent_unit(doc: &mut Document) -> u32 {
    if let Some((_, unit)) = doc.view.indent_unit.filter(|&(v, _)| v == doc.version) {
        return unit;
    }
    let Some(head) = doc.buf.read(0..doc.buf.len().min(super::indent::GUESS_BYTES)) else { return 4 };
    let unit = super::indent::guess_unit(&head);
    doc.view.indent_unit = Some((doc.version, unit));
    unit
}

/// The visible text of a row: as painted (`run`, with the byte ranges of placeholder glyphs),
/// and as in the file (`src`), with where each character of `src` is painted in `run`.
struct Shown<'a> {
    run: &'a str,
    specials: &'a [(usize, usize)],
    src: &'a str,
    map: &'a [(usize, usize)],
}

/// Turns the visible text of a row into layout sections: syntax colours (of the text as it is
/// in the file, starting in state `st`), with placeholder glyphs (controls, invalid bytes)
/// always dimmed.
#[allow(clippy::too_many_arguments)]
fn build_job(job: &mut LayoutJob, shown: &Shown, lang: super::highlight::Lang, st: super::highlight::State, font: &FontId, normal: Color32, weak: Color32, look: &Look) {
    let text = shown.run;
    if text.is_empty() {
        return;
    }
    let mut colors = vec![normal; text.len()];
    if lang != super::highlight::Lang::Plain && !shown.src.is_empty() {
        let mut spans = Vec::new();
        super::highlight::spans_from(lang, st, shown.src, false, &mut spans);
        let mut src_colors = vec![normal; shown.src.len()];
        for (a, b, k) in spans {
            let c = look.token(k);
            for x in &mut src_colors[a.min(shown.src.len())..b.min(shown.src.len())] {
                *x = c;
            }
        }
        for (n, &(s, r)) in shown.map.iter().enumerate() {
            let end = shown.map.get(n + 1).map_or(text.len(), |m| m.1);
            for x in &mut colors[r..end] {
                *x = src_colors[s];
            }
        }
    }
    for &(a, b) in shown.specials {
        for x in &mut colors[a..b] {
            *x = weak;
        }
    }
    let mut start = 0;
    let mut cur = colors[0];
    for (i, _) in text.char_indices().skip(1) {
        if colors[i] != cur {
            job.append(&text[start..i], 0.0, TextFormat { font_id: font.clone(), color: cur, ..Default::default() });
            start = i;
            cur = colors[i];
        }
    }
    job.append(&text[start..], 0.0, TextFormat { font_id: font.clone(), color: cur, ..Default::default() });
}

fn control_glyph(c: char) -> char {
    match c as u32 {
        0 => '∅',
        0x0D => '←',
        0x1B => '⎋',
        _ => '·',
    }
}

pub(crate) fn vertical_scrollbar(ui: &mut Ui, doc: &mut Document, id: egui::Id, bar: Rect, rows: &[Row], wrap: Option<usize>) {
    let len = doc.buf.len().max(1);
    let visible = rows.last().map(|r| r.seg.next.max(r.end)).unwrap_or(doc.view.top).saturating_sub(doc.view.top).max(1);
    let track_h = bar.height();
    let thumb_h = (track_h * (visible as f64 / len as f64) as f32).clamp(24.0_f32.min(track_h), track_h);
    let frac = doc.view.top as f64 / len as f64;
    let thumb_y = bar.top() + (track_h - thumb_h) * frac as f32;
    let thumb = Rect::from_min_max(pos2(bar.left() + 2.0, thumb_y), pos2(bar.right() - 2.0, thumb_y + thumb_h));
    let r = ui.interact(bar, id.with("vbar"), Sense::click_and_drag());
    ui.ctx().accesskit_node_builder(r.id, |b| {
        use egui::accesskit;
        b.set_role(accesskit::Role::ScrollBar);
        b.set_orientation(accesskit::Orientation::Vertical);
        b.set_min_numeric_value(0.0);
        b.set_max_numeric_value(100.0);
        b.set_numeric_value((frac * 100.0).round());
    });
    let painter = ui.painter_at(bar);
    let v = ui.visuals();
    painter.rect_filled(bar, 0.0, v.faint_bg_color);
    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);
    paint_marks(&painter, doc, bar, v.dark_mode);
    if r.dragged() || r.is_pointer_button_down_on() {
        if let Some(p) = r.interact_pointer_pos() {
            let f = ((p.y - bar.top() - thumb_h / 2.0) / (track_h - thumb_h).max(1.0)).clamp(0.0, 1.0) as f64;
            let target = (f * len as f64) as u64;
            if let Ok(row) = rows::row_at(&doc.buf, target.min(doc.buf.len()), wrap) {
                doc.view.top = row.start;
            }
            // Where the drag is: "~Ln 45,357,933 · 48 %" next to the pointer.
            let (line, exact) = doc.buf.line_of(doc.view.top);
            let text = format!("{}Ln {} · {:.0} %", if exact { "" } else { "~" }, crate::app::filter_panel::fmt_count(line + 1), doc.view.top as f64 * 100.0 / len as f64);
            let tip = ui.ctx().layer_painter(egui::LayerId::new(egui::Order::Tooltip, id.with("vbar-tip")));
            let galley = tip.layout_no_wrap(text, egui::FontId::proportional(13.0), v.text_color());
            let at = pos2(bar.left() - 12.0 - galley.size().x, p.y - galley.size().y / 2.0);
            tip.rect_filled(Rect::from_min_size(at, galley.size()).expand(4.0), 4.0, v.window_fill());
            tip.galley(at, galley, v.text_color());
        }
    }
}

/// Where things are in the document, one bit per kind for each pixel row of the scrollbar.
/// Find All and filter results only grow while their job runs, so new entries are added
/// incrementally; everything is rebuilt when the document, its length or the bar height changes.
#[derive(Default)]
pub struct ScrollMarks {
    key: (u64, u64, u32, usize, usize),
    results_done: usize,
    filter_done: usize,
    other: (usize, usize),
    rows: Vec<u8>,
}

pub const MARK_FOUND: u8 = 1;
pub const MARK_FILTER: u8 = 2;
pub const MARK_BOOKMARK: u8 = 4;
pub const MARK_DIFF: u8 = 8;

impl ScrollMarks {
    /// The kinds of marks currently on the bar (bitwise or of `MARK_*`).
    pub fn kinds(&self) -> u8 {
        self.rows.iter().fold(0, |a, &b| a | b)
    }
}

fn paint_marks(painter: &egui::Painter, doc: &mut Document, bar: Rect, dark: bool) {
    let len = doc.buf.len();
    let h = bar.height().max(1.0) as u32;
    if len == 0 {
        return;
    }
    let ptr = |o: Option<usize>| o.unwrap_or(0);
    let results = doc.results.as_ref().filter(|r| r.version == doc.version);
    let filter = doc.filter.as_ref().filter(|r| r.version == doc.version);
    let key = (doc.version, len, h, ptr(results.map(|r| std::sync::Arc::as_ptr(&r.data) as usize)), ptr(filter.map(|r| std::sync::Arc::as_ptr(&r.data) as usize)));
    let mut m = std::mem::take(&mut doc.view.scroll_marks);
    let other = (doc.bookmarks.len(), doc.diff_marks.len());
    if m.key != key || m.other != other {
        m = ScrollMarks { key, rows: vec![0; h as usize], ..Default::default() };
        m.other = other;
        let row = |off: u64| ((off as f64 / len as f64) * h as f64).min(h as f64 - 1.0) as usize;
        for &b in &doc.bookmarks {
            m.rows[row(b)] |= MARK_BOOKMARK;
        }
        for &d in &doc.diff_marks {
            m.rows[row(d)] |= MARK_DIFF;
        }
    }
    let row = |off: u64| ((off as f64 / len as f64) * h as f64).min(h as f64 - 1.0) as usize;
    if let Some(r) = results {
        let g = r.data.lock().unwrap();
        for &(s, _) in &g.matches[m.results_done.min(g.matches.len())..] {
            m.rows[row(s)] |= MARK_FOUND;
        }
        m.results_done = g.matches.len();
    }
    if let Some(r) = filter {
        let g = r.data.lock().unwrap();
        let from = m.filter_done.min(g.lines.len());
        for (i, &s) in g.lines[from..].iter().enumerate() {
            if !g.is_context(from + i) {
                m.rows[row(s)] |= MARK_FILTER;
            }
        }
        m.filter_done = g.lines.len();
    }
    // Lanes from the left: diff, filter, search, bookmarks across the whole width.
    let lane = (bar.width() - 4.0) / 3.0;
    let colors = [
        (MARK_DIFF, 0.0, role(if dark { Color32::from_rgb(220, 90, 90) } else { Color32::from_rgb(200, 50, 50) }, Tone::Bad, dark)),
        (MARK_FILTER, 1.0, role(if dark { Color32::from_rgb(90, 160, 240) } else { Color32::from_rgb(40, 110, 220) }, Tone::Info, dark)),
        (MARK_FOUND, 2.0, role(if dark { Color32::from_rgb(230, 180, 30) } else { Color32::from_rgb(220, 150, 0) }, Tone::Found, dark)),
    ];
    for (y, &bits) in m.rows.iter().enumerate() {
        if bits == 0 {
            continue;
        }
        let top = bar.top() + y as f32;
        for &(bit, i, c) in &colors {
            if bits & bit != 0 {
                let x = bar.left() + 2.0 + i * lane;
                painter.rect_filled(Rect::from_min_max(pos2(x, top), pos2(x + lane, top + 2.0)), 0.0, c);
            }
        }
        if bits & MARK_BOOKMARK != 0 {
            painter.rect_filled(Rect::from_min_max(pos2(bar.left() + 1.0, top), pos2(bar.right() - 1.0, top + 2.0)), 0.0, role(if dark { Color32::from_rgb(120, 200, 255) } else { Color32::from_rgb(30, 120, 200) }, Tone::Caret, dark));
        }
    }
    doc.view.scroll_marks = m;
}

fn horizontal_scrollbar(ui: &mut Ui, doc: &mut Document, id: egui::Id, bar: Rect, m: Metrics, text_w: f32) {
    let content = doc.view.max_cells as f32 * m.cw + 4.0 * m.cw;
    let max_scroll = (content - text_w).max(0.0);
    doc.view.scroll_x = doc.view.scroll_x.clamp(0.0, max_scroll.max(doc.view.scroll_x.min(max_scroll + text_w)));
    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 track_w = bar.width();
    let thumb_w = (track_w * text_w / content).clamp(24.0_f32.min(track_w), track_w);
    let x = bar.left() + (track_w - thumb_w) * (doc.view.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);
            doc.view.scroll_x = f * max_scroll;
        }
    }
}

fn handle_wheel(ui: &mut Ui, doc: &mut Document, resp: &egui::Response, m: Metrics, wrap: Option<usize>, env: &mut ViewEnv) {
    if !resp.hovered() {
        return;
    }
    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 / m.rh + doc.view.wheel_rem;
        let n = rows_f.trunc() as i64;
        doc.view.wheel_rem = rows_f - n as f32;
        if n != 0 {
            if let Ok(top) = rows::row_at(&doc.buf, doc.view.top, wrap) {
                if let Ok(r) = super::folds::step_rows(&doc.buf, top, n, wrap, &doc.view.folds) {
                    doc.view.top = r.start;
                }
            }
        }
    }
    if delta.x != 0.0 && h_scroll(&doc.view) {
        doc.view.scroll_x = (doc.view.scroll_x - delta.x).max(0.0);
    }
}

/// The row under `pos` and the nearest cell boundary.
fn hit_cell(doc: &Document, rows: &[Row], text_rect: Rect, m: Metrics, pos: Pos2) -> Option<(Row, u32)> {
    if rows.is_empty() {
        return None;
    }
    let ri = ((pos.y - text_rect.top()) / m.rh).floor();
    let row = if ri < 0.0 {
        rows[0]
    } else {
        let i = (ri as usize).min(rows.len() - 1);
        rows[i]
    };
    let col = ((pos.x - text_rect.left() + doc.view.scroll_x) / m.cw).round().max(0.0) as u32;
    Some((row, col))
}

/// Under the mouse, a Unix time (`1714573925`, `1714573925123`) shows as a date and time.
fn epoch_tooltip(ui: &Ui, doc: &Document, resp: &egui::Response, text_rect: Rect, m: Metrics, rows: &[Row]) {
    let Some(pos) = resp.hover_pos().filter(|p| text_rect.contains(*p)) else { return };
    if doc.buf.codec.unit() != 1 || ui.input(|i| i.pointer.any_down()) {
        return;
    }
    let ri = ((pos.y - text_rect.top()) / m.rh).floor() as usize;
    let Some(row) = rows.get(ri) else { return };
    // The character under the pointer, not the nearest boundary.
    let col = ((pos.x - text_rect.left() + doc.view.scroll_x) / m.cw).floor().max(0.0) as u32;
    let Ok(off) = rows::offset_at_cell(&doc.buf, row, col) else { return };
    let (from, to) = (off.saturating_sub(24).max(row.start), (off + 24).min(row.end));
    let Some(b) = doc.buf.read(from..to) else { return };
    let i = (off - from) as usize;
    let num = |c: &u8| c.is_ascii_digit() || *c == b'.';
    if !b.get(i).is_some_and(u8::is_ascii_digit) {
        return;
    }
    let s = i - b[..i].iter().rev().take_while(|c| num(c)).count();
    let e = i + b[i..].iter().take_while(|c| num(c)).count();
    let word = String::from_utf8_lossy(&b[s..e]);
    if let Some(text) = bigtext::timestamp::epoch_text(word.trim_matches('.')) {
        resp.clone().on_hover_text_at_pointer(text);
    }
}

fn hit_test(doc: &Document, rows: &[Row], text_rect: Rect, m: Metrics, pos: Pos2) -> Option<u64> {
    let (row, col) = hit_cell(doc, rows, text_rect, m, pos)?;
    rows::offset_at_cell(&doc.buf, &row, col).ok()
}

#[allow(clippy::too_many_arguments)]
fn handle_mouse(ui: &mut Ui, doc: &mut Document, resp: &egui::Response, text_rect: Rect, m: Metrics, wrap: Option<usize>, rows: &[Row], active_pane: bool) {
    let (pressed, down, mods, pos, dbl, tpl) = ui.input(|i| {
        (
            i.pointer.primary_pressed(),
            i.pointer.primary_down(),
            i.modifiers,
            i.pointer.interact_pos(),
            i.pointer.button_double_clicked(PointerButton::Primary),
            i.pointer.button_triple_clicked(PointerButton::Primary),
        )
    });
    let Some(pos) = pos else { return };
    // Alt+drag: column (block) selection.
    if pressed && text_rect.contains(pos) && resp.hovered() && mods.alt && wrap.is_none() {
        if let Some((row, col)) = hit_cell(doc, rows, text_rect, m, pos) {
            doc.view.alt_prev = Some((doc.view.anchor, doc.view.caret));
            doc.view.block = Some(Block::at(row.start, col));
            doc.view.block_drag = true;
            if let Ok(off) = rows::offset_at_cell(&doc.buf, &row, col) {
                doc.set_caret(off, false);
                doc.view.scroll_to_caret = false;
            }
        }
        return;
    }
    if doc.view.block_drag && active_pane {
        if !down {
            doc.view.block_drag = false;
            // Alt+click without a drag: another cursor.
            if let (Some(b), Some((a, c))) = (doc.view.block, doc.view.alt_prev.take()) {
                if b.anchor == b.caret && b.anchor_cell == b.caret_cell {
                    let off = doc.view.caret;
                    doc.view.block = None;
                    doc.view.anchor = a;
                    doc.view.caret = c;
                    crate::view::multi::add_cursor(doc, off, off);
                }
            }
            return;
        }
        if pos.y < text_rect.top() || pos.y > text_rect.bottom() {
            let n = if pos.y < text_rect.top() { -1 } else { 1 };
            if let Ok(top) = rows::row_at(&doc.buf, doc.view.top, wrap) {
                if let Ok(r) = super::folds::step_rows(&doc.buf, top, n, wrap, &doc.view.folds) {
                    doc.view.top = r.start;
                }
            }
            ui.ctx().request_repaint();
        }
        let clamped = pos2(pos.x.max(text_rect.left()), pos.y.clamp(text_rect.top(), text_rect.bottom() - 1.0));
        if let (Some((row, col)), Some(b)) = (hit_cell(doc, rows, text_rect, m, clamped), doc.view.block.as_mut()) {
            b.caret = row.start;
            b.caret_cell = col;
            if let Ok(off) = rows::offset_at_cell(&doc.buf, &row, col) {
                doc.view.caret = off;
                doc.view.anchor = off;
            }
        }
        return;
    }
    if pressed && text_rect.contains(pos) && resp.hovered() {
        doc.view.block = None;
        doc.view.extra.clear();
        if let Some(off) = hit_test(doc, rows, text_rect, m, pos) {
            doc.set_caret(off, mods.shift);
            doc.view.desired_cell = None;
            doc.view.dragging = true;
            doc.view.scroll_to_caret = false;
        }
    }
    if (dbl || tpl) && text_rect.contains(pos) {
        if let Some(off) = hit_test(doc, rows, text_rect, m, pos) {
            if tpl {
                doc.select_line(off);
            } else {
                select_word(doc, off, wrap);
            }
            doc.view.dragging = false;
        }
    }
    if doc.view.dragging && active_pane {
        if !down {
            doc.view.dragging = false;
        } else {
            if pos.y < text_rect.top() || pos.y > text_rect.bottom() {
                let n = if pos.y < text_rect.top() { -1 } else { 1 };
                if let Ok(top) = rows::row_at(&doc.buf, doc.view.top, wrap) {
                    if let Ok(r) = super::folds::step_rows(&doc.buf, top, n, wrap, &doc.view.folds) {
                        doc.view.top = r.start;
                    }
                }
                ui.ctx().request_repaint();
            }
            let clamped = pos2(pos.x.max(text_rect.left()), pos.y.clamp(text_rect.top(), text_rect.bottom() - 1.0));
            if let Some(off) = hit_test(doc, rows, text_rect, m, clamped) {
                doc.view.caret = off.clamp(doc.min_caret(), doc.buf.len());
            }
        }
    }
}

fn is_word_char(c: char) -> bool {
    c.is_alphanumeric() || c == '_'
}

pub(crate) fn select_word(doc: &mut Document, off: u64, wrap: Option<usize>) {
    let Ok(row) = rows::row_at(&doc.buf, off, wrap) else { return };
    let lo = off.saturating_sub(1024).max(row.seg.start);
    let hi = (off + 1024).min(row.seg.content_end);
    let Some(bytes) = doc.buf.read(lo..hi) else { return };
    let codec = doc.buf.codec;
    let mut chars: Vec<(u64, u64, char)> = Vec::new();
    rows::for_each_cell(&codec, &bytes, lo, |c| {
        chars.push((c.off, c.off + c.len as u64, c.ch));
        true
    });
    let Some(i) = chars.iter().position(|&(s, e, _)| off >= s && off < e).or_else(|| chars.len().checked_sub(1)) else { return };
    let word = is_word_char(chars[i].2);
    let mut a = i;
    while a > 0 && is_word_char(chars[a - 1].2) == word && word {
        a -= 1;
    }
    let mut b = i;
    while b + 1 < chars.len() && is_word_char(chars[b + 1].2) == word && word {
        b += 1;
    }
    doc.select(chars[a].0, chars[b].1);
    doc.view.scroll_to_caret = false;
}

/// Turns on the input method with its window at `caret`. egui-winit places the window by
/// `rect`, so that is the caret too, not the whole text area (the window would go below it).
fn ime_output(ui: &mut Ui, doc: &mut Document, caret: Rect, interrupt: bool) {
    let to_global = ui.ctx().layer_transform_to_global(ui.layer_id()).unwrap_or_default();
    let rect = to_global * caret;
    doc.view.ime_rect = Some(rect);
    ui.ctx().output_mut(|o| {
        o.ime = Some(egui::output::IMEOutput { purpose: egui::IMEPurpose::Normal, rect, cursor_rect: rect, should_interrupt_composition: interrupt });
    });
}

/// How far `text` advances as egui draws it in `font`: with the glyphs of fallback fonts, the
/// replacement glyph for characters no font has, nothing for invisible ones. (egui's own
/// `glyph_width` gives 0 for a missing character, and `has_glyph` is false for every character
/// of the font that has the replacement glyph.)
fn advance(ctx: &egui::Context, font: &FontId, text: &str) -> f32 {
    ctx.fonts_mut(|f| {
        let galley = f.layout_no_wrap(text.to_owned(), font.clone(), Color32::PLACEHOLDER);
        galley.rows.first().map_or(0.0, |r| r.row.glyphs.iter().map(|g| g.advance_width).sum())
    })
}

/// True for characters of right-to-left scripts (Hebrew, Arabic, Syriac, Thaana, N'Ko…).
fn is_rtl(c: char) -> bool {
    matches!(c as u32, 0x0590..=0x08FF | 0xFB1D..=0xFDFF | 0xFE70..=0xFEFE | 0x10800..=0x10FFF | 0x1E800..=0x1EFFF)
}

/// Where the clusters of `cells` start: user-perceived characters (a letter with its accents,
/// a Hindi syllable, an emoji with its skin tone or joined emoji); tabs, control characters and
/// invalid bytes stand alone.
fn cluster_starts(cells: &[rows::Cell]) -> Vec<usize> {
    use unicode_segmentation::UnicodeSegmentation;
    if cells.iter().all(|c| c.ch.is_ascii()) {
        return (0..cells.len()).collect();
    }
    let mut text = String::new();
    let mut index = Vec::with_capacity(cells.len());
    for (i, c) in cells.iter().enumerate() {
        index.extend(std::iter::repeat_n(i, c.ch.len_utf8()));
        text.push(c.ch);
    }
    let mut breaks = vec![false; cells.len()];
    for (b, _) in text.grapheme_indices(true) {
        breaks[index[b]] = true;
    }
    // A sign that stacks the next consonant under the one before (Myanmar, Khmer, Kannada…)
    // joins their clusters, which Unicode's rules leave apart for these scripts: shaped apart,
    // each would get a dotted circle.
    let stacks = |c: char| matches!(c as u32, 0x0A4D | 0x0CCD | 0x1039 | 0x17D2 | 0x1A60 | 0x1B44 | 0x1BAB | 0xA9C0);
    // Vowel signs the rules leave out of their syllable (Myanmar ာ, Tai Tham…), likewise.
    let vowel = |c: char| matches!(c as u32, 0x102B | 0x102C | 0x1038 | 0x1062..=0x1064 | 0x1067..=0x106D | 0x1083 | 0x1087..=0x108C | 0x108F | 0x109A..=0x109C | 0x1A61 | 0x1A63 | 0x1A64 | 0xAA7B | 0xAA7D);
    (0..cells.len())
        .filter(|&i| i == 0 || (breaks[i] && !stacks(cells[i - 1].ch) && !vowel(cells[i].ch)) || cells[i].kind != CellKind::Normal || cells[i - 1].kind != CellKind::Normal)
        .collect()
}

/// The loose clusters of a row (see [`Loose`]) as layout jobs, with the cell each starts at
/// and how far right and down of its row: neighbours alike in width and colour go in one job,
/// spaced out to their cells; each is centred in its cells, and one much wider than them (a
/// Tamil letter, a circled number) is made smaller to fit. Colours come from the row's `job`;
/// `fh` is the font's line height.
fn loose_jobs(loose: &[Loose], job: &LayoutJob, font: &FontId, cw: f32, fh: f32) -> Vec<(u32, egui::Vec2, LayoutJob)> {
    let color_at = |at: usize| {
        let i = job.sections.partition_point(|s| s.byte_range.end.0 <= at);
        job.sections.get(i).map_or(Color32::PLACEHOLDER, |s| s.format.color)
    };
    let mut out = Vec::new();
    let mut i = 0;
    while i < loose.len() {
        let a = &loose[i];
        let color = color_at(a.at);
        let mut text = a.text.clone();
        let mut j = i + 1;
        while let Some(b) = loose.get(j).filter(|_| !a.alone) {
            let prev = &loose[j - 1];
            if b.alone || b.cell != prev.cell + prev.width || b.width != a.width || (b.adv - a.adv).abs() > 0.01 || color_at(b.at) != color {
                break;
            }
            text.push_str(&b.text);
            j += 1;
        }
        let slot = a.width as f32 * cw;
        // A little wider may stick out; much wider shrinks, to no less than 60 %.
        let scale = if a.adv > slot * 1.15 { (slot / a.adv).max(0.6) } else { 1.0 };
        // The spacing goes between glyphs, not before the first.
        let gap = slot - a.adv * scale;
        let spacing = if j - i > 1 { gap } else { 0.0 };
        let font_id = FontId::new(font.size * scale, font.family.clone());
        let mut lj = LayoutJob::default();
        lj.append(&text, 0.0, TextFormat { font_id, color, extra_letter_spacing: spacing, ..Default::default() });
        out.push((a.cell, egui::vec2(gap / 2.0, fh * (1.0 - scale) / 2.0), lj));
        i = j;
    }
    out
}

/// Input while a block selection is active. Returns true if the event was used; keys that
/// move the caret or edit normally end the block first.
fn handle_block_event(ui: &mut Ui, doc: &mut Document, ev: &Event) -> bool {
    let Some(mut b) = doc.view.block else { return false };
    let used = match ev {
        Event::Text(t) if !t.chars().all(|c| c.is_control()) => {
            edit_block(doc, &mut b, BlockEdit::Insert(t.clone()));
            true
        }
        Event::Ime(egui::ImeEvent::Commit(t)) if !t.is_empty() => {
            edit_block(doc, &mut b, BlockEdit::Insert(t.clone()));
            true
        }
        Event::Paste(s) => {
            let lines: Vec<String> = s.lines().map(str::to_string).collect();
            let n = block_rows(doc, &b).map(|r| r.len()).unwrap_or(0);
            let e = if n > 1 && lines.len() == n { BlockEdit::PerRow(lines) } else { BlockEdit::Insert(s.replace(['\r', '\n'], " ")) };
            edit_block(doc, &mut b, e);
            true
        }
        Event::Copy | Event::Cut => {
            if let Some(t) = block_text(doc, &b) {
                ui.ctx().copy_text(t);
            }
            if matches!(ev, Event::Cut) {
                edit_block(doc, &mut b, BlockEdit::Insert(String::new()));
            }
            true
        }
        Event::Key { key: Key::Backspace, pressed: true, modifiers, .. } if !modifiers.command => {
            edit_block(doc, &mut b, BlockEdit::Backspace);
            true
        }
        Event::Key { key: Key::Delete, pressed: true, modifiers, .. } if !modifiers.command => {
            edit_block(doc, &mut b, BlockEdit::Delete);
            true
        }
        Event::Key { key: Key::Tab, pressed: true, modifiers, .. } if !modifiers.command && !modifiers.shift => {
            edit_block(doc, &mut b, BlockEdit::Insert("\t".into()));
            true
        }
        Event::Key { key, pressed: true, modifiers, .. } => {
            let ends = matches!(
                key,
                Key::ArrowLeft | Key::ArrowRight | Key::ArrowUp | Key::ArrowDown | Key::Home | Key::End | Key::PageUp | Key::PageDown | Key::Escape | Key::Enter
            ) || (modifiers.command && matches!(key, Key::Z | Key::Y | Key::A | Key::D | Key::K));
            if ends {
                doc.view.block = None;
                if *key == Key::Escape {
                    return true;
                }
            }
            return false;
        }
        _ => false,
    };
    if used {
        doc.view.block = Some(b);
    }
    used
}

/// Shift+Alt+arrows (Ctrl too, since Shift+Alt alone switches the keyboard layout on many
/// systems): make or grow a column block from the keyboard.
fn block_key(doc: &mut Document, ev: &Event, wrap: Option<usize>) -> bool {
    use bigtext::text::rows;
    let Event::Key { key, pressed: true, modifiers: m, .. } = ev else { return false };
    if !(m.alt && m.shift) || wrap.is_some() || !matches!(key, Key::ArrowLeft | Key::ArrowRight | Key::ArrowUp | Key::ArrowDown | Key::Home | Key::End | Key::PageUp | Key::PageDown) {
        return false;
    }
    let buf = &doc.buf;
    let mut b = match doc.view.block {
        Some(b) => b,
        None => {
            let Ok(row) = rows::row_at(buf, doc.view.caret, None) else { return true };
            let Ok(cell) = rows::cell_of_offset(buf, &row, doc.view.caret) else { return true };
            crate::view::block::Block::at(row.start, cell)
        }
    };
    let Ok(row) = rows::row_at(buf, b.caret, None) else { return true };
    let page = doc.view.rows_on_screen.saturating_sub(1).max(1) as i64;
    let to_row = |n: i64| rows::step_rows(buf, row, n, None).map(|r| r.start).unwrap_or(row.start);
    match key {
        Key::ArrowLeft => b.caret_cell = b.caret_cell.saturating_sub(1),
        Key::ArrowRight => b.caret_cell += 1,
        Key::ArrowUp => b.caret = to_row(-1),
        Key::ArrowDown => b.caret = to_row(1),
        Key::PageUp => b.caret = to_row(-page),
        Key::PageDown => b.caret = to_row(page),
        Key::Home if m.command => b.caret = rows::row_at(buf, doc.min_caret(), None).map(|r| r.start).unwrap_or(0),
        Key::End if m.command => b.caret = rows::row_at(buf, buf.len(), None).map(|r| r.start).unwrap_or(b.caret),
        Key::Home => b.caret_cell = 0,
        _ => b.caret_cell = rows::cell_of_offset(buf, &row, row.end).unwrap_or(b.caret_cell),
    }
    // The caret follows the block's moving corner.
    if let Ok(r) = rows::row_at(buf, b.caret, None) {
        if let Ok(off) = rows::offset_at_cell(buf, &r, b.caret_cell) {
            doc.view.caret = off;
            doc.view.anchor = off;
            doc.view.scroll_to_caret = true;
        }
    }
    doc.view.block = Some(b);
    true
}

fn handle_keys(ui: &mut Ui, doc: &mut Document, wrap: Option<usize>, env: &mut ViewEnv) {
    let events = ui.input(|i| i.events.clone());
    for ev in events {
        match &ev {
            Event::Ime(egui::ImeEvent::Preedit { text, active_range_chars }) => {
                let shown = doc.editable() && !text.is_empty();
                doc.view.preedit = if shown { Preedit { text: text.clone(), cursor: active_range_chars.as_ref().map(|r| r.end), at: doc.view.caret } } else { Preedit::default() };
                continue;
            }
            Event::Ime(egui::ImeEvent::Commit(_)) => doc.view.preedit = Preedit::default(),
            _ => {}
        }
        if block_key(doc, &ev, wrap) || handle_block_event(ui, doc, &ev) || crate::view::multi::handle_event(ui, doc, &ev, wrap) {
            continue;
        }
        match ev {
            Event::Text(t) => {
                if doc.editable() && !t.chars().all(|c| c.is_control()) && !super::pairs::typed(doc, &t, env.lang) {
                    doc.insert_text(&t);
                }
            }
            // Brackets and quotes in code: an empty pair goes at once, Enter opens a block.
            Event::Key { key: Key::Backspace, pressed: true, modifiers, .. } if modifiers.is_none() && super::pairs::backspace(doc, env.lang) => {}
            Event::Key { key: Key::Enter, pressed: true, modifiers, .. } if modifiers.is_none() && {
                let unit = " ".repeat(doc.view.indent_unit.map_or(4, |u| u.1 as usize));
                super::pairs::enter(doc, env.lang, &unit)
            } => {}
            Event::Ime(egui::ImeEvent::Commit(t)) => {
                if doc.editable() && !t.is_empty() {
                    doc.insert_text(&t);
                }
            }
            Event::Copy => copy(ui, doc, env, false),
            Event::Cut => {
                if doc.editable() {
                    copy(ui, doc, env, true)
                }
            }
            Event::Paste(s) => {
                if doc.editable() {
                    paste(doc, &s);
                }
            }
            Event::Key { key: Key::Escape, pressed: true, .. } if !doc.has_selection() => env.actions.push(ViewAction::Escape),
            Event::Key { key, pressed: true, modifiers, .. } => handle_key(doc, key, modifiers, wrap),
            _ => {}
        }
    }
}

fn copy(ui: &mut Ui, doc: &mut Document, env: &mut ViewEnv, cut: bool) {
    match doc.selection_text(SYNC_COPY_MAX) {
        Some(Ok(text)) => {
            ui.ctx().copy_text(text);
            if cut {
                doc.delete_selection();
            }
        }
        Some(Err(len)) => env.actions.push(ViewAction::CopyLarge { cut, len }),
        None => {}
    }
}

/// Inserts clipboard text, converting its line breaks to the document's style.
pub fn paste(doc: &mut Document, s: &str) {
    use bigtext::encoding::LineEnding;
    let normalized: std::borrow::Cow<str> = match doc.line_ending {
        LineEnding::CrLf => {
            let lf = s.replace("\r\n", "\n");
            std::borrow::Cow::Owned(lf.replace('\n', "\r\n"))
        }
        LineEnding::Lf => std::borrow::Cow::Owned(s.replace("\r\n", "\n")),
        LineEnding::Cr => std::borrow::Cow::Owned(s.replace("\r\n", "\r").replace('\n', "\r")),
        _ => std::borrow::Cow::Borrowed(s),
    };
    let (a, b) = doc.selection();
    let bytes = doc.buf.codec.encode(&normalized);
    doc.edit(a..b, &bytes, crate::app::document::EditKind::Other);
}

fn move_horizontal(doc: &Document, wrap: Option<usize>, right: bool, word: bool) -> u64 {
    let c = doc.view.caret;
    let Ok(row) = rows::row_at(&doc.buf, c, wrap) else { return c };
    if right {
        if c >= row.seg.content_end && row.is_last_in_seg() {
            return row.seg.next.min(doc.buf.len()).max(c);
        }
        if word {
            return word_boundary(doc, c, row.seg.content_end, true);
        }
        rows::next_stop(&doc.buf, c)
    } else {
        if c == row.seg.start && row.seg.line_start && c > 0 {
            if let Ok(Some(prev)) = rows::prev_seg(&doc.buf, &row.seg) {
                return prev.content_end.max(doc.min_caret());
            }
        }
        if word {
            return word_boundary(doc, c, row.seg.start, false);
        }
        rows::prev_stop(&doc.buf, c).max(doc.min_caret())
    }
}

fn word_boundary(doc: &Document, c: u64, limit: u64, right: bool) -> u64 {
    let (lo, hi) = if right { (c, limit.min(c + 4096)) } else { (limit.max(c.saturating_sub(4096)), c) };
    let Some(bytes) = doc.buf.read(lo..hi) else { return c };
    let mut chars: Vec<(u64, char)> = Vec::new();
    rows::for_each_cell(&doc.buf.codec, &bytes, lo, |x| {
        chars.push((x.off, x.ch));
        true
    });
    if right {
        let mut i = 0;
        while i < chars.len() && !is_word_char(chars[i].1) {
            i += 1;
        }
        while i < chars.len() && is_word_char(chars[i].1) {
            i += 1;
        }
        chars.get(i).map(|x| x.0).unwrap_or(hi)
    } else {
        let mut i = chars.len();
        while i > 0 && !is_word_char(chars[i - 1].1) {
            i -= 1;
        }
        while i > 0 && is_word_char(chars[i - 1].1) {
            i -= 1;
        }
        chars.get(i).map(|x| x.0).unwrap_or(lo).max(doc.min_caret())
    }
}

fn move_vertical(doc: &mut Document, n: i64, extend: bool, wrap: Option<usize>) {
    let c = doc.view.caret;
    let Ok(row) = rows::row_at(&doc.buf, c, wrap) else { return };
    let cell = match doc.view.desired_cell {
        Some(x) => x,
        None => rows::cell_of_offset(&doc.buf, &row, c).unwrap_or(0),
    };
    let Ok(target) = super::folds::step_rows(&doc.buf, row, n, wrap, &doc.view.folds) else { return };
    let off = if target.start == row.start {
        if n < 0 {
            row.start
        } else {
            row.end
        }
    } else {
        rows::offset_at_cell(&doc.buf, &target, cell).unwrap_or(target.start)
    };
    doc.set_caret(off, extend);
    doc.view.desired_cell = Some(cell);
    if n.unsigned_abs() > 1 {
        // Page movement scrolls the view by the same amount.
        if let Ok(top) = rows::row_at(&doc.buf, doc.view.top, wrap) {
            if let Ok(t) = super::folds::step_rows(&doc.buf, top, n, wrap, &doc.view.folds) {
                doc.view.top = t.start;
            }
        }
    }
}

fn smart_home(doc: &Document, wrap: Option<usize>) -> u64 {
    let c = doc.view.caret;
    let Ok(row) = rows::row_at(&doc.buf, c, wrap) else { return c };
    let mut first = row.start;
    if let Some(bytes) = doc.buf.read(row.start..row.end.min(row.start + 4096)) {
        rows::for_each_cell(&doc.buf.codec, &bytes, row.start, |x| {
            if x.ch == ' ' || x.ch == '\t' {
                first = x.off + x.len as u64;
                true
            } else {
                false
            }
        });
    }
    let first = first.max(doc.min_caret());
    if c == first {
        row.start.max(doc.min_caret())
    } else {
        first
    }
}

fn handle_key(doc: &mut Document, key: Key, m: Modifiers, wrap: Option<usize>) {
    let shift = m.shift;
    let cmd = m.command;
    let page = doc.view.rows_on_screen.saturating_sub(1).max(1) as i64;
    match key {
        Key::ArrowLeft | Key::ArrowRight => {
            let right = key == Key::ArrowRight;
            if !shift && doc.has_selection() && !cmd {
                let (s, e) = doc.selection();
                doc.set_caret(if right { e } else { s }, false);
            } else {
                let c = move_horizontal(doc, wrap, right, cmd);
                doc.set_caret(c, shift);
            }
            doc.view.desired_cell = None;
        }
        Key::ArrowUp => move_vertical(doc, -1, shift, wrap),
        Key::ArrowDown => move_vertical(doc, 1, shift, wrap),
        Key::PageUp => move_vertical(doc, -page, shift, wrap),
        Key::PageDown => move_vertical(doc, page, shift, wrap),
        Key::Home => {
            let c = if cmd { doc.min_caret() } else { smart_home(doc, wrap) };
            doc.set_caret(c, shift);
            doc.view.desired_cell = None;
        }
        Key::End => {
            let c = if cmd {
                doc.buf.len()
            } else {
                rows::row_at(&doc.buf, doc.view.caret, wrap).map(|r| r.end).unwrap_or(doc.view.caret)
            };
            doc.set_caret(c, shift);
            doc.view.desired_cell = None;
        }
        Key::Backspace if doc.editable() => {
            if cmd && !doc.has_selection() {
                let c = move_horizontal(doc, wrap, false, true);
                doc.view.anchor = c;
                doc.delete_selection();
            } else {
                doc.backspace();
            }
        }
        Key::Delete if doc.editable() => {
            if cmd && !doc.has_selection() {
                let c = move_horizontal(doc, wrap, true, true);
                doc.view.anchor = c;
                doc.delete_selection();
            } else {
                doc.delete_forward();
            }
        }
        Key::Enter if doc.editable() => doc.newline(),
        Key::Tab if doc.editable() && !shift && !cmd => doc.insert_text("\t"),
        Key::A if cmd => {
            let len = doc.buf.len();
            doc.view.anchor = doc.min_caret();
            doc.view.caret = len;
        }
        Key::Z if cmd => {
            if shift {
                doc.redo()
            } else {
                doc.undo()
            }
        }
        Key::Y if cmd => doc.redo(),
        Key::K if cmd && shift => doc.delete_line(),
        Key::Escape => {
            let c = doc.view.caret;
            doc.view.anchor = c;
        }
        _ => {}
    }
}

fn ensure_caret_visible(doc: &mut Document, wrap: Option<usize>, center: bool, m: Metrics, text_w: f32) -> Result<(), Pending> {
    let n = doc.view.rows_on_screen.max(1);
    let buf = &doc.buf;
    let crow = rows::row_at(buf, doc.view.caret, wrap)?;
    let top_row = rows::row_at(buf, doc.view.top, wrap)?;
    if center {
        doc.view.top = super::folds::step_rows(buf, crow, -((n / 2) as i64), wrap, &doc.view.folds)?.start;
    } else if crow.start < top_row.start {
        doc.view.top = crow.start;
    } else {
        let mut r = top_row;
        let mut visible = r.start == crow.start;
        for _ in 1..n {
            if visible {
                break;
            }
            match super::folds::next_row(buf, &r, wrap, &doc.view.folds)? {
                Some(x) => {
                    r = x;
                    visible = r.start == crow.start;
                }
                None => break,
            }
        }
        if !visible {
            doc.view.top = super::folds::step_rows(buf, crow, -((n as i64) - 1), wrap, &doc.view.folds)?.start;
        }
    }
    if h_scroll(&doc.view) {
        let x = rows::cell_of_offset(buf, &crow, doc.view.caret)? as f32 * m.cw;
        if x < doc.view.scroll_x {
            doc.view.scroll_x = (x - 4.0 * m.cw).max(0.0);
        } else if x > doc.view.scroll_x + text_w - 2.0 * m.cw {
            doc.view.scroll_x = x - text_w + 6.0 * m.cw;
        }
    }
    Ok(())
}