Skip to main content

editor_core/
search.rs

1//! Text search helpers.
2//!
3//! This module provides simple search APIs over a UTF-8 `&str`, using **character offsets**
4//! (not byte offsets) for all public inputs/outputs. It supports:
5//!
6//! - plain substring search (escaped and compiled into a regex)
7//! - regex search
8//! - optional whole-word matching
9
10use regex::{Regex, RegexBuilder};
11
12/// Options that control how search is performed.
13#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14pub struct SearchOptions {
15    /// If `true`, performs a case-sensitive search.
16    pub case_sensitive: bool,
17    /// If `true`, matches only whole words (ASCII-alphanumeric and `_`).
18    pub whole_word: bool,
19    /// If `true`, treats the query as a regex pattern.
20    pub regex: bool,
21}
22
23impl Default for SearchOptions {
24    fn default() -> Self {
25        Self {
26            case_sensitive: true,
27            whole_word: false,
28            regex: false,
29        }
30    }
31}
32
33/// A match returned by the search APIs, expressed as a half-open character range.
34#[derive(Debug, Clone, Copy, PartialEq, Eq)]
35pub struct SearchMatch {
36    /// Inclusive start character offset.
37    pub start: usize,
38    /// Exclusive end character offset.
39    pub end: usize,
40}
41
42impl SearchMatch {
43    /// Returns the length of the match in characters.
44    pub fn len(&self) -> usize {
45        self.end.saturating_sub(self.start)
46    }
47
48    /// Returns `true` if the match is empty.
49    pub fn is_empty(&self) -> bool {
50        self.start >= self.end
51    }
52}
53
54/// Search errors.
55#[derive(Debug)]
56pub enum SearchError {
57    /// The provided regex pattern failed to compile.
58    InvalidRegex(regex::Error),
59}
60
61impl std::fmt::Display for SearchError {
62    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
63        match self {
64            Self::InvalidRegex(err) => write!(f, "Invalid regex: {}", err),
65        }
66    }
67}
68
69impl std::error::Error for SearchError {}
70
71#[derive(Debug)]
72pub(crate) struct CharIndex {
73    char_to_byte: Vec<usize>,
74    text_len: usize,
75}
76
77impl CharIndex {
78    pub(crate) fn new(text: &str) -> Self {
79        let mut char_to_byte: Vec<usize> = text.char_indices().map(|(b, _)| b).collect();
80        char_to_byte.push(text.len());
81        Self {
82            char_to_byte,
83            text_len: text.len(),
84        }
85    }
86
87    pub(crate) fn char_count(&self) -> usize {
88        self.char_to_byte.len().saturating_sub(1)
89    }
90
91    pub(crate) fn char_to_byte(&self, char_offset: usize) -> usize {
92        let clamped = char_offset.min(self.char_count());
93        self.char_to_byte
94            .get(clamped)
95            .cloned()
96            .unwrap_or(self.text_len)
97    }
98
99    pub(crate) fn byte_to_char(&self, byte_offset: usize) -> usize {
100        let clamped = byte_offset.min(self.text_len);
101        match self.char_to_byte.binary_search(&clamped) {
102            Ok(idx) => idx,
103            Err(idx) => idx,
104        }
105    }
106
107    pub(crate) fn char_at(&self, text: &str, char_offset: usize) -> Option<char> {
108        if char_offset >= self.char_count() {
109            return None;
110        }
111        let start = self.char_to_byte[char_offset];
112        let end = self.char_to_byte[char_offset + 1];
113        text.get(start..end)?.chars().next()
114    }
115}
116
117fn compile_search_regex(query: &str, options: SearchOptions) -> Result<Regex, SearchError> {
118    let pattern = if options.regex {
119        query.to_string()
120    } else {
121        regex::escape(query)
122    };
123
124    RegexBuilder::new(&pattern)
125        .case_insensitive(!options.case_sensitive)
126        .multi_line(true)
127        .build()
128        .map_err(SearchError::InvalidRegex)
129}
130
131/// A search query whose regex is compiled once and can be reused across many texts.
132///
133/// The one-shot free functions ([`find_all`], [`find_next`], …) recompile the regex on every
134/// call, which is wasteful when scanning many small texts (e.g. searching a file line-by-line, or
135/// many files). Compile once with [`CompiledSearch::new`] and call [`CompiledSearch::find_all`]
136/// repeatedly instead.
137#[derive(Debug, Clone)]
138pub struct CompiledSearch {
139    regex: Regex,
140    whole_word: bool,
141}
142
143impl CompiledSearch {
144    /// Compile `query` under `options` for repeated use.
145    ///
146    /// Returns [`SearchError::InvalidRegex`] if the query is an invalid regex (only possible when
147    /// `options.regex` is set).
148    pub fn new(query: &str, options: SearchOptions) -> Result<Self, SearchError> {
149        Ok(Self {
150            regex: compile_search_regex(query, options)?,
151            whole_word: options.whole_word,
152        })
153    }
154
155    /// Find all non-empty matches in `text` (character offsets, half-open ranges).
156    ///
157    /// Semantics match [`find_all`]; only the regex compilation is amortized.
158    pub fn find_all(&self, text: &str) -> Vec<SearchMatch> {
159        let index = CharIndex::new(text);
160        let mut matches: Vec<SearchMatch> = Vec::new();
161        for m in self.regex.find_iter(text) {
162            let start = index.byte_to_char(m.start());
163            let end = index.byte_to_char(m.end());
164            let candidate = SearchMatch { start, end };
165
166            if candidate.is_empty() {
167                continue;
168            }
169            if self.whole_word && !is_whole_word(text, &index, candidate) {
170                continue;
171            }
172
173            matches.push(candidate);
174        }
175
176        matches
177    }
178}
179
180fn is_word_char(ch: char) -> bool {
181    ch == '_' || ch.is_alphanumeric()
182}
183
184fn is_whole_word(text: &str, index: &CharIndex, m: SearchMatch) -> bool {
185    if m.is_empty() {
186        return false;
187    }
188
189    let before = if m.start == 0 {
190        None
191    } else {
192        index.char_at(text, m.start.saturating_sub(1))
193    };
194    let after = index.char_at(text, m.end);
195
196    !before.is_some_and(is_word_char) && !after.is_some_and(is_word_char)
197}
198
199/// Find the next occurrence of `query` in `text`, searching forward from `from_char`.
200///
201/// - Returns `Ok(None)` if no match is found (or if `query` is empty).
202/// - Match ranges are character offsets and are half-open (`[start, end)`).
203pub fn find_next(
204    text: &str,
205    query: &str,
206    options: SearchOptions,
207    from_char: usize,
208) -> Result<Option<SearchMatch>, SearchError> {
209    if query.is_empty() {
210        return Ok(None);
211    }
212
213    let re = compile_search_regex(query, options)?;
214    let index = CharIndex::new(text);
215
216    let mut start_char = from_char.min(index.char_count());
217    loop {
218        let start_byte = index.char_to_byte(start_char);
219        let Some(m) = re.find_at(text, start_byte) else {
220            return Ok(None);
221        };
222
223        let start = index.byte_to_char(m.start());
224        let end = index.byte_to_char(m.end());
225        let candidate = SearchMatch { start, end };
226
227        if candidate.is_empty() {
228            if end >= index.char_count() {
229                return Ok(None);
230            }
231            start_char = end + 1;
232            continue;
233        }
234
235        if options.whole_word && !is_whole_word(text, &index, candidate) {
236            start_char = candidate.end;
237            continue;
238        }
239
240        return Ok(Some(candidate));
241    }
242}
243
244/// Find the previous occurrence of `query` in `text`, searching backward from `from_char`.
245///
246/// - Returns `Ok(None)` if no match is found (or if `query` is empty).
247/// - Match ranges are character offsets and are half-open (`[start, end)`).
248pub fn find_prev(
249    text: &str,
250    query: &str,
251    options: SearchOptions,
252    from_char: usize,
253) -> Result<Option<SearchMatch>, SearchError> {
254    if query.is_empty() {
255        return Ok(None);
256    }
257
258    let re = compile_search_regex(query, options)?;
259    let index = CharIndex::new(text);
260
261    let limit_char = from_char.min(index.char_count());
262    let limit_byte = index.char_to_byte(limit_char);
263
264    // Iterate over the *full* text (not a truncated slice) so anchors (`$`, `\b`, `\z`) and greedy
265    // quantifiers see the real trailing context, then keep the last match that ends at or before
266    // the boundary. Searching a `&text[..limit_byte]` slice would let those constructs match at the
267    // artificial slice end, yielding matches that do not exist in the full document.
268    let mut last: Option<SearchMatch> = None;
269    for m in re.find_iter(text) {
270        // Matches are yielded left-to-right; once one starts at/after the boundary, no later match
271        // can end before it either.
272        if m.start() >= limit_byte {
273            break;
274        }
275        // A match that crosses the boundary is not "before" `from_char`.
276        if m.end() > limit_byte {
277            continue;
278        }
279
280        let start = index.byte_to_char(m.start());
281        let end = index.byte_to_char(m.end());
282        let candidate = SearchMatch { start, end };
283
284        if candidate.is_empty() {
285            continue;
286        }
287        if options.whole_word && !is_whole_word(text, &index, candidate) {
288            continue;
289        }
290
291        last = Some(candidate);
292    }
293
294    Ok(last)
295}
296
297/// Find all occurrences of `query` in `text`.
298///
299/// - Returns an empty list if `query` is empty.
300/// - Match ranges are character offsets and are half-open (`[start, end)`).
301pub fn find_all(
302    text: &str,
303    query: &str,
304    options: SearchOptions,
305) -> Result<Vec<SearchMatch>, SearchError> {
306    if query.is_empty() {
307        return Ok(Vec::new());
308    }
309
310    Ok(CompiledSearch::new(query, options)?.find_all(text))
311}
312
313/// Returns `true` if `range` exactly matches an occurrence of `query` in `text`.
314///
315/// This is useful for checking whether a current selection/caret range corresponds to the
316/// "current match" when implementing find/replace flows.
317pub fn is_match_exact(
318    text: &str,
319    query: &str,
320    options: SearchOptions,
321    range: SearchMatch,
322) -> Result<bool, SearchError> {
323    if range.is_empty() {
324        return Ok(false);
325    }
326
327    let Some(next) = find_next(text, query, options, range.start)? else {
328        return Ok(false);
329    };
330
331    Ok(next.start == range.start && next.end == range.end)
332}
333
334#[cfg(test)]
335mod tests {
336    use super::*;
337
338    fn regex_opts() -> SearchOptions {
339        SearchOptions {
340            case_sensitive: true,
341            whole_word: false,
342            regex: true,
343        }
344    }
345
346    #[test]
347    fn find_prev_does_not_fabricate_end_anchor_match_at_slice_boundary() {
348        // Regression (P1-4): searching a `&text[..limit_byte]` slice let `$` match at the
349        // artificial slice end. In "foo\nbar", `o$` only matches the last `o` of "foo" (offset
350        // 2..3, end of line 0). With from_char=2 the slice would be "fo", where the truncated
351        // "o" sits at the slice end and `$` would falsely match [1,2). There is no match ending
352        // at/before offset 2, so the correct answer is None.
353        let m = find_prev("foo\nbar", "o$", regex_opts(), 2).unwrap();
354        assert_eq!(m, None);
355    }
356
357    #[test]
358    fn find_prev_finds_real_end_anchor_match_using_full_context() {
359        // The real `o$` match is [2,3) (the "o" at end of line 0). Searching from the end of the
360        // document must find it, proving `$` is evaluated against the true line boundary.
361        let text = "foo\nbar";
362        let m = find_prev(text, "o$", regex_opts(), text.chars().count())
363            .unwrap()
364            .expect("should find the end-of-line match");
365        assert_eq!((m.start, m.end), (2, 3));
366    }
367
368    #[test]
369    fn find_prev_does_not_truncate_greedy_match_crossing_boundary() {
370        // Greedy `a+` over "aaaa": the only match is [0,4). With from_char=2, a slice "aa" would
371        // wrongly yield [0,2). Since the real match crosses the boundary, the answer is None.
372        assert_eq!(find_prev("aaaa", "a+", regex_opts(), 2).unwrap(), None);
373        // From the end, the full greedy match is returned intact.
374        let m = find_prev("aaaa", "a+", regex_opts(), 4).unwrap().unwrap();
375        assert_eq!((m.start, m.end), (0, 4));
376    }
377
378    #[test]
379    fn find_prev_returns_last_match_before_boundary() {
380        // Plain (non-regex) search: "abcabcabc", query "abc". From offset 9 the last match is
381        // [6,9); from offset 6 it is [3,6).
382        let opts = SearchOptions::default();
383        let m = find_prev("abcabcabc", "abc", opts, 9).unwrap().unwrap();
384        assert_eq!((m.start, m.end), (6, 9));
385        let m = find_prev("abcabcabc", "abc", opts, 6).unwrap().unwrap();
386        assert_eq!((m.start, m.end), (3, 6));
387    }
388}