bigtext 0.16.0

Free editor for huge text and log files (1-50+ GB): opens them without loading them into memory, 4 GB/s search, atomic save
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
//! Save / Save As, streaming replace-all and the finalize protocol that swaps files on disk.
//!
//! Protocol: (1) a worker streams a snapshot to a temp file and fsyncs it; (2) the UI drops its
//! `Arc<Source>` and cancels jobs holding snapshots; (3) a finalize worker waits until the old
//! source is gone, atomically replaces the target, and reopens it. If anything fails the
//! original is reopened unchanged and the user's edits are re-attached to it.

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

use bigtext::csv::Dialect;
use bigtext::encoding::{Encoding, LineEnding};
use bigtext::file::{self, Source};
use bigtext::index::LineIndex;
use bigtext::jobs::{self, human_bytes, CancelToken, Progress};
use bigtext::replace::{self, Collected, ReplaceStats, Template};
use bigtext::save::{self, SaveError, Transform};
use bigtext::search::Matcher;
use bigtext::text::Batch;

use super::document::{Banner, DocState, FileStamp};
use super::i18n::{tr, trf};
use super::{open_worker, same_path, BigTextApp, Confirm, ConfirmAction, Msg, Opened};

/// Replacements up to this count are applied as undoable piece-table edits.
pub const UNDO_THRESHOLD: usize = 50_000;

pub struct SaveJob {
    pub cancel: CancelToken,
    pub progress: Progress,
    pub label: String,
}

/// A Replace preview being found: for one version of a document, with the search and the
/// replacement as they were when it started.
pub struct PreviewJob {
    seq: u64,
    doc: u64,
    version: u64,
    query: bigtext::search::Query,
    with: String,
    cancel: CancelToken,
}

#[derive(Clone)]
pub enum WriteSpec {
    Identity,
    /// Line breaks converted; `true`: lone CRs become line breaks too.
    Eol(LineEnding, bool),
    Replace {
        matcher: Arc<Matcher>,
        template: Template,
        range: std::ops::Range<u64>,
    },
    DeleteColumns {
        dialect: Dialect,
        cols: Vec<usize>,
    },
    /// Saved in another encoding; with `eol`, line breaks converted as in `Eol`.
    Transcode {
        enc: Encoding,
        bom: bool,
        eol: Option<(LineEnding, bool)>,
    },
    Csv {
        dialect: Dialect,
        rewrite: bigtext::csv::Rewrite,
    },
    /// Delete the lines a filter shows (or, with `keep`, all the others).
    Lines {
        sel: Arc<super::lines_edit::LineSel>,
        keep: bool,
    },
    /// A text operation over a range too large to change in memory.
    TextOp {
        op: bigtext::textops::Op,
        range: std::ops::Range<u64>,
    },
    /// A column filled from a line to the end of the file.
    ColumnEdit {
        from: u64,
        cells: (u32, u32),
        gen: bigtext::column_edit::ColumnGen,
    },
    /// The lines sorted on disk.
    Sort {
        spec: bigtext::extsort::SortSpec,
        eol: Vec<u8>,
    },
}

/// What a write to disk does, for its progress label and the message when it is done.
#[derive(Clone, PartialEq)]
pub enum WriteKind {
    Save,
    Replace,
    /// These columns (sorted) were deleted.
    DeleteColumns(Vec<usize>),
    /// Saved in another encoding.
    Transcode(Encoding),
    /// A CSV table was rewritten (sorted, columns moved).
    Csv(bigtext::csv::Rewrite),
    /// Lines were deleted.
    Lines,
    TextOp(bigtext::textops::Op),
    ColumnEdit,
    Sort,
}

pub struct TempWritten {
    pub doc: u64,
    pub temp: PathBuf,
    pub target: PathBuf,
    pub backup: bool,
    pub prefix: Option<Vec<u64>>,
    pub stats: ReplaceStats,
    pub kind: WriteKind,
    pub elapsed: Duration,
}

pub struct Finalized {
    pub doc: u64,
    pub prefix: Option<Vec<u64>>,
    pub result: Result<Opened, (String, Result<Opened, String>)>,
    pub stats: ReplaceStats,
    pub kind: WriteKind,
    pub elapsed: Duration,
    /// The document's file as it was opened, which a failed save puts the edits back on.
    pub opened: FileStamp,
}

/// What a save writes: the text as it is, with other line breaks, or in another encoding.
fn save_spec(d: &super::document::Document, encoding: Option<(Encoding, bool)>) -> WriteSpec {
    match (encoding, d.eol_on_save) {
        (Some((enc, bom)), eol) => WriteSpec::Transcode {
            enc,
            bom,
            eol: eol.map(|le| (le, d.eol_lone_cr)),
        },
        (None, Some(le)) => WriteSpec::Eol(le, d.eol_lone_cr),
        (None, None) => WriteSpec::Identity,
    }
}

/// Whether the document's file is no longer the one it was opened from (another length or
/// change time). A file that is gone is not "changed": saving brings it back.
fn changed_on_disk(d: &super::document::Document) -> bool {
    let Some(p) = &d.path else { return false };
    let Ok(m) = std::fs::metadata(p) else {
        return false;
    };
    let src = &d.buf.source;
    m.len() != src.len() || src.modified().is_some_and(|t| m.modified().ok() != Some(t))
}

impl BigTextApp {
    pub(crate) fn save(&mut self, save_as: bool) {
        self.save_with(save_as, None);
    }

    /// Save, or Save As when `save_as`; with `encoding` (and whether to write a byte order
    /// mark) the document is re-encoded, always through the Save As dialog.
    pub(crate) fn save_with(&mut self, save_as: bool, encoding: Option<(Encoding, bool)>) {
        let Some(d) = self.docs.get(self.active) else {
            return;
        };
        if !d.is_ready() || d.save_job.is_some() {
            return;
        }
        let save_as = save_as || encoding.is_some();
        let target = match (&d.path, save_as) {
            // An unpacked copy lives in the temp folder: Save means Save As.
            (Some(p), false) if !d.temporary => p.clone(),
            _ => {
                let name = d
                    .unpacked_from
                    .as_deref()
                    .map(bigtext::decompress::inner_name)
                    .unwrap_or_else(|| d.title.clone());
                let mut dlg = rfd::FileDialog::new()
                    .set_title(super::i18n::tr("Save As"))
                    .set_file_name(name);
                if let Some(dir) = d
                    .unpacked_from
                    .as_ref()
                    .or(d.path.as_ref())
                    .and_then(|p| p.parent())
                {
                    dlg = dlg.set_directory(file::display_path(dir));
                }
                match dlg.save_file() {
                    Some(p) => p,
                    None => return,
                }
            }
        };
        let id = d.id;
        let same = d.path.as_deref().is_some_and(|p| same_path(p, &target));
        // Another program wrote to the file (a log that grew): saving would drop what it wrote,
        // so that is asked first.
        if same && changed_on_disk(d) {
            let file = d.title.clone();
            self.confirm = Some(super::Confirm {
                title: tr("File changed on disk").into(),
                message: trf("{file} changed on disk after it was opened (another program wrote to it). Saving replaces it with the text shown here, and what the other program wrote is lost.", &[("file", &file)]),
                action: super::ConfirmAction::SaveOverChanged { doc: id },
                checkbox: None,
            });
            return;
        }
        let spec = save_spec(d, encoding);
        let backup = self.settings.backup_on_save;
        self.start_write(id, target, spec, backup);
    }

    /// Saves the document to its file without asking whether the file changed on disk.
    pub(super) fn save_unchecked(&mut self, id: u64) {
        let Some(d) = self.docs.iter().find(|d| d.id == id) else {
            return;
        };
        let (Some(target), true) = (d.path.clone(), d.is_ready() && !d.temporary) else {
            return;
        };
        let spec = save_spec(d, None);
        let backup = self.settings.backup_on_save;
        self.start_write(id, target, spec, backup);
    }

    pub(crate) fn start_write(&mut self, id: u64, target: PathBuf, spec: WriteSpec, backup: bool) {
        self.start_write_checked(id, target, spec, backup, true);
    }

    /// [`Self::start_write`]; with `check`, a document that would not fit on the target's drive
    /// asks first.
    pub(crate) fn start_write_checked(
        &mut self,
        id: u64,
        target: PathBuf,
        spec: WriteSpec,
        backup: bool,
        check: bool,
    ) {
        // A comparison holding the file (or its backup) open would hold up replacing it.
        let holds = self.diff.as_ref().is_some_and(|r| {
            let running = !r.data.lock().unwrap().done;
            (r.doc == id && (running || !matches!(r.other, super::extras::DiffOther::File(_))))
                || r.other.path().is_some_and(|p| same_path(p, &target))
        });
        if holds {
            if let Some(r) = self.diff.take() {
                r.cancel.cancel();
            }
        }
        let Some((busy, temporary)) = self.docs.iter().find(|d| d.id == id).map(|d| {
            let same = d.path.as_deref().is_some_and(|p| same_path(p, &target));
            (d.save_job.is_some(), d.temporary && same)
        }) else {
            return;
        };
        // One write at a time: a second one (Ctrl+S while a "replace on disk" question was
        // open) could end up on disk instead of the first.
        if busy {
            return;
        }
        // An unpacked copy, standard input or a remote file is a file in the temp folder that
        // goes with its tab: a result written there would be thrown away on close.
        if temporary {
            self.error = Some(tr("This is a temporary copy (unpacked, standard input or remote). Save it as a file first (File → Save As), then do this in that file.").into());
            return;
        }
        let Some(d) = self.docs.iter_mut().find(|d| d.id == id) else {
            return;
        };
        let same_file = d.path.as_deref().is_some_and(|p| same_path(p, &target));
        let prefix = match spec {
            WriteSpec::Identity if same_file => {
                Some(d.buf.index.prefix_checkpoints(d.buf.pristine_prefix()))
            }
            _ => None,
        };
        let kind = match &spec {
            WriteSpec::Replace { .. } => WriteKind::Replace,
            WriteSpec::DeleteColumns { cols, .. } => WriteKind::DeleteColumns(cols.clone()),
            WriteSpec::Transcode { enc, .. } => WriteKind::Transcode(*enc),
            WriteSpec::Csv { rewrite, .. } => WriteKind::Csv(rewrite.clone()),
            WriteSpec::Lines { .. } => WriteKind::Lines,
            WriteSpec::TextOp { op, .. } => WriteKind::TextOp(*op),
            WriteSpec::ColumnEdit { .. } => WriteKind::ColumnEdit,
            WriteSpec::Sort { .. } => WriteKind::Sort,
            WriteSpec::Identity | WriteSpec::Eol(..) => WriteKind::Save,
        };
        let cancel = CancelToken::new();
        let progress = Progress::new(d.buf.len());
        let label = match kind {
            WriteKind::Save | WriteKind::Transcode(_) => "Saving",
            WriteKind::Replace => "Replacing",
            WriteKind::DeleteColumns(_) => "Deleting columns",
            WriteKind::Csv(_) => "Rewriting",
            WriteKind::Lines => "Deleting lines",
            WriteKind::TextOp(op) => op.name(),
            WriteKind::ColumnEdit => "Column editor",
            WriteKind::Sort => "Sorting",
        };
        d.save_job = Some(SaveJob {
            cancel: cancel.clone(),
            progress: progress.clone(),
            label: super::i18n::tr(label).into(),
        });
        let snap = d.buf.snapshot();
        let tx = self.tx.clone();
        let waker = self.waker.clone();
        jobs::spawn("save", move || {
            let t = Instant::now();
            if check {
                // About the document's size (twice that when it becomes UTF-16).
                let need = match &spec {
                    WriteSpec::Transcode { enc, .. } if enc.unit() == 2 => {
                        snap.len().saturating_mul(2)
                    }
                    _ => snap.len(),
                };
                let dir = target
                    .parent()
                    .map(std::path::Path::to_path_buf)
                    .unwrap_or_default();
                if let Some(free) = bigtext::sysinfo::free_space(&dir) {
                    if need > free {
                        let resume = super::Resume::Write {
                            doc: id,
                            target,
                            spec,
                            backup,
                        };
                        let _ = tx.send(Msg::LowSpace(Box::new(super::LowSpace {
                            need,
                            free,
                            dir,
                            resume,
                        })));
                        waker();
                        return;
                    }
                }
            }
            let transform = match &spec {
                WriteSpec::Identity => Transform::Identity,
                WriteSpec::Eol(le, lone) => Transform::Eol(*le, *lone),
                WriteSpec::Replace {
                    matcher,
                    template,
                    range,
                } => Transform::Replace {
                    matcher,
                    template,
                    range: range.clone(),
                },
                WriteSpec::DeleteColumns { dialect, cols } => Transform::DeleteColumns {
                    dialect: *dialect,
                    cols,
                },
                WriteSpec::Transcode { enc, bom, eol } => Transform::Transcode {
                    enc: *enc,
                    bom: *bom,
                    eol: *eol,
                },
                WriteSpec::Csv { dialect, rewrite } => Transform::Csv {
                    dialect: *dialect,
                    rewrite,
                },
                WriteSpec::Lines { sel, keep } => Transform::Lines {
                    keep: &|l: &[u8]| sel.shows(l) == *keep,
                },
                WriteSpec::TextOp { op, range } => Transform::TextOp {
                    op: *op,
                    range: range.clone(),
                },
                WriteSpec::ColumnEdit { from, cells, gen } => Transform::ColumnEdit {
                    from: *from,
                    cells: *cells,
                    gen,
                },
                WriteSpec::Sort { spec, eol } => Transform::Sort { spec: *spec, eol },
            };
            let r = save::write_temp(&snap, &target, transform, &cancel, &progress);
            drop(snap);
            let msg = match r {
                Ok((temp, stats)) => Msg::TempWritten(Box::new(TempWritten {
                    doc: id,
                    temp,
                    target,
                    backup,
                    prefix,
                    stats,
                    kind,
                    elapsed: t.elapsed(),
                })),
                Err(SaveError::Cancelled) => Msg::JobFailed { doc: id, msg: None },
                Err(SaveError::Io(e)) => Msg::JobFailed {
                    doc: id,
                    msg: Some(e),
                },
            };
            let _ = tx.send(msg);
            waker();
        });
    }

    pub(super) fn on_temp_written(&mut self, tw: TempWritten) {
        let waker = self.waker.clone();
        let tx = self.tx.clone();
        let Some(d) = self.docs.iter_mut().find(|d| d.id == tw.doc) else {
            let _ = std::fs::remove_file(&tw.temp);
            return;
        };
        // Release everything that maps the old file, keeping the edits for a failure rollback.
        d.cancel_jobs();
        d.watch_cancel.cancel();
        let opened = FileStamp::of(&d.buf.source);
        let weak: Weak<Source> = Arc::downgrade(&d.buf.source);
        d.buf = d
            .buf
            .with_source(Arc::new(Source::empty()), LineIndex::new(0));
        d.state = DocState::Finalizing(match tw.kind {
            WriteKind::Save | WriteKind::Transcode(_) => tr("Saving…").into(),
            WriteKind::Replace => tr("Replacing on disk…").into(),
            WriteKind::DeleteColumns(_) => tr("Deleting columns on disk…").into(),
            WriteKind::Csv(_) => tr("Rewriting on disk…").into(),
            WriteKind::Lines => tr("Deleting lines on disk…").into(),
            WriteKind::TextOp(op) => trf("{op} on disk…", &[("op", tr(op.name()))]),
            WriteKind::ColumnEdit => tr("Filling the column on disk…").into(),
            WriteKind::Sort => tr("Sorting on disk…").into(),
        });
        let original = d.path.clone();
        jobs::spawn("finalize", move || {
            let deadline = Instant::now() + Duration::from_secs(10);
            while weak.strong_count() > 0 && Instant::now() < deadline {
                std::thread::sleep(Duration::from_millis(5));
            }
            let result = match save::finalize(&tw.temp, &tw.target, tw.backup) {
                Ok(()) => open_worker(
                    &tw.target,
                    match tw.kind {
                        WriteKind::Transcode(enc) => Some(enc),
                        _ => None,
                    },
                    bigtext::file::OpenMode::Auto,
                )
                .map_err(|e| {
                    (
                        trf("Saved, but reopening failed: {e}", &[("e", &e)]),
                        Err(e),
                    )
                }),
                Err(e) => {
                    let reopened = match &original {
                        Some(p) => open_worker(p, None, bigtext::file::OpenMode::Auto),
                        None => Err("no original file".into()),
                    };
                    Err((e, reopened))
                }
            };
            let _ = tx.send(Msg::Finalized(Box::new(Finalized {
                doc: tw.doc,
                prefix: tw.prefix,
                result,
                stats: tw.stats,
                kind: tw.kind,
                elapsed: tw.elapsed,
                opened,
            })));
            waker();
        });
    }

    pub(super) fn on_finalized(&mut self, f: Finalized) {
        let waker = self.waker.clone();
        let mut close = None;
        let mut error = None;
        let Some(d) = self.docs.iter_mut().find(|d| d.id == f.doc) else {
            return;
        };
        d.save_job = None;
        match f.result {
            Ok(o) => {
                let target = o.path.clone();
                let same = d.path.as_deref().is_some_and(|p| same_path(p, &target));
                // Saved as a real file: the unpacked copy is not needed any more.
                if !same && d.temporary {
                    d.temporary = false;
                    d.unpacked_from = None;
                    if let Some(temp) = d.path.clone() {
                        jobs::spawn("remove-unpacked", move || {
                            bigtext::decompress::remove_temp(&temp)
                        });
                    }
                }
                d.title = target
                    .file_name()
                    .map(|n| n.to_string_lossy().into_owned())
                    .unwrap_or_default();
                d.path = Some(target);
                let codec = d.buf.codec;
                let mut det = o.detected;
                // Keep the user's encoding choice rather than re-sniffing it.
                if !matches!(f.kind, WriteKind::Transcode(_)) {
                    det.codec.enc = codec.enc;
                }
                d.install(
                    o.source,
                    det,
                    if same { f.prefix } else { None },
                    waker.clone(),
                );
                d.eol_on_save = None;
                d.eol_lone_cr = false;
                let secs = f.elapsed.as_secs_f64();
                d.banner = Some(Banner::Info(match &f.kind {
                    WriteKind::Replace => trf("Replaced {n} matches; wrote {size} in {secs}s.", &[("n", &f.stats.count.to_string()), ("size", &human_bytes(f.stats.bytes_out)), ("secs", &format!("{secs:.2}"))]),
                    WriteKind::DeleteColumns(cols) => {
                        d.table_state.columns_deleted(cols);
                        trf("Deleted {cols} from all {n} lines; wrote {size} in {secs}s.", &[("cols", &super::columns::count_label(cols.len())), ("n", &f.stats.count.to_string()), ("size", &human_bytes(f.stats.bytes_out)), ("secs", &format!("{secs:.2}"))])
                    }
                    WriteKind::Sort => trf("Sorted into {n} lines; wrote {size} in {secs}s.", &[("n", &f.stats.count.to_string()), ("size", &human_bytes(d.buf.len())), ("secs", &format!("{secs:.2}"))]),
                    WriteKind::ColumnEdit => trf("Filled the column on {n} lines in {secs}s.", &[("n", &f.stats.count.to_string()), ("secs", &format!("{secs:.2}"))]),
                    WriteKind::TextOp(op) => trf("{op}: wrote {size} in {secs}s.", &[("op", tr(op.name())), ("size", &human_bytes(f.stats.bytes_out)), ("secs", &format!("{secs:.2}"))]),
                    WriteKind::Lines => trf("Kept {n} lines; wrote {size} in {secs}s.", &[("n", &f.stats.count.to_string()), ("size", &human_bytes(f.stats.bytes_out)), ("secs", &format!("{secs:.2}"))]),
                    WriteKind::Save => trf("Saved {size} in {secs}s.", &[("size", &human_bytes(d.buf.len())), ("secs", &format!("{secs:.2}"))]),
                    WriteKind::Csv(rw) => {
                        if matches!(rw, bigtext::csv::Rewrite::Derive { .. }) {
                            d.table_state.keep_layout();
                        }
                        if let bigtext::csv::Rewrite::Swap(a, b) = rw {
                            d.table_state.columns_swapped(*a, *b);
                        }
                        super::i18n::trf("Rewrote all {n} lines; wrote {size} in {secs}s.", &[("n", &f.stats.count.to_string()), ("size", &human_bytes(f.stats.bytes_out)), ("secs", &format!("{secs:.2}"))])
                    }
                    // A Unicode target counts the unreadable bytes, written as U+FFFD; another
                    // counts the characters it lacks, written as '?' (see Transform::Transcode).
                    WriteKind::Transcode(enc) if f.stats.count > 0 && enc.is_unicode() => super::i18n::trf(
                        "Saved as {enc} ({size}). The file had {n} unreadable characters; they were written as “�”.",
                        &[("enc", enc.name()), ("size", &human_bytes(f.stats.bytes_out)), ("n", &f.stats.count.to_string())],
                    ),
                    WriteKind::Transcode(enc) if f.stats.count > 0 => super::i18n::trf(
                        "Saved as {enc} ({size}). {n} characters do not exist in {enc} and were written as “?”.",
                        &[("enc", enc.name()), ("size", &human_bytes(f.stats.bytes_out)), ("n", &f.stats.count.to_string())],
                    ),
                    WriteKind::Transcode(enc) => super::i18n::trf("Saved as {enc} ({size}) in {secs}s.", &[("enc", enc.name()), ("size", &human_bytes(f.stats.bytes_out)), ("secs", &format!("{secs:.2}"))]),
                }));
                if let Some(Banner::Info(t)) = &d.banner {
                    self.announcement = Some(t.clone());
                }
                if d.close_after_save {
                    close = Some(d.id);
                }
                super::watch(d, self.tx.clone(), waker);
            }
            Err((msg, reopened)) => {
                // Only on the file as it was: if another program wrote to it meanwhile, the
                // unedited text would be other bytes. The document then fails as when the file
                // cannot be reopened, and its last journal stays (see `journal_tick`).
                let reattached = reopened.and_then(|o| {
                    if d.rebind(o.source, f.opened, waker.clone()) {
                        Ok(())
                    } else {
                        Err(tr("The file changed on disk.").to_string())
                    }
                });
                match reattached {
                    Ok(()) => {}
                    // Text that is all typed (an untitled document) needs no file: it stays
                    // editable, so the user can save it somewhere else.
                    Err(_) if d.buf.pieces().all(|p| p.buf == bigtext::text::Buf::Add) => {
                        d.state = DocState::Ready;
                    }
                    Err(e) => d.state = DocState::Failed(format!("{msg}\n{e}")),
                }
                d.close_after_save = false;
                error = Some(msg);
                super::watch(d, self.tx.clone(), waker);
            }
        }
        if let Some(e) = error {
            self.error = Some(e);
        }
        if let Some(id) = close {
            self.close_tab(id, true);
        }
    }

    pub(super) fn on_job_failed(&mut self, doc: u64, msg: Option<String>) {
        if let Some(d) = self.docs.iter_mut().find(|d| d.id == doc) {
            d.save_job = None;
            d.close_after_save = false;
            if msg.is_none() {
                d.banner = Some(Banner::Info(
                    tr("Cancelled. The file on disk was not modified.").into(),
                ));
            }
        }
        if let Some(m) = msg {
            self.error = Some(m);
        }
    }

    // ------------------------------------------------------------------------------------------
    // Replace.

    fn replace_setup(&mut self) -> Option<(u64, Arc<Matcher>, Template, std::ops::Range<u64>)> {
        let d = self.docs.get(self.active)?;
        if !d.is_ready() {
            return None;
        }
        if d.read_only {
            self.search.status = tr("Document is read-only").into();
            return None;
        }
        let m = match self.search.matcher(d.buf.codec) {
            Ok(m) => m,
            Err(e) => {
                self.search.status = e;
                return None;
            }
        };
        let tpl = Template::new(&self.search.replace_with, self.search.query.regex);
        let range = if self.search.in_selection && d.has_selection() {
            let (s, e) = d.selection();
            s..e
        } else {
            0..d.buf.len()
        };
        Some((d.id, m, tpl, range))
    }

    pub(super) fn replace_current(&mut self) {
        let Some((_, m, tpl, _)) = self.replace_setup() else {
            return;
        };
        let d = &mut self.docs[self.active];
        let (s, e) = d.selection();
        let is_match =
            s != e && bigtext::search::matches_in_view(&d.buf, &m, s..e, 64).contains(&(s, e));
        if is_match && d.editable() {
            let snap = d.buf.snapshot();
            let bytes = tpl.expand(&snap, &m, s, e);
            drop(snap);
            d.edit(s..e, &bytes, super::document::EditKind::Other);
        }
        self.find_next(true);
    }

    pub(crate) fn replace_all(&mut self) {
        let Some((id, m, tpl, range)) = self.replace_setup() else {
            return;
        };
        let d = &mut self.docs[self.active];
        if d.save_job.is_some() {
            return;
        }
        let cancel = CancelToken::new();
        let progress = Progress::new(range.end - range.start);
        d.save_job = Some(SaveJob {
            cancel: cancel.clone(),
            progress: progress.clone(),
            label: tr("Counting matches").into(),
        });
        let snap = d.buf.snapshot();
        let version = d.version;
        let tx = self.tx.clone();
        let waker = self.waker.clone();
        jobs::spawn("replace-collect", move || {
            let msg = match replace::collect(
                &snap,
                &m,
                &tpl,
                range.clone(),
                UNDO_THRESHOLD,
                &cancel,
                Some(&progress),
            ) {
                Collected::Edits(edits) => {
                    let count = edits.len();
                    Msg::ReplaceBatch {
                        doc: id,
                        version,
                        batch: snap.build_batch(&edits),
                        count,
                    }
                }
                Collected::TooMany => Msg::ReplaceTooMany {
                    doc: id,
                    version,
                    matcher: m,
                    template: tpl,
                    range,
                },
                Collected::Cancelled => Msg::JobFailed { doc: id, msg: None },
            };
            let _ = tx.send(msg);
            waker();
        });
    }

    pub(super) fn on_replace_batch(&mut self, doc: u64, version: u64, batch: Batch, count: usize) {
        let Some(d) = self.docs.iter_mut().find(|d| d.id == doc) else {
            return;
        };
        d.save_job = None;
        if d.version != version || d.buf.add_len() != batch.add_len() {
            self.search.status = tr("Document changed during replace; nothing replaced").into();
            return;
        }
        if count == 0 {
            self.search.status = tr("No matches").into();
            return;
        }
        let (s, _) = d.selection();
        let swap = d.buf.apply_batch(batch);
        d.record(swap, (s, s));
        self.search.status = trf(
            "Replaced {n} matches (undo with Ctrl+Z)",
            &[("n", &count.to_string())],
        );
    }

    pub(super) fn on_replace_too_many(
        &mut self,
        doc: u64,
        version: u64,
        matcher: Arc<Matcher>,
        template: Template,
        range: std::ops::Range<u64>,
    ) {
        let Some(d) = self.docs.iter_mut().find(|d| d.id == doc) else {
            return;
        };
        d.save_job = None;
        if d.version != version {
            return;
        }
        if d.path.is_none() {
            self.error = Some(trf("More than {n} matches. Save the document to a file first; large replacements are streamed to disk.", &[("n", &UNDO_THRESHOLD.to_string())]));
            return;
        }
        self.pending_replace = Some((doc, matcher, template, range));
        self.confirm = Some(Confirm {
            title: tr("Replace All on disk").into(),
            message: format!(
                "{}{}",
                trf(
                    "More than {n} matches. Replace All will stream the result to a new file and atomically replace “{file}”. Undo will not be available.",
                    &[("n", &UNDO_THRESHOLD.to_string()), ("file", &d.title)]
                ),
                if d.is_modified() { tr(" Your unsaved edits are included.") } else { "" }
            ),
            action: ConfirmAction::ReplaceOnDisk { doc },
            checkbox: Some((tr("Keep a backup (.bak)").into(), true)),
        });
    }

    pub(crate) fn replace_on_disk(&mut self, doc: u64, backup: bool) {
        let Some((id, matcher, template, range)) = self.pending_replace.take() else {
            return;
        };
        if id != doc {
            return;
        }
        let Some(path) = self
            .docs
            .iter()
            .find(|d| d.id == doc)
            .and_then(|d| d.path.clone())
        else {
            return;
        };
        self.start_write(
            doc,
            path,
            WriteSpec::Replace {
                matcher,
                template,
                range,
            },
            backup,
        );
    }

    pub(super) fn replace_preview(&mut self) {
        let Some((id, m, tpl, range)) = self.replace_setup() else {
            return;
        };
        // One preview at a time: the one running (a slow regex over a huge file can take a
        // while) is not wanted any more.
        self.cancel_preview();
        self.preview_seq += 1;
        let d = &self.docs[self.active];
        let (snap, version, seq, cancel) = (
            d.buf.snapshot(),
            d.version,
            self.preview_seq,
            CancelToken::new(),
        );
        self.preview_job = Some(PreviewJob {
            seq,
            doc: id,
            version,
            query: self.search.query.clone(),
            with: self.search.replace_with.clone(),
            cancel: cancel.clone(),
        });
        let tx = self.tx.clone();
        let waker = self.waker.clone();
        jobs::spawn("replace-preview", move || {
            let items = replace::preview(&snap, &m, &tpl, range, 200, &cancel);
            if cancel.is_cancelled() {
                return;
            }
            let lines = items
                .iter()
                .map(|(off, _, _)| snap.line_of(*off).0 + 1)
                .collect();
            let _ = tx.send(Msg::Preview {
                doc: id,
                version,
                seq,
                items,
                lines,
            });
            waker();
        });
    }

    fn cancel_preview(&mut self) {
        if let Some(j) = self.preview_job.take() {
            j.cancel.cancel();
        }
    }

    /// Stops the preview running when it is no longer wanted: its document was closed or
    /// changed, or the search or the replacement was edited (every frame).
    pub(super) fn preview_tick(&mut self) {
        let Some(j) = &self.preview_job else {
            return;
        };
        let wanted = self
            .docs
            .iter()
            .any(|d| d.id == j.doc && d.version == j.version)
            && j.query == self.search.query
            && j.with == self.search.replace_with;
        if !wanted {
            self.cancel_preview();
        }
    }

    /// Shows a preview that is the latest one started, for its document as it still is; an
    /// older one arriving late is dropped.
    pub(super) fn on_preview(
        &mut self,
        doc: u64,
        version: u64,
        seq: u64,
        items: Vec<(u64, String, String)>,
        lines: Vec<u64>,
    ) {
        if self.preview_job.as_ref().map(|j| j.seq) != Some(seq) {
            return;
        }
        self.preview_job = None;
        if self
            .docs
            .iter()
            .any(|d| d.id == doc && d.version == version)
        {
            self.preview = Some((doc, items, lines));
        }
    }
}

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

    /// A save in another encoding converts line breaks as the document's choices say, the
    /// lone-CR one included.
    #[test]
    fn save_in_another_encoding_keeps_the_line_break_choices() {
        let mut d = super::super::document::Document::loading(1, PathBuf::from("t.txt"));
        d.eol_on_save = Some(LineEnding::CrLf);
        d.eol_lone_cr = true;
        assert!(matches!(
            save_spec(&d, Some((Encoding::Utf16Le, true))),
            WriteSpec::Transcode {
                enc: Encoding::Utf16Le,
                bom: true,
                eol: Some((LineEnding::CrLf, true)),
            }
        ));
        assert!(matches!(
            save_spec(&d, None),
            WriteSpec::Eol(LineEnding::CrLf, true)
        ));
        d.eol_on_save = None;
        assert!(matches!(
            save_spec(&d, Some((Encoding::Utf8, false))),
            WriteSpec::Transcode { eol: None, .. }
        ));
    }

    use crate::app::document::{Document, EditKind};

    /// Saves "HELLO world" over a file of "hello world" where the final replace fails (the
    /// temporary file is gone), after `appended` was written to the file by another program.
    /// Gives the document's state, its text when it has one, and its typed bytes.
    fn failed_save(appended: &str) -> (DocState, Option<Vec<u8>>, Vec<u8>) {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("a.txt");
        std::fs::write(&path, "hello world\n").unwrap();
        let mut app = crate::app::test_app();
        let o = open_worker(&path, None, file::OpenMode::Auto).unwrap();
        let mut d = Document::loading(99, o.path.clone());
        d.install(o.source, o.detected, None, app.waker.clone());
        d.edit(0..5, b"HELLO", EditKind::Other);
        app.docs.push(d);
        if !appended.is_empty() {
            use std::io::Write;
            let mut f = std::fs::File::options().append(true).open(&path).unwrap();
            f.write_all(appended.as_bytes()).unwrap();
        }
        app.on_temp_written(TempWritten {
            doc: 99,
            temp: dir.path().join("gone.tmp"),
            target: path.clone(),
            backup: false,
            prefix: None,
            stats: ReplaceStats::default(),
            kind: WriteKind::Save,
            elapsed: Duration::ZERO,
        });
        let deadline = Instant::now() + Duration::from_secs(30);
        loop {
            app.poll_messages();
            let d = app.docs.iter().find(|d| d.id == 99).unwrap();
            if !matches!(d.state, DocState::Finalizing(_)) {
                break;
            }
            assert!(Instant::now() < deadline, "the save did not end");
            std::thread::sleep(Duration::from_millis(5));
        }
        let d = app.docs.iter().find(|d| d.id == 99).unwrap();
        let snap = d.buf.snapshot();
        let text = d
            .is_ready()
            .then(|| snap.read(0..snap.len()).unwrap().to_vec());
        (d.state.clone(), text, d.buf.add_bytes_from(0))
    }

    #[test]
    fn a_failed_save_puts_the_edits_back_on_the_file_as_it_was() {
        let (state, text, _) = failed_save("");
        assert_eq!(state, DocState::Ready);
        assert_eq!(text.as_deref(), Some(&b"HELLO world\n"[..]));
    }

    /// The edits are offsets into the file as it was opened: over a file another program wrote
    /// to meanwhile they would show (and save) other bytes, so they are not put back on it.
    #[test]
    fn a_failed_save_does_not_put_the_edits_on_a_file_that_changed() {
        let (state, text, typed) = failed_save("written by another program\n");
        assert!(matches!(state, DocState::Failed(_)), "{state:?} {text:?}");
        // The typed text is still there, for the journal.
        assert_eq!(typed, b"HELLO");
    }

    /// An app whose document is "one two one" with Replace "one" → `with` filled in.
    fn preview_app(with: &str) -> BigTextApp {
        let mut app = crate::app::test_app();
        let d = &mut app.docs[app.active];
        d.edit(0..0, b"one two one\n", EditKind::Other);
        app.search.query.pattern = "one".into();
        app.search.replace_with = with.into();
        app
    }

    fn preview_token(app: &BigTextApp) -> CancelToken {
        app.preview_job.as_ref().unwrap().cancel.clone()
    }

    /// Polls for 200 ms, and until no preview is running.
    fn settle_previews(app: &mut BigTextApp) {
        let start = Instant::now();
        while start.elapsed() < Duration::from_millis(200)
            || (app.preview_job.is_some() && start.elapsed() < Duration::from_secs(30))
        {
            app.poll_messages();
            std::thread::sleep(Duration::from_millis(5));
        }
    }

    #[test]
    fn a_new_replace_preview_cancels_the_running_one_and_drops_its_result() {
        let mut app = preview_app("1");
        app.replace_preview();
        let (first, first_seq) = (preview_token(&app), app.preview_seq);
        app.search.replace_with = "uno".into();
        app.replace_preview();
        assert!(first.is_cancelled());
        // What the first one found before it saw the cancel arrives late, after the second.
        let d = &app.docs[app.active];
        let late = Msg::Preview {
            doc: d.id,
            version: d.version,
            seq: first_seq,
            items: vec![(0, "one".into(), "1".into())],
            lines: vec![1],
        };
        settle_previews(&mut app);
        app.tx.send(late).unwrap();
        settle_previews(&mut app);
        let (_, items, _) = app.preview.as_ref().expect("no preview");
        let after: Vec<&str> = items.iter().map(|i| i.2.as_str()).collect();
        assert_eq!(after, ["uno", "uno"]);
    }

    #[test]
    fn a_running_replace_preview_stops_when_it_is_no_longer_wanted() {
        let mut app = preview_app("1");
        // The search changes.
        app.replace_preview();
        let token = preview_token(&app);
        app.search.query.pattern = "two".into();
        app.preview_tick();
        assert!(token.is_cancelled());
        // The replacement changes.
        app.replace_preview();
        let token = preview_token(&app);
        app.search.replace_with = "2".into();
        app.preview_tick();
        assert!(token.is_cancelled());
        // The document changes.
        app.replace_preview();
        let token = preview_token(&app);
        app.docs[app.active].edit(0..0, b"x", EditKind::Other);
        app.preview_tick();
        assert!(token.is_cancelled());
        // The document closes.
        app.replace_preview();
        let token = preview_token(&app);
        let doc = app.docs[app.active].id;
        app.close_tab(doc, true);
        app.preview_tick();
        assert!(token.is_cancelled());
        // None of them shows up.
        settle_previews(&mut app);
        assert!(app.preview.is_none());
    }
}