bigtext 0.19.1

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
//! Replacement: templates (`$1`, `${name}`, `\n`, `\t`), small batches as piece-table edits and
//! the streaming replace-all that writes a new file with bounded memory.

use std::io::{self, Write};
use std::ops::Range;

use crate::jobs::{CancelToken, Progress};
use crate::search::{self, Matcher, SearchEnd};
use crate::text::TextBuf;
use regex_automata::util::captures::Captures;

/// Replacement text with escape sequences resolved.
#[derive(Clone, Debug)]
pub struct Template {
    text: String,
    /// `$` references are interpolated (regex mode only).
    interpolate: bool,
}

/// Resolves `\n`, `\r`, `\t`, `\0` and `\\`; other backslash sequences are kept verbatim.
pub fn unescape(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    let mut it = s.chars().peekable();
    while let Some(c) = it.next() {
        if c != '\\' {
            out.push(c);
            continue;
        }
        match it.peek().copied() {
            Some('n') => out.push('\n'),
            Some('r') => out.push('\r'),
            Some('t') => out.push('\t'),
            Some('0') => out.push('\0'),
            Some('\\') => out.push('\\'),
            _ => {
                out.push('\\');
                continue;
            }
        }
        it.next();
    }
    out
}

impl Template {
    /// Replacement text used exactly as written: no escapes, no `$` references (the command
    /// line's plain-text mode, where `C:\new` is a path, not a line break).
    pub fn verbatim(replacement: &str) -> Template {
        Template {
            text: replacement.to_string(),
            interpolate: false,
        }
    }

    pub fn new(replacement: &str, regex_mode: bool) -> Template {
        let text = unescape(replacement);
        let interpolate = regex_mode && text.contains('$');
        Template { text, interpolate }
    }

    /// Replacement bytes (in the document's encoding) for the match `s..e`.
    pub fn expand(&self, buf: &TextBuf, m: &Matcher, s: u64, e: u64) -> Vec<u8> {
        let mut out = Vec::new();
        Expander::new(self, m).expand_into(buf, s, e, &mut out);
        out
    }
}

/// Expands a [`Template`] for many matches of one search: a replacement without `$`
/// references is encoded once, and capture buffers are reused, so Replace All does no
/// per-match encoding or allocation beyond the output itself.
pub struct Expander<'a> {
    tpl: &'a Template,
    m: &'a Matcher,
    /// The encoded replacement when it does not depend on the match.
    fixed: Option<Vec<u8>>,
    caps: Option<Captures>,
    hay: Vec<u8>,
    interp: Vec<u8>,
}

impl<'a> Expander<'a> {
    pub fn new(tpl: &'a Template, m: &'a Matcher) -> Expander<'a> {
        let codec = m.codec();
        let fixed = (!tpl.interpolate).then(|| codec.encode(&tpl.text));
        let caps = if tpl.interpolate {
            m.regex().map(|r| r.create_captures())
        } else {
            None
        };
        Expander {
            tpl,
            m,
            fixed,
            caps,
            hay: Vec::new(),
            interp: Vec::new(),
        }
    }

    /// The replacement when it is the same for every match.
    pub fn fixed(&self) -> Option<&[u8]> {
        self.fixed.as_deref()
    }

    /// Appends the replacement for the match `s..e` to `out`.
    pub fn expand_into(&mut self, buf: &TextBuf, s: u64, e: u64, out: &mut Vec<u8>) {
        if let Some(f) = &self.fixed {
            out.extend_from_slice(f);
            return;
        }
        let codec = self.m.codec();
        let found = match self.caps.as_mut() {
            Some(caps) => search::captures_into(buf, self.m, s, e, caps, &mut self.hay).is_some(),
            None => false,
        };
        if !found {
            out.extend_from_slice(&codec.encode(&self.tpl.text));
            return;
        }
        let caps = self.caps.as_ref().expect("captures");
        if codec.enc == crate::encoding::Encoding::Utf8 {
            caps.interpolate_bytes_into(&self.hay, self.tpl.text.as_bytes(), out);
        } else {
            self.interp.clear();
            caps.interpolate_bytes_into(&self.hay, self.tpl.text.as_bytes(), &mut self.interp);
            out.extend_from_slice(&codec.encode(&String::from_utf8_lossy(&self.interp)));
        }
    }
}

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct ReplaceStats {
    pub count: u64,
    pub bytes_in: u64,
    pub bytes_out: u64,
}

/// Outcome of collecting replacements for in-memory application.
pub enum Collected {
    /// Few enough matches: apply as piece-table edits (undoable).
    Edits(Vec<(Range<u64>, Vec<u8>)>),
    /// More than `threshold` matches: use the streaming path.
    TooMany,
    Cancelled,
}

/// Collects up to `threshold` replacements in `range`.
pub fn collect(
    buf: &TextBuf,
    m: &Matcher,
    tpl: &Template,
    range: Range<u64>,
    threshold: usize,
    cancel: &CancelToken,
    progress: Option<&Progress>,
) -> Collected {
    let mut edits = Vec::new();
    let mut too_many = false;
    let mut exp = Expander::new(tpl, m);
    let end = search::search_forward(buf, m, range, cancel, progress, |s, e| {
        if edits.len() >= threshold {
            too_many = true;
            return false;
        }
        let mut rep = Vec::new();
        exp.expand_into(buf, s, e, &mut rep);
        edits.push((s..e, rep));
        true
    });
    match end {
        SearchEnd::Cancelled | SearchEnd::Unavailable => Collected::Cancelled,
        _ if too_many => Collected::TooMany,
        _ => Collected::Edits(edits),
    }
}

/// First `n` replacements as (offset, before, after) for preview.
pub fn preview(
    buf: &TextBuf,
    m: &Matcher,
    tpl: &Template,
    range: Range<u64>,
    n: usize,
    cancel: &CancelToken,
) -> Vec<(u64, String, String)> {
    let codec = buf.codec;
    let mut out = Vec::new();
    search::search_forward(buf, m, range, cancel, None, |s, e| {
        let before = buf
            .read(s..e.min(s + 200))
            .map(|b| codec.decode_lossy(&b))
            .unwrap_or_default();
        let after = codec.decode_lossy(&tpl.expand(buf, m, s, e));
        out.push((s, before, after));
        out.len() < n
    });
    out
}

/// Streams the whole document to `out`, replacing every match in `range`.
/// Returns `Ok(None)` if cancelled.
pub fn replace_all_to<W: Write>(
    buf: &TextBuf,
    m: &Matcher,
    tpl: &Template,
    range: Range<u64>,
    out: &mut W,
    cancel: &CancelToken,
    progress: Option<&Progress>,
) -> io::Result<Option<ReplaceStats>> {
    let mut stats = ReplaceStats {
        bytes_in: buf.len(),
        ..Default::default()
    };
    let mut pos = 0u64;
    let mut err: Option<io::Error> = None;
    let mut scratch = Vec::new();
    // Copies [from, to) to `out`, straight from the search window when it holds those bytes.
    let mut copy = |from: u64,
                    to: u64,
                    hay: &[u8],
                    base: u64,
                    out: &mut W,
                    stats: &mut ReplaceStats|
     -> io::Result<()> {
        if from >= to {
            return Ok(());
        }
        stats.bytes_out += to - from;
        if from >= base && to <= base + hay.len() as u64 {
            return out.write_all(&hay[(from - base) as usize..(to - base) as usize]);
        }
        const STEP: u64 = 4 * 1024 * 1024;
        let mut p = from;
        while p < to {
            let e = (p + STEP).min(to);
            let n = buf
                .read_to(p..e, &mut scratch)
                .ok_or_else(|| io::Error::other("could not read the document"))?;
            out.write_all(&scratch[..n])?;
            p = e;
        }
        Ok(())
    };
    let mut exp = Expander::new(tpl, m);
    let mut rep = Vec::new();
    let end = search::search_forward_ctx(buf, m, range, cancel, progress, |s, e, hay, base| {
        let r = copy(pos, s, hay, base, out, &mut stats).and_then(|_| {
            let rep: &[u8] = if exp.fixed().is_none() {
                rep.clear();
                exp.expand_into(buf, s, e, &mut rep);
                &rep
            } else {
                exp.fixed().unwrap_or_default()
            };
            stats.bytes_out += rep.len() as u64;
            out.write_all(rep)
        });
        if let Err(e) = r {
            err = Some(e);
            return false;
        }
        stats.count += 1;
        pos = e;
        true
    });
    if let Some(e) = err {
        return Err(e);
    }
    match end {
        SearchEnd::Cancelled => return Ok(None),
        SearchEnd::Unavailable => return Err(io::Error::other("could not read the document")),
        _ => {}
    }
    let len = buf.len();
    copy(pos, len, &[], 0, out, &mut stats)?;
    Ok(Some(stats))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::encoding::Codec;
    use crate::file::{OpenMode, Source};
    use crate::index;
    use crate::search::Query;
    use std::sync::Arc;

    fn buf_with(data: &[u8]) -> (tempfile::NamedTempFile, TextBuf) {
        buf_in(data, Codec::utf8())
    }

    fn buf_in(data: &[u8], codec: Codec) -> (tempfile::NamedTempFile, TextBuf) {
        let mut f = tempfile::NamedTempFile::new().unwrap();
        f.write_all(data).unwrap();
        f.flush().unwrap();
        let src = Arc::new(Source::open(f.path(), OpenMode::Auto).unwrap());
        let idx = index::build_blocking(&src, codec);
        let mut t = TextBuf::new(src, idx, codec);
        t.blocking = true;
        (f, t)
    }

    fn replaced(t: &TextBuf, pattern: &str, regex: bool, tpl: &Template, r: Range<u64>) -> Vec<u8> {
        let q = Query {
            pattern: pattern.into(),
            regex,
            case_sensitive: true,
            ..Default::default()
        };
        let m = Matcher::new(&q, t.codec).unwrap();
        let mut out = Vec::new();
        replace_all_to(t, &m, tpl, r, &mut out, &CancelToken::new(), None)
            .unwrap()
            .unwrap();
        out
    }

    /// The byte order mark is not text: `^` matches at the start of line 1, after it, and
    /// nothing is written in front of it.
    #[test]
    fn a_byte_order_mark_stays_in_front() {
        let codec = Codec::new(
            crate::encoding::Encoding::Utf8,
            crate::encoding::NlByte::Lf,
            3,
        );
        let (_f, t) = buf_in(b"\xEF\xBB\xBFid,x\nb\n", codec);
        let tpl = Template::new("> ", true);
        assert_eq!(
            replaced(&t, "^", true, &tpl, 0..t.len()),
            b"\xEF\xBB\xBF> id,x\n> b\n> "
        );
        let tpl = Template::new("ID,", true);
        assert_eq!(
            replaced(&t, "^id,", true, &tpl, 0..t.len()),
            b"\xEF\xBB\xBFID,x\nb\n"
        );
    }

    /// In a selection that ends at the start of a line, that line is not part of it.
    #[test]
    fn no_empty_match_at_the_end_of_a_selection() {
        let (_f, t) = buf_with(b"a\nb\nc\n");
        let tpl = Template::new("// ", true);
        assert_eq!(replaced(&t, "^", true, &tpl, 0..4), b"// a\n// b\nc\n");
    }

    /// A UTF-16 file with an odd number of bytes (cut off) is searched to its end instead of
    /// looping on the half code unit.
    #[test]
    fn an_odd_length_utf16_file_is_searched_to_the_end() {
        let codec = Codec::new(
            crate::encoding::Encoding::Utf16Le,
            crate::encoding::NlByte::Lf,
            2,
        );
        let (_f, t) = buf_in(b"\xFF\xFEa\x00b", codec);
        let q = Query {
            pattern: "z".into(),
            ..Default::default()
        };
        let m = Matcher::new(&q, codec).unwrap();
        let cancel = CancelToken::new();
        let watchdog = cancel.clone();
        std::thread::spawn(move || {
            std::thread::sleep(std::time::Duration::from_secs(10));
            watchdog.cancel();
        });
        let mut n = 0;
        let end = search::search_forward(&t, &m, 0..t.len(), &cancel, None, |_, _| {
            n += 1;
            true
        });
        assert_eq!((end, n), (SearchEnd::Completed, 0));
    }

    #[test]
    fn a_verbatim_replacement_keeps_backslashes_and_dollars() {
        let (_f, t) = buf_with(br"path C:\old here");
        let tpl = Template::verbatim(r"C:\new $1");
        assert_eq!(
            replaced(&t, r"C:\old", false, &tpl, 0..t.len()),
            br"path C:\new $1 here"
        );
    }

    fn run(data: &[u8], pattern: &str, regex: bool, rep: &str) -> String {
        let (_f, t) = buf_with(data);
        let q = Query {
            pattern: pattern.into(),
            regex,
            case_sensitive: true,
            ..Default::default()
        };
        let m = Matcher::new(&q, Codec::utf8()).unwrap();
        let tpl = Template::new(rep, regex);
        let mut out = Vec::new();
        replace_all_to(
            &t,
            &m,
            &tpl,
            0..t.len(),
            &mut out,
            &CancelToken::new(),
            None,
        )
        .unwrap()
        .unwrap();
        // The batch path must agree with the streaming path.
        if let Collected::Edits(edits) = collect(
            &t,
            &m,
            &tpl,
            0..t.len(),
            1_000_000,
            &CancelToken::new(),
            None,
        ) {
            let batch = t.build_batch(&edits);
            let mut t2 = t.clone();
            t2.apply_batch(batch);
            assert_eq!(t2.read(0..t2.len()).unwrap().as_ref(), out.as_slice());
        } else {
            panic!("expected edits");
        }
        String::from_utf8(out).unwrap()
    }

    #[test]
    fn literal_replace() {
        assert_eq!(run(b"a-b-c", "-", false, "+"), "a+b+c");
        assert_eq!(run(b"a-b-c", "-", false, "$1"), "a$1b$1c");
    }

    #[test]
    fn capture_groups() {
        assert_eq!(
            run(b"2026-10-24", r"(\d+)-(\d+)-(\d+)", true, "$3.$2.$1"),
            "24.10.2026"
        );
        assert_eq!(
            run(b"key=value", r"(?P<k>\w+)=(?P<v>\w+)", true, "${v}=${k}"),
            "value=key"
        );
    }

    /// One `Expander` reuses its capture buffers for every match: many matches of different
    /// lengths, in UTF-8 and in decoded encodings, must expand exactly as one at a time.
    #[test]
    fn expander_reuse_matches_single_expansion() {
        use crate::encoding::{Encoding, NlByte};
        let text: String = (0..300)
            .map(|i| format!("k{i}={} x{}\n", "v".repeat(i % 17), i * 7))
            .collect();
        let encodings = [
            (Encoding::Utf8, Codec::utf8()),
            (
                Encoding::Utf16Le,
                Codec::new(Encoding::Utf16Le, NlByte::Lf, 0),
            ),
            (
                Encoding::Windows1251,
                Codec::new(Encoding::Windows1251, NlByte::Lf, 0),
            ),
        ];
        for (enc, codec) in encodings {
            let data = codec.encode(&text);
            let mut f = tempfile::NamedTempFile::new().unwrap();
            f.write_all(&data).unwrap();
            f.flush().unwrap();
            let src = Arc::new(Source::open(f.path(), OpenMode::Auto).unwrap());
            let idx = index::build_blocking(&src, codec);
            let mut t = TextBuf::new(src, idx, codec);
            t.blocking = true;
            let q = Query {
                pattern: r"(\w+)=(v*) x(\d+)".into(),
                regex: true,
                case_sensitive: true,
                ..Default::default()
            };
            let m = Matcher::new(&q, codec).unwrap();
            for rep in ["[$3|$2|$1]", "fixed"] {
                let tpl = Template::new(rep, true);
                let mut exp = Expander::new(&tpl, &m);
                let mut n = 0;
                search::search_forward(&t, &m, 0..t.len(), &CancelToken::new(), None, |s, e| {
                    let mut out = Vec::new();
                    exp.expand_into(&t, s, e, &mut out);
                    assert_eq!(out, tpl.expand(&t, &m, s, e), "{enc:?} {rep}");
                    n += 1;
                    true
                });
                assert_eq!(n, 300, "{enc:?}");
            }
            let mut out = Vec::new();
            let tpl = Template::new("[$3|$2|$1]", true);
            replace_all_to(
                &t,
                &m,
                &tpl,
                0..t.len(),
                &mut out,
                &CancelToken::new(),
                None,
            )
            .unwrap()
            .unwrap();
            let expected: String = (0..300)
                .map(|i| format!("[{}|{}|k{i}]\n", i * 7, "v".repeat(i % 17)))
                .collect();
            assert_eq!(codec.decode_lossy(&out), expected, "{enc:?}");
        }
    }

    #[test]
    fn escapes() {
        assert_eq!(run(b"a,b,c", ",", false, "\\n"), "a\nb\nc");
        assert_eq!(run(b"a,b", ",", false, "\\t\\\\"), "a\t\\b");
    }

    #[test]
    fn empty_matches_grow_file() {
        assert_eq!(run(b"ab\ncd\n", "^", true, "> "), "> ab\n> cd\n> ");
        assert_eq!(run(b"abc", "x*", true, "-"), "-a-b-c-");
    }

    #[test]
    fn shrink_to_nothing() {
        assert_eq!(run(b"xxxx", "x", false, ""), "");
    }

    #[test]
    fn threshold_switches_to_streaming() {
        let (_f, t) = buf_with(&b"a ".repeat(1000));
        let q = Query {
            pattern: "a".into(),
            case_sensitive: true,
            ..Default::default()
        };
        let m = Matcher::new(&q, Codec::utf8()).unwrap();
        let tpl = Template::new("b", false);
        assert!(matches!(
            collect(&t, &m, &tpl, 0..t.len(), 10, &CancelToken::new(), None),
            Collected::TooMany
        ));
    }

    #[test]
    fn cancel_leaves_no_result() {
        let (_f, t) = buf_with(b"aaaa");
        let q = Query {
            pattern: "a".into(),
            case_sensitive: true,
            ..Default::default()
        };
        let m = Matcher::new(&q, Codec::utf8()).unwrap();
        let c = CancelToken::new();
        c.cancel();
        let mut out = Vec::new();
        assert!(
            replace_all_to(&t, &m, &Template::new("b", false), 0..4, &mut out, &c, None)
                .unwrap()
                .is_none()
        );
    }
}