Skip to main content

strata_editor/
search.rs

1//! Find & Replace engine supporting literal, case-sensitive, whole-word, and regex search.
2
3use regex::RegexBuilder;
4use serde::{Deserialize, Serialize};
5
6use crate::buffer::LineBuffer;
7use crate::code_editor::CodeEditor;
8use crate::cursor::Position;
9
10/// A single match range inside a document buffer (char-indexed columns).
11#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
12pub struct SearchMatch {
13    pub start: Position,
14    pub end: Position,
15    pub text: String,
16}
17
18/// Interactive Find & Replace controller state.
19#[derive(Debug, Clone, Default, Serialize, Deserialize)]
20pub struct FindReplaceState {
21    pub query: String,
22    pub replacement: String,
23    pub case_sensitive: bool,
24    pub whole_word: bool,
25    pub use_regex: bool,
26    pub is_open: bool,
27    pub show_replace: bool,
28    pub active_match_index: usize,
29    pub matches: Vec<SearchMatch>,
30    pub regex_error: Option<String>,
31}
32
33impl FindReplaceState {
34    pub fn new() -> Self {
35        Self::default()
36    }
37
38    pub fn open_find(&mut self) {
39        self.is_open = true;
40    }
41
42    pub fn open_replace(&mut self) {
43        self.is_open = true;
44        self.show_replace = true;
45    }
46
47    pub fn close(&mut self) {
48        self.is_open = false;
49        self.matches.clear();
50        self.active_match_index = 0;
51    }
52
53    pub fn set_query(&mut self, query: impl Into<String>, buffer: &LineBuffer) {
54        self.query = query.into();
55        self.recompute_matches(buffer);
56    }
57
58    pub fn set_replacement(&mut self, replacement: impl Into<String>) {
59        self.replacement = replacement.into();
60    }
61
62    pub fn toggle_case_sensitive(&mut self, buffer: &LineBuffer) {
63        self.case_sensitive = !self.case_sensitive;
64        self.recompute_matches(buffer);
65    }
66
67    pub fn toggle_whole_word(&mut self, buffer: &LineBuffer) {
68        self.whole_word = !self.whole_word;
69        self.recompute_matches(buffer);
70    }
71
72    pub fn toggle_regex(&mut self, buffer: &LineBuffer) {
73        self.use_regex = !self.use_regex;
74        self.recompute_matches(buffer);
75    }
76
77    /// Recomputes all matches across `buffer` cleanly with Unicode char-column accuracy.
78    pub fn recompute_matches(&mut self, buffer: &LineBuffer) {
79        self.matches.clear();
80        self.regex_error = None;
81
82        if self.query.is_empty() {
83            self.active_match_index = 0;
84            return;
85        }
86
87        let pattern = if self.use_regex {
88            if self.whole_word {
89                format!(r"\b(?:{})\b", self.query)
90            } else {
91                self.query.clone()
92            }
93        } else {
94            let escaped = regex::escape(&self.query);
95            if self.whole_word {
96                format!(r"\b{escaped}\b")
97            } else {
98                escaped
99            }
100        };
101
102        let compiled = match RegexBuilder::new(&pattern)
103            .case_insensitive(!self.case_sensitive)
104            .build()
105        {
106            Ok(re) => re,
107            Err(err) => {
108                self.regex_error = Some(err.to_string());
109                self.active_match_index = 0;
110                return;
111            }
112        };
113
114        let line_count = buffer.line_count();
115        for row in 0..line_count {
116            let Some(line) = buffer.line(row) else {
117                continue;
118            };
119            if line.is_empty() {
120                continue;
121            }
122
123            // Build a lightweight byte->char column lookup only if the line has matches.
124            let mut match_iter = compiled.find_iter(line).peekable();
125            if match_iter.peek().is_none() {
126                continue;
127            }
128
129            for m in match_iter {
130                if m.start() == m.end() {
131                    // Guard against zero-width regex matches flooding results.
132                    continue;
133                }
134                let start_col = byte_to_char_col(line, m.start());
135                let end_col = byte_to_char_col(line, m.end());
136                self.matches.push(SearchMatch {
137                    start: Position::new(row, start_col),
138                    end: Position::new(row, end_col),
139                    text: m.as_str().to_string(),
140                });
141            }
142        }
143
144        if self.matches.is_empty() || self.active_match_index >= self.matches.len() {
145            self.active_match_index = 0;
146        }
147    }
148
149    /// Returns the currently focused match, if any.
150    pub fn active_match(&self) -> Option<&SearchMatch> {
151        self.matches.get(self.active_match_index)
152    }
153
154    /// Advances to the next match (wrapping around to match 0).
155    pub fn find_next(&mut self) -> Option<SearchMatch> {
156        if self.matches.is_empty() {
157            return None;
158        }
159        self.active_match_index = (self.active_match_index + 1) % self.matches.len();
160        self.matches.get(self.active_match_index).cloned()
161    }
162
163    /// Moves to the previous match (wrapping around to the last match).
164    pub fn find_prev(&mut self) -> Option<SearchMatch> {
165        if self.matches.is_empty() {
166            return None;
167        }
168        self.active_match_index = if self.active_match_index == 0 {
169            self.matches.len() - 1
170        } else {
171            self.active_match_index - 1
172        };
173        self.matches.get(self.active_match_index).cloned()
174    }
175
176    /// Moves `active_match_index` to the first match starting at or after `pos`.
177    pub fn select_nearest_after(&mut self, pos: Position) -> Option<SearchMatch> {
178        if self.matches.is_empty() {
179            return None;
180        }
181        let idx = self
182            .matches
183            .partition_point(|m| m.start < pos)
184            .min(self.matches.len() - 1);
185        self.active_match_index = idx;
186        self.matches.get(idx).cloned()
187    }
188
189    /// Binary-searches all matches on logical `line`, returning `(match_index, &SearchMatch)`.
190    pub fn matches_on_line(&self, line: usize) -> Vec<(usize, &SearchMatch)> {
191        if self.matches.is_empty() {
192            return Vec::new();
193        }
194        let first = self.matches.partition_point(|m| m.end.line < line);
195        let mut out = Vec::new();
196        for (offset, m) in self.matches[first..].iter().enumerate() {
197            if m.start.line > line {
198                break;
199            }
200            out.push((first + offset, m));
201        }
202        out
203    }
204
205    /// Replaces the active match in `editor`, recomputes matches, and selects the next match.
206    pub fn replace_current(&mut self, editor: &mut CodeEditor) -> bool {
207        let Some(target) = self.active_match().cloned() else {
208            return false;
209        };
210        let replacement = self.expand_replacement(&target.text);
211        let new_end = editor.replace_range(target.start, target.end, &replacement);
212        self.recompute_matches(editor.buffer());
213        let _ = self.select_nearest_after(new_end);
214        true
215    }
216
217    /// Replaces every match in `editor` as ONE atomic undo transaction and single incremental reparse.
218    pub fn replace_all(&mut self, editor: &mut CodeEditor) -> usize {
219        if self.matches.is_empty() {
220            return 0;
221        }
222        let count = self.matches.len();
223        let batch: Vec<(Position, Position, String)> = self
224            .matches
225            .iter()
226            .map(|m| (m.start, m.end, self.expand_replacement(&m.text)))
227            .collect();
228        editor.replace_ranges_atomic(batch);
229        self.recompute_matches(editor.buffer());
230        count
231    }
232
233    /// Formats a Monaco-style status label like `"2 of 14"` or `"No results"`.
234    pub fn status_label(&self) -> String {
235        if self.query.is_empty() {
236            return String::new();
237        }
238        if self.regex_error.is_some() {
239            return "Invalid regex".to_string();
240        }
241        if self.matches.is_empty() {
242            "No results".to_string()
243        } else {
244            format!("{} of {}", self.active_match_index + 1, self.matches.len())
245        }
246    }
247
248    fn expand_replacement(&self, matched_text: &str) -> String {
249        if !self.use_regex {
250            return self.replacement.clone();
251        }
252        let pattern = if self.whole_word {
253            format!(r"\b(?:{})\b", self.query)
254        } else {
255            self.query.clone()
256        };
257        if let Ok(re) = RegexBuilder::new(&pattern)
258            .case_insensitive(!self.case_sensitive)
259            .build()
260        {
261            re.replace(matched_text, self.replacement.as_str())
262                .into_owned()
263        } else {
264            self.replacement.clone()
265        }
266    }
267}
268
269#[inline]
270fn byte_to_char_col(line: &str, byte_idx: usize) -> usize {
271    let clamped = byte_idx.min(line.len());
272    line[..clamped].chars().count()
273}