Skip to main content

agentmux_srv_core/backend/
editor_search_text.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `filesearchtext`: the next match of a text, or a regular expression, in a UTF-8
5//! file, for the Large text viewer's find (case-insensitive, regex). Like
6//! `filesearchbytes` the file is read here in blocks, each call does a bounded
7//! amount of work and says where to go on from.
8//!
9//! A match is found when it lies inside one block and the 64 KiB after it: a match
10//! longer than that (a regex that spans many lines) is not found. A `^` or `$` is
11//! judged with 64 KiB of the file before the block, so on a line longer than that
12//! it can match in the middle of the line.
13//!
14//! docs/specs/SPEC_EDITOR_REVAMP_UNIFIED_VIEWERS_2026_10_15.md §4.4.6.
15
16use std::io::{Read, Seek, SeekFrom};
17use std::path::Path;
18use std::time::{Duration, Instant};
19
20use regex::bytes::{Regex, RegexBuilder};
21
22use crate::backend::base::expand_home_dir_safe;
23use crate::backend::rpc::engine::WshRpcEngine;
24use crate::backend::rpc_types::{FileSearchBytesResult, FileSearchTextReq};
25
26/// The longest query, in characters.
27const MAX_QUERY: usize = 1000;
28/// One block of match starts.
29const BLOCK: u64 = 1 << 20;
30/// The file read beyond a block, for a match that starts in it and runs past its end.
31const AFTER: u64 = 64 << 10;
32/// The file read before a block, for the text a `^`, `$` or `\b` looks at.
33const BEFORE: u64 = 64 << 10;
34/// The most a call reads before it hands back where it got to.
35const BUDGET_BYTES: u64 = 256 << 20;
36/// The longest a call goes on before it hands back where it got to.
37const BUDGET_TIME: Duration = Duration::from_millis(1500);
38/// The most memory a compiled expression may take.
39const REGEX_SIZE_LIMIT: usize = 8 << 20;
40
41/// The expression for a query: a literal text is escaped; `^` and `$` match at each line (a line ends at `\n` or `\r\n`).
42pub fn compile(query: &str, regex: bool, ignore_case: bool) -> Result<Regex, String> {
43    if query.is_empty() {
44        return Err("nothing to find".into());
45    }
46    if query.chars().count() > MAX_QUERY {
47        return Err(format!("at most {MAX_QUERY} characters"));
48    }
49    let source = if regex { query.to_string() } else { regex::escape(query) };
50    RegexBuilder::new(&source)
51        .case_insensitive(ignore_case)
52        .multi_line(true)
53        .crlf(true)
54        .unicode(true)
55        .size_limit(REGEX_SIZE_LIMIT)
56        .build()
57        .map_err(|e| format!("not a valid expression: {}", first_line(&e.to_string())))
58}
59
60/// The last line of a regex error, which is the reason (the first lines draw the expression).
61fn first_line(message: &str) -> String {
62    message.lines().rev().find(|l| !l.trim().is_empty()).unwrap_or(message).trim().trim_start_matches("error: ").to_string()
63}
64
65/// The first non-empty match that starts in `hay[from..to]` (an empty one, of `a*`, is no place to stop).
66fn first_in(re: &Regex, hay: &[u8], from: usize, to: usize) -> Option<(usize, usize)> {
67    let mut pos = from;
68    while pos <= to && pos <= hay.len() {
69        let m = re.find_at(hay, pos)?;
70        if m.start() > to {
71            return None;
72        }
73        if m.end() > m.start() {
74            return Some((m.start(), m.end()));
75        }
76        pos = m.end() + 1;
77    }
78    None
79}
80
81/// The last non-empty match that starts in `hay[from..=to]`, among the matches found one after another (each
82/// begins where the one before ended), as a viewer marks them. The walk begins at the start of the line that
83/// holds `from`, so which matches there are does not depend on where a block happens to begin.
84fn last_in(re: &Regex, hay: &[u8], from: usize, to: usize) -> Option<(usize, usize)> {
85    let mut best = None;
86    let mut pos = memchr::memrchr(b'\n', &hay[..from]).map_or(0, |i| i + 1);
87    while pos <= to && pos <= hay.len() {
88        let Some(m) = re.find_at(hay, pos) else { break };
89        if m.start() > to {
90            break;
91        }
92        if m.end() > m.start() {
93            if m.start() >= from {
94                best = Some((m.start(), m.end()));
95            }
96            pos = m.end();
97        } else {
98            pos = m.end() + 1;
99        }
100    }
101    best
102}
103
104fn read_window<F: Read + Seek>(file: &mut F, buf: &mut Vec<u8>, lo: u64, hi: u64) -> std::io::Result<()> {
105    buf.resize((hi - lo) as usize, 0);
106    file.seek(SeekFrom::Start(lo))?;
107    file.read_exact(buf)
108}
109
110/// The search over `file` (`size` bytes). Forward: the first match starting at or after `from`; backward: the last
111/// one starting at or before it.
112pub fn search<F: Read + Seek>(
113    file: &mut F,
114    size: u64,
115    re: &Regex,
116    from: u64,
117    backward: bool,
118    budget_bytes: u64,
119    budget_time: Duration,
120) -> std::io::Result<FileSearchBytesResult> {
121    let not_found = |done: bool, next_from: u64| FileSearchBytesResult { found: false, offset: 0, length: 0, done, next_from };
122    let found = |start: u64, end: u64| FileSearchBytesResult { found: true, offset: start, length: end - start, done: false, next_from: 0 };
123    if size == 0 {
124        return Ok(not_found(true, 0));
125    }
126    let started = Instant::now();
127    let mut read = 0u64;
128    let mut buf = Vec::new();
129    if !backward {
130        let mut at = from;
131        while at < size {
132            let end = (at + BLOCK).min(size);
133            let ctx = at.saturating_sub(BEFORE);
134            let stop = (end + AFTER).min(size);
135            read_window(file, &mut buf, ctx, stop)?;
136            if let Some((s, e)) = first_in(re, &buf, (at - ctx) as usize, (end - 1 - ctx) as usize) {
137                return Ok(found(ctx + s as u64, ctx + e as u64));
138            }
139            read += stop - ctx;
140            at = end;
141            if at < size && (read >= budget_bytes || started.elapsed() >= budget_time) {
142                return Ok(not_found(false, at));
143            }
144        }
145        return Ok(not_found(true, size));
146    }
147    // Backward: blocks of starts [lo, hi], going down.
148    let mut hi = from.min(size - 1);
149    loop {
150        let lo = hi.saturating_sub(BLOCK - 1);
151        let ctx = lo.saturating_sub(BEFORE);
152        let stop = (hi + 1 + AFTER).min(size);
153        read_window(file, &mut buf, ctx, stop)?;
154        if let Some((s, e)) = last_in(re, &buf, (lo - ctx) as usize, (hi - ctx) as usize) {
155            return Ok(found(ctx + s as u64, ctx + e as u64));
156        }
157        if lo == 0 {
158            return Ok(not_found(true, 0));
159        }
160        hi = lo - 1;
161        read += stop - ctx;
162        if read >= budget_bytes || started.elapsed() >= budget_time {
163            return Ok(not_found(false, hi));
164        }
165    }
166}
167
168/// `filesearchtext`. This computer's files only, like `filesearchbytes`.
169pub fn register(engine: &std::sync::Arc<WshRpcEngine>) {
170    engine.register_typed("filesearchtext", move |cmd: FileSearchTextReq, _ctx| async move {
171        let re = compile(&cmd.query, cmd.regex, cmd.ignore_case).map_err(|e| format!("filesearchtext: {e}"))?;
172        let path = expand_home_dir_safe(&cmd.path);
173        tokio::task::spawn_blocking(move || search_path(&path, &re, cmd.from, cmd.backward).map_err(|e| format!("filesearchtext: {e}")))
174            .await
175            .map_err(|e| format!("filesearchtext: {e}"))?
176    });
177}
178
179fn search_path(path: &Path, re: &Regex, from: u64, backward: bool) -> std::io::Result<FileSearchBytesResult> {
180    let meta = std::fs::metadata(path)?;
181    if meta.is_dir() {
182        return Err(std::io::Error::other("is a directory"));
183    }
184    let mut file = std::fs::File::open(path)?;
185    search(&mut file, meta.len(), re, from, backward, BUDGET_BYTES, BUDGET_TIME)
186}
187
188#[cfg(test)]
189mod tests {
190    use super::*;
191    use std::io::Cursor;
192
193    fn run(data: &[u8], query: &str, regex: bool, ignore_case: bool, from: u64, backward: bool) -> FileSearchBytesResult {
194        let re = compile(query, regex, ignore_case).unwrap();
195        search(&mut Cursor::new(data.to_vec()), data.len() as u64, &re, from, backward, u64::MAX, Duration::from_secs(60)).unwrap()
196    }
197
198    #[test]
199    fn a_literal_is_exact_and_its_metacharacters_mean_themselves() {
200        let data = b"a.c abc ABC";
201        assert_eq!(run(data, "a.c", false, false, 0, false).offset, 0);
202        assert_eq!(run(data, "a.c", false, false, 1, false).found, false);
203        // Exact case: "ABC" is the only one.
204        assert_eq!(run(data, "ABC", false, false, 0, false).offset, 8);
205    }
206
207    #[test]
208    fn ignoring_case_finds_either_case_and_unicode_letters() {
209        let data = "xx Straße STRASSE ÉCOLE école".as_bytes();
210        let r = run(data, "école", false, true, 0, false);
211        assert_eq!(&data[r.offset as usize..(r.offset + r.length) as usize], "ÉCOLE".as_bytes());
212        let r = run(data, "école", false, true, r.offset + 1, false);
213        assert_eq!(&data[r.offset as usize..(r.offset + r.length) as usize], "école".as_bytes());
214        assert_eq!(run(data, "ÉCOLE", false, false, 0, false).offset, 19);
215    }
216
217    #[test]
218    fn a_regex_gives_the_match_length_and_anchors_match_each_line() {
219        let data = b"one\nfoo123 bar\nfoo45\n";
220        let r = run(data, r"foo\d+", true, false, 0, false);
221        assert_eq!((r.offset, r.length), (4, 6));
222        let r = run(data, r"^foo\d+$", true, false, 5, false);
223        assert_eq!((r.offset, r.length), (15, 5));
224        // `^bar` is not at the start of a line.
225        assert!(!run(data, "^bar", true, false, 0, false).found);
226    }
227
228    #[test]
229    fn backward_finds_the_last_match_at_or_before_the_offset() {
230        let data = b"ab ab ab";
231        assert_eq!(run(data, "ab", false, false, 7, true).offset, 6);
232        assert_eq!(run(data, "ab", false, false, 5, true).offset, 3);
233        assert_eq!(run(data, "ab", false, false, 2, true).offset, 0);
234        assert!(run(data, "ab", false, false, 2, true).found);
235        let r = run(data, "zz", false, false, 7, true);
236        assert!(!r.found && r.done);
237    }
238
239    #[test]
240    fn backward_goes_by_whole_matches_never_to_the_tail_of_one() {
241        // "foo123 456": the matches of \d+ are 123 (at 3) and 456 (at 7); "23" and "3" are not matches.
242        let data = b"foo123 456\n78\n";
243        assert_eq!(run(data, r"\d+", true, false, 6, true).offset, 3);
244        assert_eq!(run(data, r"\d+", true, false, 6, true).length, 3);
245        assert_eq!(run(data, r"\d+", true, false, 9, true).offset, 7);
246        // From the start of 123, no match before it.
247        assert!(!run(data, r"\d+", true, false, 2, true).found);
248        // Forward from the end of a match goes to the next whole one.
249        assert_eq!(run(data, r"\d+", true, false, 6, false).offset, 7);
250    }
251
252    #[test]
253    fn a_backward_walk_starts_at_a_line_start_whichever_block_it_is_in() {
254        // "aaaaa" starting a line: the matches of "aa" are at 0 and 2 of it, never at 1 or 3. The first block of a
255        // backward search begins at the 2nd character (`size - BLOCK`), mid-match: the walk still starts at the line.
256        let edge = BLOCK as usize;
257        let mut data = vec![b'\n'; edge * 2 + 7];
258        data[edge + 6..edge + 11].copy_from_slice(b"aaaaa");
259        let line = (edge + 6) as u64;
260        assert_eq!(run(&data, "aa", false, false, data.len() as u64, true).offset, line + 2);
261    }
262
263    #[test]
264    fn a_line_ending_is_crlf_as_well_as_lf() {
265        let data = b"foo\r\nbar\r\nfoo\n";
266        let r = run(data, "^foo$", true, false, 0, false);
267        assert_eq!((r.offset, r.length), (0, 3));
268        let r = run(data, "^foo$", true, false, 1, false);
269        assert_eq!((r.offset, r.length), (10, 3));
270        assert_eq!(run(data, "^bar$", true, false, 0, false).offset, 5);
271    }
272
273    #[test]
274    fn a_match_that_could_be_empty_is_skipped_not_returned() {
275        let data = b"xxaaay";
276        let r = run(data, "a*", true, false, 0, false);
277        assert_eq!((r.offset, r.length), (2, 3));
278        let r = run(data, "a*", true, false, 5, true);
279        assert_eq!((r.offset, r.length), (2, 3));
280    }
281
282    #[test]
283    fn a_match_across_a_block_edge_and_at_the_end_is_found_both_ways() {
284        let edge = BLOCK as usize;
285        let mut data = vec![b'.'; edge * 2 + 10];
286        data[edge - 2..edge + 2].copy_from_slice(b"WXYZ");
287        let end = data.len();
288        data[end - 3..].copy_from_slice(b"end");
289        assert_eq!(run(&data, "wxyz", false, true, 0, false).offset, (edge - 2) as u64);
290        assert_eq!(run(&data, "wxyz", false, true, (edge * 2) as u64, true).offset, (edge - 2) as u64);
291        assert_eq!(run(&data, "END", false, true, 0, false).offset, (end - 3) as u64);
292        assert_eq!(run(&data, "end", false, true, end as u64, true).offset, (end - 3) as u64);
293        // A start in the next block, from just past the edge.
294        assert!(!run(&data, "wxyz", false, true, (edge - 1) as u64, false).found);
295    }
296
297    #[test]
298    fn a_line_start_is_judged_with_the_text_before_the_block() {
299        // "x" fills the block edge: the "^y" after it is mid-line, not a line start.
300        let edge = BLOCK as usize;
301        let mut data = vec![b'x'; edge + 4];
302        data[edge..edge + 2].copy_from_slice(b"y!");
303        assert!(!run(&data, "^y", true, false, 0, false).found);
304        data[edge - 1] = b'\n';
305        assert_eq!(run(&data, "^y", true, false, 0, false).offset, edge as u64);
306    }
307
308    #[test]
309    fn hands_back_where_it_got_to_when_its_budget_runs_out() {
310        let data = vec![b'.'; (BLOCK as usize) * 4];
311        let re = compile("zz", false, false).unwrap();
312        let r = search(&mut Cursor::new(data.clone()), data.len() as u64, &re, 0, false, 1, Duration::from_secs(60)).unwrap();
313        assert!(!r.found && !r.done);
314        assert_eq!(r.next_from, BLOCK);
315        let r = search(&mut Cursor::new(data.clone()), data.len() as u64, &re, data.len() as u64, true, 1, Duration::from_secs(60)).unwrap();
316        assert!(!r.found && !r.done);
317        assert_eq!(r.next_from, BLOCK * 3 - 1);
318    }
319
320    #[test]
321    fn an_empty_file_and_a_bad_query_are_refused_or_not_found() {
322        let re = compile("a", false, false).unwrap();
323        let r = search(&mut Cursor::new(Vec::new()), 0, &re, 0, false, u64::MAX, Duration::from_secs(60)).unwrap();
324        assert!(!r.found && r.done);
325        assert!(compile("", false, false).is_err());
326        assert!(compile("(", true, false).is_err());
327        assert!(compile("(", false, false).is_ok());
328        assert!(compile(&"a".repeat(1001), false, false).is_err());
329    }
330
331    #[test]
332    fn searches_a_real_file_and_refuses_a_folder() {
333        let dir = tempfile::tempdir().unwrap();
334        let file = dir.path().join("a.txt");
335        std::fs::write(&file, "hello World").unwrap();
336        let re = compile("world", false, true).unwrap();
337        assert_eq!(search_path(&file, &re, 0, false).unwrap().offset, 6);
338        assert!(search_path(dir.path(), &re, 0, false).is_err());
339    }
340
341    #[tokio::test]
342    async fn filesearchtext_records_its_types() {
343        let (engine, _rx) = WshRpcEngine::new();
344        register(&engine);
345        let schema = engine.schema_json();
346        let row = schema.as_array().unwrap().iter().find(|r| r["command"] == "filesearchtext").expect("filesearchtext missing from the schema");
347        assert_eq!(row["requestName"], "FileSearchTextReq");
348        assert_eq!(row["responseName"], "FileSearchBytesResult");
349    }
350}