bigtext 0.13.0

Free editor for huge text and log files (1-50+ GB): opens them without loading them into memory, 2.5 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
//! An open document: text buffer, undo history, view state and its background jobs.

use std::path::PathBuf;
use std::sync::Arc;
use std::time::{Duration, Instant};

use bigtext::encoding::{Detected, LineEnding};
use bigtext::file::{self, Source};
use bigtext::index::{self, LineIndex};
use bigtext::jobs::{CancelToken, Waker};
use bigtext::text::rows;
use bigtext::text::{Swap, TextBuf};

/// Line commands (duplicate/delete line) scan at most this far on the UI thread; longer lines
/// can still be selected and edited.
const LINE_CMD_LIMIT: u64 = 8 * 1024 * 1024;
/// A selection and the document version: (start, end, version).
type SelKey = (u64, u64, u64);

/// Characters of a selection are counted (on the UI thread) up to this size.
pub const SEL_CHARS_MAX: u64 = 4 * 1024 * 1024;

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum EditKind {
    Typing,
    Delete,
    Other,
}

pub struct UndoGroup {
    pub swaps: Vec<Swap>,
    pub sel_before: (u64, u64),
    pub sel_after: (u64, u64),
    pub kind: EditKind,
    pub at: Instant,
    /// Content state ids before and after this group (see `Document::is_modified`).
    pub state_before: u64,
    pub state_after: u64,
}

#[derive(Clone, Debug, PartialEq)]
pub enum DocState {
    Loading,
    Ready,
    /// Saving/replacing: the source is released while the file is being swapped on disk.
    Finalizing(String),
    Failed(String),
}

#[derive(Clone, Debug, PartialEq)]
pub enum Banner {
    Binary,
    ChangedOnDisk {
        deleted: bool,
        grown: bool,
    },
    /// Following went on in a new file after the log was rotated (to this file, when known).
    Rotated(Option<std::path::PathBuf>),
    Info(String),
    Error(String),
}

/// Per-document view state (positions are byte offsets in the document).
pub struct ViewState {
    /// Folded values (sorted, not overlapping), for the version `folds_version`.
    pub folds: Vec<crate::view::folds::Fold>,
    pub folds_version: u64,
    /// View → Wrap at: the column rows wrap at (`None`: the pane's width).
    pub wrap_column: Option<usize>,
    /// What the last frame gave screen readers (tests read it).
    pub a11y_last: Option<String>,
    pub top: u64,
    pub scroll_x: f32,
    pub caret: u64,
    pub anchor: u64,
    pub desired_cell: Option<u32>,
    pub wrap: bool,
    pub rows_on_screen: usize,
    pub text_cols: usize,
    pub max_cells: u32,
    pub scroll_to_caret: bool,
    pub center_caret: bool,
    /// Jumps so far (Go to, F3, a click in a list…), for Back / Forward.
    pub jumps: u64,
    pub pending_goto_line: Option<(u64, u64)>,
    pub wheel_rem: f32,
    pub hex_top: u64,
    pub first_paint: Option<Instant>,
    pub dragging: bool,
    pub width_cache: std::collections::HashMap<u64, u32>,
    pub width_cache_version: u64,
    /// Geometry of the last painted text area (hit testing in the self-test).
    pub text_rect: Option<egui::Rect>,
    pub cell: egui::Vec2,
    pub scroll_marks: crate::view::text_view::ScrollMarks,
    /// Highlighting state at the start of rows seen so far.
    pub hl: crate::view::hl_rows::HlCache,
    /// Column (block) selection, made with Alt+drag.
    pub block: Option<crate::view::block::Block>,
    pub block_drag: bool,
    /// More cursors (anchor, caret) besides `anchor`/`caret` (Ctrl+D, Alt+click).
    pub extra: Vec<(u64, u64)>,
    /// The document version the extra cursors belong to; any other edit drops them.
    pub extra_version: u64,
    /// The selection before an Alt+press, for adding a cursor when it turns out to be a click.
    pub alt_prev: Option<(u64, u64)>,
    /// The indentation step of code (cells) guessed from the start of the file, and the version
    /// it was guessed for.
    pub indent_unit: Option<(u64, u32)>,
    /// Indent guides painted in the last frame (tests read it).
    pub guides: usize,
    /// What an input method is composing, drawn at the caret.
    pub preedit: crate::view::text_view::Preedit,
    /// Where the input method's window was asked to go in the last frame (tests read it).
    pub ime_rect: Option<egui::Rect>,
}

impl ViewState {
    /// Centres the caret after a jump and counts the jump.
    pub fn center(&mut self) {
        self.center_caret = true;
        self.jumps += 1;
    }
}

impl Default for ViewState {
    fn default() -> Self {
        ViewState {
            jumps: 0,
            top: 0,
            scroll_x: 0.0,
            caret: 0,
            anchor: 0,
            desired_cell: None,
            wrap: false,
            rows_on_screen: 40,
            text_cols: 120,
            max_cells: 0,
            scroll_to_caret: false,
            center_caret: false,
            pending_goto_line: None,
            wheel_rem: 0.0,
            hex_top: 0,
            first_paint: None,
            dragging: false,
            width_cache: std::collections::HashMap::new(),
            width_cache_version: 0,
            text_rect: None,
            cell: egui::Vec2::ZERO,
            scroll_marks: Default::default(),
            hl: Default::default(),
            block: None,
            block_drag: false,
            extra: Vec::new(),
            extra_version: 0,
            alt_prev: None,
            a11y_last: None,
            wrap_column: None,
            folds: Vec::new(),
            folds_version: 0,
            indent_unit: None,
            guides: 0,
            preedit: Default::default(),
            ime_rect: None,
        }
    }
}

/// The highlighting checkpoints being found for a document (`BigTextApp::hl_tick` starts it).
pub struct HlJob {
    pub version: u64,
    pub lang: crate::view::highlight::Lang,
    pub data: std::sync::Arc<std::sync::Mutex<std::sync::Arc<crate::view::hl_rows::HlIndex>>>,
    pub cancel: bigtext::jobs::CancelToken,
}

pub struct Document {
    pub id: u64,
    pub path: Option<PathBuf>,
    pub title: String,
    pub buf: TextBuf,
    pub line_ending: LineEnding,
    pub eol_on_save: Option<LineEnding>,
    /// With a conversion to LF or CRLF, a CR without LF after it becomes a line break too.
    pub eol_lone_cr: bool,
    pub looks_binary: bool,
    pub read_only: bool,
    pub hex: bool,
    pub undo: Vec<UndoGroup>,
    pub redo: Vec<UndoGroup>,
    pub version: u64,
    pub saved_version: u64,
    /// Identifies the current content; undoing back to the saved state clears "modified".
    content_state: u64,
    saved_content_state: u64,
    next_content_state: u64,
    pub view: ViewState,
    pub state: DocState,
    pub banner: Option<Banner>,
    pub index_cancel: CancelToken,
    pub watch_cancel: CancelToken,
    pub opened_at: Instant,
    pub open_elapsed: Option<Duration>,
    pub follow: bool,
    pub results: Option<super::search_panel::SearchResults>,
    pub filter: Option<super::filter_panel::FilterResults>,
    pub find_job: Option<super::search_panel::FindJob>,
    pub save_job: Option<super::ops::SaveJob>,
    pub close_after_save: bool,
    pub reload_prefix: Option<Vec<u64>>,
    /// A reload is on its way (follow switching to chunked reads, a rotation).
    pub reloading: bool,
    /// After the reload, put the caret at the end (a rotated log).
    pub reload_to_end: bool,
    /// How often the followed file was rotated.
    pub rotations: u32,
    /// The banner to show once the reload is done.
    pub banner_after_reload: Option<Banner>,
    /// Bookmarked line starts (sorted byte offsets).
    pub bookmarks: Vec<u64>,
    /// Offsets of the differences found by File → Compare (marked on the scrollbar).
    pub diff_marks: Vec<u64>,
    /// The compressed file this document is an unpacked copy of (`path` is the temporary copy).
    pub unpacked_from: Option<PathBuf>,
    /// The file of the archive `unpacked_from` this is a copy of.
    pub member: Option<String>,
    /// `path` is a temporary copy (unpacked archive, standard input): Save means Save As, and
    /// the copy is deleted when the tab closes.
    pub temporary: bool,
    /// A file on an SSH server read in place: searches run there with grep.
    pub remote_ssh: Option<bigtext::remote::SshFile>,
    /// Progress and cancellation of the open job (shown while a compressed file is unpacked).
    pub unpacking: Option<(bigtext::jobs::Progress, CancelToken)>,
    /// The rest of an unpacked copy that is open already is still being unpacked.
    pub growing: Option<(bigtext::jobs::Progress, CancelToken)>,
    /// Character count of the selection, cached.
    sel_chars: std::cell::Cell<Option<(SelKey, Option<u64>)>>,
    /// Second pane of a split view (shares caret and selection, scrolls independently).
    pub split: Option<PaneView>,
    pub active_pane: u8,
    /// Syntax highlighting override (None = from the file extension).
    pub lang: Option<crate::view::highlight::Lang>,
    /// Format guessed from the first lines, for files whose extension says nothing.
    pub sniffed_lang: crate::view::highlight::Lang,
    /// The file labels of a merged log (File → Merge logs by time), painted in their colours.
    pub merged: Option<super::merge_logs::MergeTags>,
    /// Time histogram (Search → Time histogram).
    pub timeline: Option<super::timeline::TimelineResults>,
    pub gaps: Option<super::gaps_panel::GapsResults>,
    pub patterns: Option<super::patterns_window::PatternsResults>,
    /// Web log report (Search → Web log report…).
    pub log_report: Option<super::log_report::ReportResults>,
    /// View → Alerts on new lines: the patterns and what matched.
    pub alerts: Option<super::alerts::Alerts>,
    /// File → SQL dump tables: the tables of the dump.
    pub sql_dump: Option<super::sql_dump::DumpResults>,
    /// Where the records of a CSV shown as a table start (quoted fields may hold line breaks).
    pub records: Option<crate::view::table_view::RecordsJob>,
    /// Highlighting checkpoints of a large document (see `HlIndex`).
    pub hl_index: Option<HlJob>,
    pub problems: Option<super::problems_panel::ProblemsResults>,
    pub chart: Option<super::column_chart::ChartResults>,
    pub json_check: Option<super::json_validate::JsonCheckResults>,
    pub json_diff: Option<super::json_diff_panel::JsonDiffResults>,
    /// Outline for View → JSON structure.
    pub json: Option<super::json_panel::JsonTree>,
    /// Pinned tabs stay first and are not closed by "Close other tabs".
    pub pinned: bool,
    /// A session's filter, run once the document has opened.
    pub pending_filter: Option<super::sessions::SavedFilter>,
    /// Shown as a table (CSV / TSV); on by default for .csv and .tsv files.
    pub table: bool,
    pub table_state: crate::view::table_view::TableState,
    /// Position to restore once the file has opened (session restore, diff jumps).
    pub restore: Option<Restore>,
    /// What was remembered for the file, put back once it has opened.
    pub pending_opts: Option<super::extras::FileOpts>,
    /// The JSON path at the caret (status bar).
    pub json_crumb: Option<super::json_crumb::JsonCrumb>,
    /// View → Link scrolling: the tab that follows this one.
    pub link: Option<super::time_link::Link>,
    /// The line Go to this time in all tabs moved to (with the version it is for).
    pub time_mark: Option<(u64, u64)>,
    /// The encoding chosen with File → Reopen with encoding (`None`: detected).
    pub forced_enc: Option<bigtext::encoding::Encoding>,
    /// Read-only because of the file (its attribute, an unpacked copy), not by choice.
    pub file_read_only: bool,
    last_indexed: u64,
}

#[derive(Clone, Debug, Default)]
pub struct Restore {
    pub caret: u64,
    pub top: u64,
    pub wrap: bool,
    pub bookmarks: Vec<u64>,
    pub line: Option<u64>,
    /// Go to the end (follow mode from the command line).
    pub end: bool,
    /// Select this range (a match from Find in files).
    pub select: Option<(u64, u64)>,
    /// Run this filter (a session's).
    pub filter: Option<super::sessions::SavedFilter>,
}

/// Scroll state of the secondary split pane.
#[derive(Clone, Debug, Default)]
pub struct PaneView {
    pub top: u64,
    pub scroll_x: f32,
    pub wheel_rem: f32,
    pub rows_on_screen: usize,
    pub text_cols: usize,
    pub text_rect: Option<egui::Rect>,
}

impl PaneView {
    /// Exchanges the scroll state with the document's primary view state.
    pub fn swap_with(&mut self, v: &mut ViewState) {
        std::mem::swap(&mut self.top, &mut v.top);
        std::mem::swap(&mut self.scroll_x, &mut v.scroll_x);
        std::mem::swap(&mut self.wheel_rem, &mut v.wheel_rem);
        std::mem::swap(&mut self.rows_on_screen, &mut v.rows_on_screen);
        std::mem::swap(&mut self.text_cols, &mut v.text_cols);
        std::mem::swap(&mut self.text_rect, &mut v.text_rect);
    }
}

/// .csv and .tsv files open as a table.
pub fn table_by_default(path: &std::path::Path) -> bool {
    matches!(
        crate::view::highlight::Lang::from_path(Some(path)),
        crate::view::highlight::Lang::Csv(_)
    )
}

impl Document {
    /// Puts back what was remembered for the file, once it has opened.
    pub fn apply_opts(&mut self, o: super::extras::FileOpts) {
        self.forced_enc = o.enc;
        self.lang = o.lang;
        self.table = o.table;
        self.hex = o.hex;
        self.read_only |= o.read_only;
        self.view.wrap = o.wrap;
        self.table_state.pending = o.layout;
        if o.follow && !self.follow {
            self.follow = true;
            let len = self.buf.len();
            self.set_caret(len, false);
            if let Some(r) = self
                .restore
                .as_mut()
                .filter(|r| r.line.is_none() && r.select.is_none())
            {
                r.end = true;
            }
        }
    }

    pub fn loading(id: u64, path: PathBuf) -> Document {
        let title = path
            .file_name()
            .map(|n| n.to_string_lossy().into_owned())
            .unwrap_or_else(|| file::display_path(&path));
        let table = table_by_default(&path);
        let src = Arc::new(Source::empty());
        let idx = LineIndex::new(0);
        Document {
            id,
            path: Some(path),
            title,
            buf: TextBuf::new(src, idx, bigtext::encoding::Codec::utf8()),
            line_ending: LineEnding::Unknown,
            eol_on_save: None,
            eol_lone_cr: false,
            looks_binary: false,
            read_only: false,
            hex: false,
            undo: Vec::new(),
            redo: Vec::new(),
            version: 0,
            saved_version: 0,
            content_state: 0,
            saved_content_state: 0,
            next_content_state: 1,
            view: ViewState::default(),
            state: DocState::Loading,
            banner: None,
            index_cancel: CancelToken::new(),
            watch_cancel: CancelToken::new(),
            opened_at: Instant::now(),
            open_elapsed: None,
            follow: false,
            results: None,
            filter: None,
            find_job: None,
            save_job: None,
            close_after_save: false,
            reload_prefix: None,
            reloading: false,
            reload_to_end: false,
            rotations: 0,
            banner_after_reload: None,
            bookmarks: Vec::new(),
            diff_marks: Vec::new(),
            unpacked_from: None,
            member: None,
            temporary: false,
            remote_ssh: None,
            unpacking: None,
            growing: None,
            sel_chars: std::cell::Cell::new(None),
            split: None,
            active_pane: 0,
            lang: None,
            sniffed_lang: crate::view::highlight::Lang::Plain,
            merged: None,
            timeline: None,
            gaps: None,
            patterns: None,
            log_report: None,
            alerts: None,
            sql_dump: None,
            records: None,
            hl_index: None,
            problems: None,
            chart: None,
            json_check: None,
            json_diff: None,
            json: None,
            pinned: false,
            pending_filter: None,
            table,
            table_state: Default::default(),
            restore: None,
            pending_opts: None,
            link: None,
            time_mark: None,
            json_crumb: None,
            forced_enc: None,
            file_read_only: false,
            last_indexed: 0,
        }
    }

    pub fn untitled(id: u64, n: usize) -> Document {
        let mut d = Document::loading(id, PathBuf::new());
        d.path = None;
        d.title = super::i18n::trf("Untitled-{n}", &[("n", &n.to_string())]);
        d.state = DocState::Ready;
        d
    }

    /// Installs a freshly opened source (initial open, reload or after save).
    /// Puts back unsaved edits from a recovery journal: the document is modified, with no undo.
    pub fn restore_edits(&mut self, buf: TextBuf) {
        self.buf = buf;
        self.undo.clear();
        self.redo.clear();
        self.version += 1;
        self.content_state = self.next_content_state;
        self.next_content_state += 1;
        self.view.caret = self.view.caret.min(self.buf.len());
        self.view.anchor = self.view.caret;
    }

    pub fn install(
        &mut self,
        source: Arc<Source>,
        det: Detected,
        prefix: Option<Vec<u64>>,
        waker: Waker,
    ) {
        self.index_cancel.cancel();
        self.index_cancel = CancelToken::new();
        source.set_waker(waker.clone());
        let index = match prefix {
            Some(p) => LineIndex::with_prefix(source.len(), p),
            None => LineIndex::new(source.len()),
        };
        // A remote file read in parts is not indexed: that would download all of it. Line
        // numbers past the prefix it came with are estimates.
        if !index.is_done() && !source.is_remote() {
            index::spawn_indexer(
                source.clone(),
                det.codec,
                index.clone(),
                self.index_cancel.clone(),
                waker,
            );
        }
        self.buf = TextBuf::new(source, index, det.codec);
        self.line_ending = det.line_ending;
        self.looks_binary = det.looks_binary;
        if det.looks_binary && self.banner.is_none() {
            self.banner = Some(Banner::Binary);
        }
        self.undo.clear();
        self.redo.clear();
        self.version += 1;
        self.saved_version = self.version;
        self.content_state = self.next_content_state;
        self.saved_content_state = self.content_state;
        self.next_content_state += 1;
        self.last_indexed = 0;
        let min = self.min_caret();
        self.view.caret = self.view.caret.clamp(min, self.buf.len());
        self.view.anchor = self.view.caret;
        self.view.top = self.view.top.min(self.buf.len());
        let head = self
            .buf
            .read(0..self.buf.len().min(16 * 1024))
            .map(|b| self.buf.codec.decode_lossy(&b))
            .unwrap_or_default();
        self.sniffed_lang = crate::view::highlight::Lang::sniff(&head);
        self.state = DocState::Ready;
    }

    /// The format highlighting uses when none was chosen: from the extension, otherwise from
    /// the content.
    pub fn auto_lang(&self) -> crate::view::highlight::Lang {
        match crate::view::highlight::Lang::from_path(self.path.as_deref()) {
            crate::view::highlight::Lang::Plain => self.sniffed_lang,
            l => l,
        }
    }

    /// The format the document is highlighted as.
    /// The highlighting checkpoints for `lang`, when they belong to this version.
    pub fn hl_index(
        &self,
        lang: crate::view::highlight::Lang,
    ) -> Option<std::sync::Arc<crate::view::hl_rows::HlIndex>> {
        let j = self.hl_index.as_ref()?;
        (j.version == self.version && j.lang == lang).then(|| j.data.lock().unwrap().clone())
    }

    pub fn effective_lang(&self) -> crate::view::highlight::Lang {
        self.lang.unwrap_or_else(|| self.auto_lang())
    }

    pub fn is_modified(&self) -> bool {
        self.content_state != self.saved_content_state
    }

    pub fn is_ready(&self) -> bool {
        self.state == DocState::Ready
    }

    pub fn editable(&self) -> bool {
        self.is_ready() && !self.read_only && !self.hex && self.save_job.is_none()
    }

    /// Cancels every background job that holds a snapshot of the source.
    pub fn cancel_jobs(&mut self) {
        self.index_cancel.cancel();
        if let Some(r) = &self.results {
            r.cancel.cancel();
        }
        if let Some(r) = &self.filter {
            r.cancel.cancel();
        }
        if let Some(t) = &self.timeline {
            t.cancel.cancel();
        }
        if let Some(g) = &self.gaps {
            g.cancel.cancel();
        }
        if let Some(p) = &self.patterns {
            p.cancel.cancel();
        }
        if let Some(r) = &self.log_report {
            r.cancel.cancel();
        }
        if let Some(r) = &self.sql_dump {
            r.cancel.cancel();
        }
        if let Some(r) = &self.records {
            r.cancel.cancel();
        }
        if let Some(h) = &self.hl_index {
            h.cancel.cancel();
        }
        if let Some(p) = &self.problems {
            p.cancel.cancel();
        }
        if let Some(c) = &self.chart {
            c.cancel.cancel();
        }
        if let Some(j) = &self.json_check {
            j.cancel.cancel();
        }
        if let Some(j) = &self.json_diff {
            j.cancel.cancel();
        }
        if let Some((_, c)) = &self.unpacking {
            c.cancel();
        }
        if let Some((_, c)) = &self.growing {
            c.cancel();
        }
        if let Some(j) = self.find_job.take() {
            j.cancel.cancel();
        }
    }

    /// Re-attaches the buffer (keeping all edits) to a byte-identical reopened source.
    pub fn rebind(&mut self, source: Arc<Source>, waker: Waker) {
        self.index_cancel = CancelToken::new();
        source.set_waker(waker.clone());
        let index = LineIndex::new(source.len());
        if !source.is_remote() {
            index::spawn_indexer(
                source.clone(),
                self.buf.codec,
                index.clone(),
                self.index_cancel.clone(),
                waker,
            );
        }
        self.buf = self.buf.with_source(source, index);
        self.last_indexed = 0;
        self.state = DocState::Ready;
    }

    pub fn min_caret(&self) -> u64 {
        (self.buf.codec.bom_len as u64).min(self.buf.len())
    }

    pub fn selection(&self) -> (u64, u64) {
        let (a, b) = (self.view.anchor, self.view.caret);
        (a.min(b), a.max(b))
    }

    pub fn has_selection(&self) -> bool {
        self.view.anchor != self.view.caret
    }

    /// An offset moved into the text and onto a character boundary.
    pub fn fit_caret(&self, off: u64) -> u64 {
        let off = off.clamp(self.min_caret(), self.buf.len());
        self.buf.snap_char(off).max(self.min_caret())
    }

    pub fn set_caret(&mut self, off: u64, extend: bool) {
        let off = self.fit_caret(off);
        self.view.caret = off;
        if !extend {
            self.view.anchor = off;
        }
        self.view.scroll_to_caret = true;
    }

    pub fn select(&mut self, start: u64, end: u64) {
        self.view.anchor = self.fit_caret(start);
        self.view.caret = self.fit_caret(end);
        self.view.scroll_to_caret = true;
        self.view.desired_cell = None;
    }

    /// Called every frame: lets line counts catch up with the background indexer.
    pub fn tick(&mut self) -> bool {
        if self.is_ready()
            && (self.buf.index.failed() || self.buf.source.has_io_error())
            && self.banner.is_none()
        {
            self.banner = Some(Banner::Error(super::i18n::tr("Reading the file failed (was it removed, truncated or is the drive unavailable?). Display may be incomplete.").into()));
        }
        let idx = self.buf.index.indexed_bytes();
        let mut changed = false;
        if idx != self.last_indexed {
            self.last_indexed = idx;
            if self.buf.has_inexact() {
                changed |= self.buf.refresh_counts(512);
            }
        }
        changed
    }

    // ------------------------------------------------------------------------------------------
    // Editing.

    fn push_undo(
        &mut self,
        swaps: Vec<Swap>,
        sel_before: (u64, u64),
        sel_after: (u64, u64),
        kind: EditKind,
    ) {
        self.redo.clear();
        let now = Instant::now();
        let state_before = self.content_state;
        self.content_state = self.next_content_state;
        self.next_content_state += 1;
        if let Some(last) = self.undo.last_mut() {
            let coalesce = kind != EditKind::Other
                && last.kind == kind
                && now.duration_since(last.at) < Duration::from_millis(1500)
                && last.sel_after == sel_before;
            if coalesce {
                last.swaps.extend(swaps);
                last.sel_after = sel_after;
                last.at = now;
                last.state_after = self.content_state;
                return;
            }
        }
        self.undo.push(UndoGroup {
            swaps,
            sel_before,
            sel_after,
            kind,
            at: now,
            state_before,
            state_after: self.content_state,
        });
        if self.undo.len() > 10_000 {
            self.undo.remove(0);
        }
    }

    /// Replaces `range` with `bytes` (already encoded) and moves the caret after the insertion.
    pub fn edit(&mut self, range: std::ops::Range<u64>, bytes: &[u8], kind: EditKind) {
        if !self.editable() {
            return;
        }
        let sel_before = (self.view.anchor, self.view.caret);
        let swap = self.buf.replace(range.clone(), bytes);
        self.shift_bookmarks(range.clone(), bytes.len() as u64);
        let caret = range.start.min(self.buf.len()) + bytes.len() as u64;
        self.version += 1;
        self.view.anchor = caret;
        self.view.caret = caret;
        self.view.desired_cell = None;
        self.view.scroll_to_caret = true;
        self.push_undo(vec![swap], sel_before, (caret, caret), kind);
    }

    /// Records an externally built swap (batch replace, duplicate line) as one undo step.
    pub fn record(&mut self, swap: Swap, sel_after: (u64, u64)) {
        let sel_before = (self.view.anchor, self.view.caret);
        self.clamp_bookmarks();
        self.version += 1;
        // A selection given from before a batch edit may now be past the end or inside a
        // character (a replacement of another length before it).
        let sel_after = (self.fit_caret(sel_after.0), self.fit_caret(sel_after.1));
        self.view.anchor = sel_after.0;
        self.view.caret = sel_after.1;
        self.view.scroll_to_caret = true;
        self.push_undo(vec![swap], sel_before, sel_after, EditKind::Other);
    }

    pub fn insert_text(&mut self, text: &str) {
        let (s, e) = self.selection();
        let bytes = self.buf.codec.encode(text);
        let kind = if text.chars().count() <= 2 && !text.contains('\n') {
            EditKind::Typing
        } else {
            EditKind::Other
        };
        self.edit(s..e, &bytes, kind);
    }

    pub fn delete_selection(&mut self) -> bool {
        let (s, e) = self.selection();
        if s == e {
            return false;
        }
        self.edit(s..e, &[], EditKind::Other);
        true
    }

    /// `off` moved off the middle of a CRLF pair: past it going right, before it going left.
    pub fn off_crlf(&self, off: u64, right: bool) -> u64 {
        let cr = self.buf.codec.cr_unit().len() as u64;
        let nl = self.buf.codec.nl_unit().len() as u64;
        if off < cr || off + nl > self.buf.len() {
            return off;
        }
        match self.crlf_before(off + nl) {
            Some(n) if n == cr + nl && right => off + nl,
            Some(n) if n == cr + nl => off - cr,
            _ => off,
        }
    }

    /// Length of a CRLF pair ending at `off`, if any.
    pub fn crlf_before(&self, off: u64) -> Option<u64> {
        let codec = self.buf.codec;
        let cr = codec.cr_unit();
        let nl = codec.nl_unit();
        let n = (cr.len() + nl.len()) as u64;
        if off < n || codec.nl != bigtext::encoding::NlByte::Lf {
            return None;
        }
        let b = self.buf.read(off - n..off)?;
        (b.starts_with(cr) && b[cr.len()..] == *nl).then_some(n)
    }

    pub fn backspace(&mut self) {
        if self.delete_selection() {
            return;
        }
        let c = self.view.caret;
        if c <= self.min_caret() {
            return;
        }
        let start = match self.crlf_before(c) {
            Some(n) => c - n,
            None => self.buf.prev_char(c),
        };
        self.edit(start.max(self.min_caret())..c, &[], EditKind::Delete);
    }

    pub fn delete_forward(&mut self) {
        if self.delete_selection() {
            return;
        }
        let c = self.view.caret;
        if c >= self.buf.len() {
            return;
        }
        let mut end = self.buf.next_char(c);
        let cr = self.buf.codec.cr_unit().len() as u64;
        let nl = self.buf.codec.nl_unit().len() as u64;
        if let Some(n) = self.crlf_before((c + cr + nl).min(self.buf.len())) {
            if c + n == (c + cr + nl).min(self.buf.len()) {
                end = c + n;
            }
        }
        let sel = (self.view.anchor, self.view.caret);
        let swap = self.buf.replace(c..end, &[]);
        self.version += 1;
        self.view.scroll_to_caret = true;
        self.push_undo(vec![swap], sel, sel, EditKind::Delete);
    }

    /// Keeps bookmarks on their lines across an edit of `range` replaced by `inserted` bytes.
    fn shift_bookmarks(&mut self, range: std::ops::Range<u64>, inserted: u64) {
        if self.bookmarks.is_empty() {
            return;
        }
        let removed = range.end - range.start;
        for b in &mut self.bookmarks {
            if *b >= range.end && (*b > range.start || removed > 0) {
                *b = *b - removed + inserted;
            } else if *b > range.start {
                *b = range.start;
            }
        }
        self.bookmarks.dedup();
    }

    /// Drops bookmarks that no longer fit (after batch edits or undo/redo).
    fn clamp_bookmarks(&mut self) {
        let len = self.buf.len();
        self.bookmarks.retain(|&b| b <= len);
    }

    /// Toggles a bookmark on the line containing the caret.
    pub fn toggle_bookmark(&mut self) {
        let Some((ls, _, _)) = self.line_bounds(self.view.caret, LINE_CMD_LIMIT) else {
            return;
        };
        match self.bookmarks.binary_search(&ls) {
            Ok(i) => {
                self.bookmarks.remove(i);
            }
            Err(i) => self.bookmarks.insert(i, ls),
        }
    }

    /// Moves to the next (or previous) bookmark, wrapping around.
    /// Goes to the next (or previous) difference of a comparison, around the ends; returns its
    /// number and the count.
    pub fn goto_diff(&mut self, forward: bool) -> Option<(usize, usize)> {
        let n = self.diff_marks.len();
        if n == 0 {
            return None;
        }
        let here = self
            .line_bounds(self.view.caret, 64 * 1024)
            .map(|b| b.0)
            .unwrap_or(self.view.caret);
        let i = if forward {
            self.diff_marks.iter().position(|&o| o > here).unwrap_or(0)
        } else {
            self.diff_marks
                .iter()
                .rposition(|&o| o < here)
                .unwrap_or(n - 1)
        };
        let len = self.buf.len();
        self.set_caret(self.diff_marks[i].min(len).max(self.min_caret()), false);
        self.view.center();
        Some((i + 1, n))
    }

    pub fn goto_bookmark(&mut self, forward: bool) {
        if self.bookmarks.is_empty() {
            return;
        }
        let c = self.view.caret;
        let line_start = self
            .line_bounds(c, LINE_CMD_LIMIT)
            .map(|b| b.0)
            .unwrap_or(c);
        let target = if forward {
            self.bookmarks
                .iter()
                .copied()
                .find(|&b| b > line_start)
                .unwrap_or(self.bookmarks[0])
        } else {
            self.bookmarks
                .iter()
                .rev()
                .copied()
                .find(|&b| b < line_start)
                .unwrap_or(*self.bookmarks.last().unwrap())
        };
        self.set_caret(target, false);
        self.view.center();
    }

    pub fn undo(&mut self) {
        // Not while a save runs: the saved file replaces the buffer when it ends.
        if !self.is_ready() || self.save_job.is_some() {
            return;
        }
        if let Some(g) = self.undo.pop() {
            for s in g.swaps.iter().rev() {
                self.buf.apply(s, false);
            }
            self.version += 1;
            self.view.anchor = self.fit_caret(g.sel_before.0);
            self.view.caret = self.fit_caret(g.sel_before.1);
            self.view.scroll_to_caret = true;
            self.content_state = g.state_before;
            self.redo.push(g);
            self.clamp_bookmarks();
        }
    }

    pub fn redo(&mut self) {
        if !self.is_ready() || self.save_job.is_some() {
            return;
        }
        if let Some(g) = self.redo.pop() {
            for s in &g.swaps {
                self.buf.apply(s, true);
            }
            self.version += 1;
            self.view.anchor = self.fit_caret(g.sel_after.0);
            self.view.caret = self.fit_caret(g.sel_after.1);
            self.view.scroll_to_caret = true;
            self.content_state = g.state_after;
            self.undo.push(g);
            self.clamp_bookmarks();
        }
    }

    /// The word at the caret for decoding: the run of characters around it up to white space,
    /// quotes and angle brackets. `None` when there is none.
    pub fn token_at_caret(&self) -> Option<std::ops::Range<u64>> {
        let caret = self.view.caret;
        let (start, end, _) = self.line_bounds(caret, 64 * 1024)?;
        let bytes = self.buf.read(start..end)?;
        let text = self.buf.codec.decode_lossy(&bytes);
        if self.buf.codec.encode(&text) != *bytes {
            return None;
        }
        let at = self
            .buf
            .codec
            .decode_lossy(&bytes[..((caret.max(start) - start) as usize).min(bytes.len())])
            .len();
        let stop = |c: char| c.is_whitespace() || "\"'<>`".contains(c);
        let lo = text[..at]
            .rfind(stop)
            .map(|i| i + text[i..].chars().next().map_or(1, char::len_utf8))
            .unwrap_or(0);
        let hi = text[at..].find(stop).map(|i| at + i).unwrap_or(text.len());
        if lo >= hi {
            return None;
        }
        let enc = |s: &str| self.buf.codec.encode(s).len() as u64;
        Some(start + enc(&text[..lo])..start + enc(&text[..hi]))
    }

    /// Bounds of the real line containing `off`: (start, content_end, next_line_start).
    /// Scans at most `limit` bytes in each direction.
    pub fn line_bounds(&self, off: u64, limit: u64) -> Option<(u64, u64, u64)> {
        let codec = self.buf.codec;
        let unit = codec.unit() as u64;
        let len = self.buf.len();
        let lo = off.saturating_sub(limit);
        let lo = lo - lo % unit;
        let before = self.buf.read(lo..off)?;
        let start = match codec.rfind_nl(&before, lo) {
            Some(i) => lo + i as u64 + unit,
            // The first line starts after a byte order mark: it is not text, and a line
            // command (delete, duplicate, comment) must not take it along.
            None if lo == 0 => self.min_caret().min(off),
            None => return None,
        };
        let hi = (off + limit).min(len);
        let after = self.buf.read(off..hi)?;
        let (ce, next) = match codec.find_nl(&after, off) {
            Some(i) => {
                let nl = off + i as u64;
                let cr = codec.cr_unit();
                let mut ce = nl;
                if codec.nl == bigtext::encoding::NlByte::Lf
                    && i >= cr.len()
                    && &after[i - cr.len()..i] == cr
                {
                    ce -= cr.len() as u64;
                }
                (ce, nl + unit)
            }
            None if hi == len => (len, len),
            None => return None,
        };
        Some((start, ce, next))
    }

    /// Lines (and whether that count is exact), characters (for selections up to
    /// [`SEL_CHARS_MAX`]) and bytes of the selection. The character count is cached.
    pub fn selection_stats(&self) -> Option<(u64, bool, Option<u64>, u64)> {
        let (s, e) = self.selection();
        if s == e {
            return None;
        }
        let unit = self.buf.codec.unit() as u64;
        let (a, ea) = self.buf.line_of(s);
        // A selection that ends at a line start (a triple click) does not count that line.
        let (b, eb) = self.buf.line_of(e.saturating_sub(unit).max(s));
        let key = (s, e, self.version);
        let chars = match self.sel_chars.get() {
            Some((k, n)) if k == key => n,
            _ => {
                let n = (e - s <= SEL_CHARS_MAX)
                    .then(|| {
                        self.buf
                            .read(s..e)
                            .map(|bytes| self.buf.codec.decode_lossy(&bytes).chars().count() as u64)
                    })
                    .flatten();
                if n.is_some() {
                    self.sel_chars.set(Some((key, n)));
                }
                n
            }
        };
        Some((b - a + 1, ea && eb, chars, e - s))
    }

    /// Milliseconds between the timestamps of the first and the last selected line, when the
    /// selection spans lines that both start with a time.
    pub fn selection_time_delta(&self) -> Option<i64> {
        let (s, e) = self.selection();
        let e = e.saturating_sub(self.buf.codec.unit() as u64).max(s);
        let a = self.line_bounds(s, 64 * 1024)?.0;
        let b = self.line_bounds(e, 64 * 1024)?.0;
        if a == b {
            return None;
        }
        let (x, y) = (
            bigtext::timestamp::stamp_at(&self.buf, a)?,
            bigtext::timestamp::stamp_at(&self.buf, b)?,
        );
        (x.has_date == y.has_date).then_some(y.ms - x.ms)
    }

    /// Selects the whole line containing `off` including its line break (triple click).
    pub fn select_line(&mut self, off: u64) {
        if let Some((ls, _ce, next)) = self.line_bounds(off, LINE_CMD_LIMIT) {
            self.select(ls.max(self.min_caret()), next);
            self.view.scroll_to_caret = false;
        }
    }

    pub fn duplicate_line(&mut self) {
        if !self.editable() {
            return;
        }
        let (s, e) = self.selection();
        if s != e {
            let pieces = self.buf.copy_pieces(s..e);
            let swap = self.buf.insert_pieces(e, pieces);
            self.record(swap, (e, e + (e - s)));
            return;
        }
        let Some((ls, _ce, next)) = self.line_bounds(self.view.caret, LINE_CMD_LIMIT) else {
            self.banner = Some(Banner::Info(
                super::i18n::tr("Line is too long to duplicate").into(),
            ));
            return;
        };
        let caret = self.view.caret;
        let len = self.buf.len();
        if next == len && !self.ends_with_nl() {
            // Last line without newline: insert "\n" + line.
            let nl = self.buf.codec.line_break(self.line_ending);
            let mut pieces = self.buf.copy_pieces(ls..len);
            let sel = (self.view.anchor, self.view.caret);
            let s1 = self.buf.replace(len..len, &nl);
            let at = self.buf.len();
            let s2 = self.buf.insert_pieces(at, std::mem::take(&mut pieces));
            self.version += 1;
            let nc = caret + (len - ls) + nl.len() as u64;
            self.view.anchor = nc;
            self.view.caret = nc;
            self.push_undo(vec![s1, s2], sel, (nc, nc), EditKind::Other);
        } else {
            let pieces = self.buf.copy_pieces(ls..next);
            let swap = self.buf.insert_pieces(next, pieces);
            let nc = caret + (next - ls);
            self.record(swap, (nc, nc));
        }
    }

    fn ends_with_nl(&self) -> bool {
        let len = self.buf.len();
        let u = self.buf.codec.nl_unit();
        len >= u.len() as u64
            && self
                .buf
                .read(len - u.len() as u64..len)
                .is_some_and(|b| *b == *u)
    }

    pub fn delete_line(&mut self) {
        if !self.editable() {
            return;
        }
        let Some((ls, _ce, next)) = self.line_bounds(self.view.caret, LINE_CMD_LIMIT) else {
            self.banner = Some(Banner::Info(
                super::i18n::tr("Line is too long to delete with this command; select it instead")
                    .into(),
            ));
            return;
        };
        let start = if next == self.buf.len() && ls > 0 && !self.ends_with_nl() {
            // Last line: also remove the preceding line break.
            self.crlf_before(ls)
                .map(|n| ls - n)
                .unwrap_or(ls.saturating_sub(self.buf.codec.unit() as u64))
        } else {
            ls
        };
        self.edit(start..next, &[], EditKind::Other);
        let c = self.view.caret.min(self.buf.len());
        self.set_caret(c, false);
    }

    /// Edit → Toggle comment: the selected lines (or the caret's) commented out with `c`, or
    /// uncommented when they all are, as one undo step. Selected lines stay selected; a caret
    /// keeps its place in the text.
    pub fn toggle_comment(
        &mut self,
        c: crate::view::highlight::Comment,
    ) -> Result<(), &'static str> {
        if !self.editable() {
            return Err("The document is read-only (Edit → Read-only).");
        }
        let (s, e) = self.selection();
        // A selection ending at the start of a line leaves that line out.
        let last = if e > s {
            self.buf.prev_char(e).max(s)
        } else {
            e
        };
        let too_long = "Line is too long to comment with this command";
        let (ls, _, _) = self.line_bounds(s, LINE_CMD_LIMIT).ok_or(too_long)?;
        let (_, end, _) = self.line_bounds(last, LINE_CMD_LIMIT).ok_or(too_long)?;
        if end - ls > LINE_CMD_LIMIT {
            return Err("Select less text to comment it out (up to 8 MB).");
        }
        let codec = self.buf.codec;
        let bytes = self.buf.read(ls..end).ok_or("Could not read the text.")?;
        let text = codec.decode_lossy(&bytes);
        if codec.encode(&text) != *bytes {
            return Err("The lines contain bytes that are not valid in this encoding; commenting them would change them.");
        }
        let (new, changes) = crate::view::highlight::toggle_comment(&text, c);
        let out = codec.encode(&new);
        let caret = self.view.caret;
        self.edit(ls..end, &out, EditKind::Other);
        let new_end = ls + out.len() as u64;
        if s != e {
            self.select(ls, new_end);
            return Ok(());
        }
        // One line: the caret moves with the text after the change.
        let caret = match changes.first() {
            Some(&(at, removed, inserted)) => {
                let at_off = ls + codec.encode(&text[..at]).len() as u64;
                let rem = codec.encode(&text[at..at + removed]).len() as u64;
                let ins = codec.encode(&new[at..at + inserted]).len() as u64;
                if caret >= at_off + rem {
                    caret - rem + ins
                } else if caret > at_off {
                    at_off
                } else {
                    caret
                }
            }
            None => caret,
        };
        self.set_caret(caret.min(new_end), false);
        Ok(())
    }

    /// Leading whitespace of the line containing `off` (for auto-indent).
    pub fn indent_of_line(&self, off: u64) -> Vec<u8> {
        let Ok(seg) = rows::seg_containing(&self.buf, off) else {
            return Vec::new();
        };
        if !seg.line_start {
            return Vec::new();
        }
        let end = off.min(seg.content_end).min(seg.start + 256);
        let Some(b) = self.buf.read(seg.start..end) else {
            return Vec::new();
        };
        let codec = self.buf.codec;
        let mut out = Vec::new();
        let mut i = 0;
        while i < b.len() {
            let (c, l) = codec.decode_char(&b[i..]);
            if c == ' ' || c == '\t' {
                out.extend_from_slice(&b[i..i + l]);
                i += l;
            } else {
                break;
            }
        }
        out
    }

    pub fn newline(&mut self) {
        let mut bytes = self.buf.codec.line_break(self.line_ending);
        bytes.extend(self.indent_of_line(self.view.caret));
        let (s, e) = self.selection();
        self.edit(s..e, &bytes, EditKind::Other);
    }

    /// Selection text for the clipboard if it is small enough to copy synchronously.
    pub fn selection_text(&self, max: u64) -> Option<Result<String, u64>> {
        let (s, e) = self.selection();
        if s == e {
            return None;
        }
        if e - s > max {
            return Some(Err(e - s));
        }
        let b = self.buf.read(s..e)?;
        Some(Ok(self.buf.codec.decode_lossy(&b)))
    }

    /// Goes to 1-based `line`; estimated positions are refined once the index catches up.
    pub fn goto_line(&mut self, line: u64) {
        let target = line.max(1) - 1;
        let (off, exact) = match self.buf.line_start(target) {
            Some(x) => x,
            None => {
                let (n, _) = self.buf.line_count();
                self.buf
                    .line_start(n.saturating_sub(1))
                    .unwrap_or((self.buf.len(), false))
            }
        };
        let off = if exact {
            off
        } else {
            rows::seg_start(&self.buf, off).unwrap_or(off)
        };
        let off = off.max(self.min_caret());
        self.set_caret(off, false);
        self.view.center();
        self.view.pending_goto_line = if exact { None } else { Some((target, off)) };
    }

    /// Refines an estimated go-to once the index covers the requested line.
    pub fn refine_goto(&mut self) {
        if let Some((target, off)) = self.view.pending_goto_line {
            if self.view.caret != off || self.has_selection() {
                self.view.pending_goto_line = None;
                return;
            }
            if let Some((o, true)) = self.buf.line_start(target) {
                let o = o.max(self.min_caret());
                self.set_caret(o, false);
                self.view.center_caret = true;
                self.view.pending_goto_line = None;
            }
        }
    }

    pub fn goto_offset(&mut self, off: u64) {
        let off = self.buf.snap_char(off.min(self.buf.len()));
        self.set_caret(off, false);
        self.view.center();
    }
}

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

    fn doc(bytes: &[u8]) -> (tempfile::TempDir, Document) {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("t.txt");
        std::fs::write(&path, bytes).unwrap();
        let src = Arc::new(Source::open(&path, bigtext::file::OpenMode::Auto).unwrap());
        let det = bigtext::encoding::detect(&src.read(0..src.len()).unwrap(), true);
        let mut d = Document::loading(1, path);
        d.install(src, det, None, bigtext::jobs::noop_waker());
        (dir, d)
    }

    fn bytes(d: &Document) -> Vec<u8> {
        d.buf.read(0..d.buf.len()).unwrap().to_vec()
    }

    /// The byte order mark is not part of line 1: line commands leave it where it is.
    #[test]
    fn line_commands_keep_the_byte_order_mark() {
        let (_t, mut d) = doc(b"\xEF\xBB\xBFa\nb\n");
        assert_eq!(d.min_caret(), 3);
        d.set_caret(3, false);
        d.duplicate_line();
        assert_eq!(bytes(&d), b"\xEF\xBB\xBFa\na\nb\n");
        d.undo();
        d.set_caret(3, false);
        d.delete_line();
        assert_eq!(bytes(&d), b"\xEF\xBB\xBFb\n");
        d.undo();
        assert_eq!(bytes(&d), b"\xEF\xBB\xBFa\nb\n");
    }
}