1use regex::{Regex, RegexBuilder};
11
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14pub struct SearchOptions {
15 pub case_sensitive: bool,
17 pub whole_word: bool,
19 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
35pub struct SearchMatch {
36 pub start: usize,
38 pub end: usize,
40}
41
42impl SearchMatch {
43 pub fn len(&self) -> usize {
45 self.end.saturating_sub(self.start)
46 }
47
48 pub fn is_empty(&self) -> bool {
50 self.start >= self.end
51 }
52}
53
54#[derive(Debug)]
56pub enum SearchError {
57 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#[derive(Debug, Clone)]
138pub struct CompiledSearch {
139 regex: Regex,
140 whole_word: bool,
141}
142
143impl CompiledSearch {
144 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 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
199pub 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
244pub 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 let mut last: Option<SearchMatch> = None;
269 for m in re.find_iter(text) {
270 if m.start() >= limit_byte {
273 break;
274 }
275 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
297pub 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
313pub 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 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 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 assert_eq!(find_prev("aaaa", "a+", regex_opts(), 2).unwrap(), None);
373 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 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}