Skip to main content

iced_code_editor/canvas_editor/features/search/
mod.rs

1//! Text search functionality for the code editor.
2//!
3//! This module provides efficient text search capabilities including:
4//! - Case-sensitive and case-insensitive search
5//! - Multiple match detection
6//! - Position tracking for highlighting
7
8pub(crate) mod dialog;
9mod icons;
10mod pattern;
11pub(crate) mod shortcuts;
12mod update;
13
14use crate::buffer::TextBuffer;
15use crate::canvas_editor::{CodeEditor, Message};
16use iced::widget::Id;
17use std::borrow::Cow;
18use std::thread;
19
20/// Represents a search match position in the buffer.
21///
22/// Contains the line and column position of a match.
23#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24pub struct SearchMatch {
25    /// Line index (0-based)
26    pub line: usize,
27    /// Column index (0-based, UTF-8 character offset)
28    pub col: usize,
29}
30
31/// Which field in the search dialog currently has focus.
32#[derive(Debug, Clone, Copy, PartialEq, Eq)]
33pub enum SearchFocusedField {
34    /// Search input field has focus
35    Search,
36    /// Replace input field has focus
37    Replace,
38}
39
40/// Search state management.
41///
42/// Tracks the current search query, options, and results.
43#[derive(Debug, Clone)]
44pub struct SearchState {
45    /// Current search query
46    pub query: String,
47    /// Text to replace with
48    pub replace_with: String,
49    /// Case-sensitive search flag
50    pub case_sensitive: bool,
51    /// Match whole identifiers only.
52    pub whole_word: bool,
53    /// Interpret the query as a regular expression.
54    pub use_regex: bool,
55    /// Expand both inputs into multiline editors.
56    pub multiline: bool,
57    /// Multiline search input content.
58    pub search_content: iced::widget::text_editor::Content,
59    /// Multiline replacement input content.
60    pub replace_content: iced::widget::text_editor::Content,
61    /// Invalid regular expression message, if any.
62    pub pattern_error: Option<String>,
63    details: Vec<pattern::MatchDetail>,
64    /// Whether the search dialog is visible
65    pub is_open: bool,
66    /// Whether replace mode is active (true) or just search (false)
67    pub is_replace_mode: bool,
68    /// List of all matches found
69    pub matches: Vec<SearchMatch>,
70    /// Index of the currently selected match
71    pub current_match_index: Option<usize>,
72    /// ID for the search text input (for focus management)
73    pub search_input_id: Id,
74    /// ID for the replace text input (for focus management)
75    pub replace_input_id: Id,
76    /// Which field currently has focus (for Tab navigation)
77    pub focused_field: SearchFocusedField,
78    /// Buffer line count represented by `matches`.
79    buffer_line_count: usize,
80}
81
82impl Default for SearchState {
83    fn default() -> Self {
84        Self {
85            query: String::new(),
86            replace_with: String::new(),
87            case_sensitive: false,
88            whole_word: false,
89            use_regex: false,
90            multiline: false,
91            search_content: iced::widget::text_editor::Content::new(),
92            replace_content: iced::widget::text_editor::Content::new(),
93            pattern_error: None,
94            details: Vec::new(),
95            is_open: false,
96            is_replace_mode: false,
97            matches: Vec::new(),
98            current_match_index: None,
99            search_input_id: Id::unique(),
100            replace_input_id: Id::unique(),
101            focused_field: SearchFocusedField::Search,
102            buffer_line_count: 0,
103        }
104    }
105}
106
107impl SearchState {
108    /// Creates a new search state.
109    #[must_use]
110    pub fn new() -> Self {
111        Self::default()
112    }
113
114    /// Opens the search dialog in search-only mode.
115    pub fn open_search(&mut self) {
116        self.is_open = true;
117        self.is_replace_mode = false;
118        self.focused_field = SearchFocusedField::Search;
119    }
120
121    /// Opens the search dialog in search-and-replace mode.
122    pub fn open_replace(&mut self) {
123        self.is_open = true;
124        self.is_replace_mode = true;
125        self.focused_field = SearchFocusedField::Search;
126    }
127
128    /// Closes the search dialog.
129    pub fn close(&mut self) {
130        self.is_open = false;
131    }
132
133    /// Cycles focus to the next field (Tab).
134    pub fn focus_next_field(&mut self) {
135        if self.is_replace_mode {
136            self.focused_field = match self.focused_field {
137                SearchFocusedField::Search => SearchFocusedField::Replace,
138                SearchFocusedField::Replace => SearchFocusedField::Search,
139            };
140        }
141        // In search-only mode, do nothing
142    }
143
144    /// Cycles focus to the previous field (Shift+Tab).
145    pub fn focus_previous_field(&mut self) {
146        if self.is_replace_mode {
147            self.focused_field = match self.focused_field {
148                SearchFocusedField::Search => SearchFocusedField::Replace,
149                SearchFocusedField::Replace => SearchFocusedField::Search,
150            };
151        }
152        // In search-only mode, do nothing
153    }
154
155    /// Updates the search query and triggers a new search.
156    pub fn set_query(&mut self, query: String, buffer: &TextBuffer) {
157        if self.search_content.text() != query {
158            self.search_content =
159                iced::widget::text_editor::Content::with_text(&query);
160        }
161        self.query = query;
162        self.update_matches(buffer);
163    }
164
165    /// Updates the replace text.
166    pub fn set_replace_with(&mut self, replace_with: String) {
167        if self.replace_content.text() != replace_with {
168            self.replace_content =
169                iced::widget::text_editor::Content::with_text(&replace_with);
170        }
171        if !self.use_regex {
172            for detail in &mut self.details {
173                detail.replacement.clone_from(&replace_with);
174            }
175        }
176        self.replace_with = replace_with;
177    }
178
179    /// Toggles case sensitivity and re-runs the search.
180    pub fn toggle_case_sensitive(&mut self, buffer: &TextBuffer) {
181        self.case_sensitive = !self.case_sensitive;
182        self.update_matches(buffer);
183    }
184
185    /// Updates the matches list based on current query and options.
186    pub fn update_matches(&mut self, buffer: &TextBuffer) {
187        self.pattern_error = None;
188        if self.whole_word || self.use_regex || self.query.contains('\n') {
189            match pattern::find(self, buffer, Some(MAX_MATCHES)) {
190                Ok(details) => {
191                    self.matches =
192                        details.iter().map(|item| item.start).collect();
193                    self.details = details;
194                }
195                Err(error) => {
196                    self.matches.clear();
197                    self.details.clear();
198                    self.pattern_error = Some(error);
199                }
200            }
201        } else {
202            self.details.clear();
203            self.matches = find_matches(
204                buffer,
205                &self.query,
206                self.case_sensitive,
207                Some(MAX_MATCHES),
208            );
209        }
210        self.buffer_line_count = buffer.line_count();
211
212        // Update current match index
213        if self.matches.is_empty() {
214            self.current_match_index = None;
215        } else if self.current_match_index.is_none() {
216            self.current_match_index = Some(0);
217        } else if let Some(idx) = self.current_match_index {
218            // Clamp to valid range
219            if idx >= self.matches.len() {
220                self.current_match_index =
221                    Some(self.matches.len().saturating_sub(1));
222            }
223        }
224    }
225
226    /// Refreshes only the logical-line range affected by an editor operation.
227    ///
228    /// Search queries are matched independently within each line, so unchanged
229    /// lines retain their results. Matches after inserted or removed lines only
230    /// need their logical line number shifted.
231    pub(crate) fn update_matches_after_edit(
232        &mut self,
233        buffer: &TextBuffer,
234        start_line: usize,
235        old_end_exclusive: usize,
236    ) {
237        if self.query.is_empty()
238            || self.buffer_line_count == 0
239            || self.whole_word
240            || self.use_regex
241            || self.query.contains('\n')
242        {
243            self.update_matches(buffer);
244            return;
245        }
246
247        let old_line_count = self.buffer_line_count;
248        let new_line_count = buffer.line_count();
249        let start_line = start_line.min(old_line_count).min(new_line_count);
250        let old_end_exclusive =
251            old_end_exclusive.min(old_line_count).max(start_line);
252        let new_end_exclusive = if new_line_count >= old_line_count {
253            old_end_exclusive
254                .saturating_add(new_line_count - old_line_count)
255                .min(new_line_count)
256        } else {
257            old_end_exclusive
258                .saturating_sub(old_line_count - new_line_count)
259                .max(start_line)
260                .min(new_line_count)
261        };
262
263        let replace_start =
264            self.matches.partition_point(|item| item.line < start_line);
265        let replace_end =
266            self.matches.partition_point(|item| item.line < old_end_exclusive);
267        let replacement = find_matches_in_range(
268            buffer,
269            &self.query,
270            self.case_sensitive,
271            start_line,
272            new_end_exclusive,
273            Some(MAX_MATCHES),
274        );
275        let replacement_len = replacement.len();
276
277        self.matches.splice(replace_start..replace_end, replacement);
278        let shifted_suffix_start = replace_start + replacement_len;
279        for item in &mut self.matches[shifted_suffix_start..] {
280            item.line = if new_line_count >= old_line_count {
281                item.line.saturating_add(new_line_count - old_line_count)
282            } else {
283                item.line.saturating_sub(old_line_count - new_line_count)
284            };
285        }
286        self.matches.truncate(MAX_MATCHES);
287        self.buffer_line_count = new_line_count;
288
289        // Clamp the current index, mirroring `update_matches`: the edit may
290        // have shrunk the match list without emptying it, leaving a stale
291        // index past the end that would make `current_match()` return `None`
292        // despite matches still existing.
293        if self.matches.is_empty() {
294            self.current_match_index = None;
295        } else if let Some(idx) = self.current_match_index
296            && idx >= self.matches.len()
297        {
298            self.current_match_index = Some(self.matches.len() - 1);
299        }
300    }
301
302    /// Moves to the next match (circular).
303    pub fn next_match(&mut self) {
304        if self.matches.is_empty() {
305            return;
306        }
307
308        self.current_match_index = Some(match self.current_match_index {
309            Some(idx) => {
310                if idx + 1 >= self.matches.len() {
311                    0 // Wrap to first
312                } else {
313                    idx + 1
314                }
315            }
316            None => 0,
317        });
318    }
319
320    /// Moves to the previous match (circular).
321    pub fn previous_match(&mut self) {
322        if self.matches.is_empty() {
323            return;
324        }
325
326        self.current_match_index = Some(match self.current_match_index {
327            Some(idx) => {
328                if idx == 0 {
329                    self.matches.len() - 1 // Wrap to last
330                } else {
331                    idx - 1
332                }
333            }
334            None => self.matches.len() - 1,
335        });
336    }
337
338    /// Returns the current match position if available.
339    #[must_use]
340    pub fn current_match(&self) -> Option<SearchMatch> {
341        self.current_match_index.and_then(|idx| self.matches.get(idx).copied())
342    }
343
344    /// Returns the number of matches found.
345    #[must_use]
346    pub fn match_count(&self) -> usize {
347        self.matches.len()
348    }
349
350    /// Selects the search match identified by a manually positioned cursor or
351    /// selection.
352    ///
353    /// An exact single-line selection takes precedence over the active cursor
354    /// endpoint. A cursor on either boundary of a match counts as being on that
355    /// match so a selection ending immediately after the query is recognised.
356    /// Otherwise, the closest match on the cursor's logical line is selected.
357    /// If that line has no matches, the current match remains unchanged.
358    ///
359    /// Returns `true` when the current match index changed.
360    pub fn select_match_at_cursor(
361        &mut self,
362        cursor: (usize, usize),
363        selection: Option<((usize, usize), (usize, usize))>,
364    ) -> bool {
365        if self.matches.is_empty() || self.query.is_empty() {
366            return false;
367        }
368
369        let exact_selection_index = selection.and_then(|(start, end)| {
370            self.matches_on_line(start.0).find(|&index| {
371                let match_item = self.matches[index];
372                (match_item.line, match_item.col) == start
373                    && self.match_end(match_item) == end
374            })
375        });
376        let containing_index = self.details.iter().position(|detail| {
377            (detail.start.line, detail.start.col) <= cursor
378                && cursor <= detail.end
379        });
380        let cursor_index =
381            exact_selection_index.or(containing_index).or_else(|| {
382                let line_matches = self.matches_on_line(cursor.0);
383                line_matches
384                    .clone()
385                    .find(|&index| {
386                        let match_item = self.matches[index];
387                        (match_item.col..=self.match_end(match_item).1)
388                            .contains(&cursor.1)
389                    })
390                    .or_else(|| {
391                        line_matches.min_by_key(|&index| {
392                            let match_item = self.matches[index];
393                            let match_end = self.match_end(match_item).1;
394                            if cursor.1 < match_item.col {
395                                match_item.col - cursor.1
396                            } else {
397                                cursor.1.saturating_sub(match_end)
398                            }
399                        })
400                    })
401            });
402
403        let Some(index) = cursor_index else {
404            return false;
405        };
406        if self.current_match_index == Some(index) {
407            return false;
408        }
409
410        self.current_match_index = Some(index);
411        true
412    }
413
414    /// Returns the logical end of a match, including multiline patterns.
415    pub(crate) fn match_end(&self, item: SearchMatch) -> (usize, usize) {
416        self.details
417            .binary_search_by_key(&(item.line, item.col), |detail| {
418                (detail.start.line, detail.start.col)
419            })
420            .ok()
421            .map(|index| self.details[index].end)
422            .unwrap_or((item.line, item.col + self.query.chars().count()))
423    }
424
425    pub(crate) fn replacement(&self, item: SearchMatch) -> (usize, String) {
426        self.details
427            .binary_search_by_key(&(item.line, item.col), |detail| {
428                (detail.start.line, detail.start.col)
429            })
430            .ok()
431            .map(|index| {
432                (
433                    self.details[index].len,
434                    self.details[index].replacement.clone(),
435                )
436            })
437            .unwrap_or((self.query.chars().count(), self.replace_with.clone()))
438    }
439
440    /// Returns the indices of matches on one logical line.
441    fn matches_on_line(&self, line: usize) -> std::ops::Range<usize> {
442        let start = self.matches.partition_point(|item| item.line < line);
443        let end = self.matches.partition_point(|item| item.line <= line);
444        start..end
445    }
446
447    /// Selects the match closest to the given cursor position.
448    ///
449    /// This is useful after buffer modifications to maintain context.
450    /// If no matches exist, sets current_match_index to None.
451    pub fn select_match_near_cursor(&mut self, cursor: (usize, usize)) {
452        if self.matches.is_empty() {
453            self.current_match_index = None;
454            return;
455        }
456
457        let (cursor_line, cursor_col) = cursor;
458        let insertion = self.matches.partition_point(|item| {
459            (item.line, item.col) < (cursor_line, cursor_col)
460        });
461        let mut left = insertion.checked_sub(1);
462        let mut right = (insertion < self.matches.len()).then_some(insertion);
463        let mut closest_index = insertion.min(self.matches.len() - 1);
464        let mut closest_distance = usize::MAX;
465
466        while left.is_some() || right.is_some() {
467            let left_line_distance = left.map_or(usize::MAX, |index| {
468                self.matches[index]
469                    .line
470                    .abs_diff(cursor_line)
471                    .saturating_mul(1000)
472            });
473            let right_line_distance = right.map_or(usize::MAX, |index| {
474                self.matches[index]
475                    .line
476                    .abs_diff(cursor_line)
477                    .saturating_mul(1000)
478            });
479
480            if left_line_distance.min(right_line_distance) > closest_distance {
481                break;
482            }
483
484            let index = match (left, right) {
485                (Some(index), Some(_))
486                    if left_line_distance <= right_line_distance =>
487                {
488                    left = index.checked_sub(1);
489                    index
490                }
491                (_, Some(index)) => {
492                    right =
493                        (index + 1 < self.matches.len()).then_some(index + 1);
494                    index
495                }
496                (Some(index), None) => {
497                    left = index.checked_sub(1);
498                    index
499                }
500                (None, None) => break,
501            };
502            let item = self.matches[index];
503            let distance = item
504                .line
505                .abs_diff(cursor_line)
506                .saturating_mul(1000)
507                .saturating_add(item.col.abs_diff(cursor_col));
508            if distance < closest_distance {
509                closest_distance = distance;
510                closest_index = index;
511                if distance == 0 {
512                    break;
513                }
514            }
515        }
516
517        self.current_match_index = Some(closest_index);
518    }
519}
520
521/// Finds all matches of a query in the text buffer.
522///
523/// # Arguments
524///
525/// * `buffer` - The text buffer to search in
526/// * `query` - The search string
527/// * `case_sensitive` - Whether to perform case-sensitive search
528/// * `limit` - Optional maximum number of matches to return
529///
530/// # Returns
531///
532/// A vector of all match positions found
533#[must_use]
534pub fn find_matches(
535    buffer: &TextBuffer,
536    query: &str,
537    case_sensitive: bool,
538    limit: Option<usize>,
539) -> Vec<SearchMatch> {
540    if query.is_empty() {
541        return Vec::new();
542    }
543
544    let line_count = buffer.line_count();
545
546    // Use parallel search for larger files
547    // Threshold can be tuned, but PARALLEL_SEARCH_THRESHOLD lines is a reasonable start to offset thread creation overhead
548    if line_count > PARALLEL_SEARCH_THRESHOLD {
549        let num_threads =
550            std::thread::available_parallelism().map(|n| n.get()).unwrap_or(1);
551
552        if num_threads > 1 {
553            let chunk_size = line_count.div_ceil(num_threads);
554
555            return thread::scope(|s| {
556                let mut handles = Vec::with_capacity(num_threads);
557
558                for i in 0..num_threads {
559                    let start = i * chunk_size;
560                    let end = (start + chunk_size).min(line_count);
561
562                    if start >= end {
563                        break;
564                    }
565
566                    handles.push(s.spawn(move || {
567                        find_matches_in_range(
568                            buffer,
569                            query,
570                            case_sensitive,
571                            start,
572                            end,
573                            limit,
574                        )
575                    }));
576                }
577
578                let mut matches = Vec::new();
579                for handle in handles {
580                    if let Ok(mut chunk_matches) = handle.join() {
581                        matches.append(&mut chunk_matches);
582                        if let Some(l) = limit
583                            && matches.len() >= l
584                        {
585                            matches.truncate(l);
586                            break;
587                        }
588                    }
589                }
590                matches
591            });
592        }
593    }
594
595    find_matches_in_range(buffer, query, case_sensitive, 0, line_count, limit)
596}
597
598/// Threshold for line count to trigger parallel search.
599const PARALLEL_SEARCH_THRESHOLD: usize = 1000;
600
601/// Maximum number of matches to return to prevent UI performance issues.
602pub const MAX_MATCHES: usize = 10_000;
603
604/// Returns the range of matches that fall within the specified logical line range (inclusive).
605///
606/// This function uses binary search to efficiently find the starting match
607/// and iterates to find the end match, avoiding full iteration of the matches vector.
608pub fn get_visible_match_range(
609    matches: &[SearchMatch],
610    min_logical_line: usize,
611    max_logical_line: usize,
612) -> std::ops::Range<usize> {
613    if matches.is_empty() {
614        return 0..0;
615    }
616
617    // Find the first match that is on or after min_logical_line
618    let start_idx = matches.partition_point(|m| m.line < min_logical_line);
619
620    // Find the end index (exclusive)
621    // We start searching from start_idx since we know everything before is < min_logical_line
622    let mut end_idx = start_idx;
623    for match_item in matches.iter().skip(start_idx) {
624        if match_item.line > max_logical_line {
625            break;
626        }
627        end_idx += 1;
628    }
629
630    start_idx..end_idx
631}
632
633fn find_matches_in_range(
634    buffer: &TextBuffer,
635    query: &str,
636    case_sensitive: bool,
637    start_line: usize,
638    end_line: usize,
639    limit: Option<usize>,
640) -> Vec<SearchMatch> {
641    let mut matches = Vec::new();
642    let search_query = if case_sensitive {
643        Cow::Borrowed(query)
644    } else {
645        Cow::Owned(query.to_lowercase())
646    };
647
648    for line_idx in start_line..end_line {
649        // Stop if we have enough matches
650        if let Some(l) = limit
651            && matches.len() >= l
652        {
653            break;
654        }
655
656        let line = buffer.line(line_idx);
657
658        // Optimization: skip lines shorter than query
659        if line.len() < query.len() {
660            continue;
661        }
662
663        if case_sensitive {
664            find_matches_case_sensitive(
665                line,
666                search_query.as_ref(),
667                line_idx,
668                &mut matches,
669            );
670        } else {
671            find_matches_case_insensitive(
672                line,
673                search_query.as_ref(),
674                line_idx,
675                &mut matches,
676            );
677        }
678    }
679
680    matches
681}
682
683/// Appends every case-sensitive occurrence of `search_query` in `line` to `matches`.
684///
685/// The searched string is `line` itself, so byte offsets from `str::find`
686/// always land on `line`'s own character boundaries and can be converted to
687/// a character column directly.
688fn find_matches_case_sensitive(
689    line: &str,
690    search_query: &str,
691    line_idx: usize,
692    matches: &mut Vec<SearchMatch>,
693) {
694    let mut start_pos = 0;
695    while let Some(relative_pos) = line[start_pos..].find(search_query) {
696        let absolute_pos = start_pos + relative_pos;
697        let col = line[..absolute_pos].chars().count();
698        matches.push(SearchMatch { line: line_idx, col });
699        start_pos = absolute_pos + search_query.len();
700    }
701}
702
703/// Appends every case-insensitive occurrence of `search_query` (already
704/// lowercased) in `line` to `matches`.
705///
706/// `to_lowercase()` can change both the byte *and* character length of a
707/// character (e.g. 'İ' U+0130 becomes "i" + a combining dot above, one
708/// character turning into two), so a byte offset found in the lowercased
709/// line cannot be converted to a column by re-slicing the original line —
710/// that silently drifts once such a character precedes the match. Instead,
711/// `boundaries` records, for every original character, the byte offset at
712/// which its lowercased form starts in the lowercased line, so a match's
713/// byte offset maps back to the original character it belongs to.
714fn find_matches_case_insensitive(
715    line: &str,
716    search_query: &str,
717    line_idx: usize,
718    matches: &mut Vec<SearchMatch>,
719) {
720    // ASCII text lowercases one byte to one byte, so byte offset == char
721    // offset == column and no boundary table is needed. This is the common
722    // case, so skip the per-line `Vec` allocation below for it.
723    if line.is_ascii() {
724        let search_line = line.to_ascii_lowercase();
725        let mut start_pos = 0;
726        while let Some(relative_pos) =
727            search_line[start_pos..].find(search_query)
728        {
729            let absolute_pos = start_pos + relative_pos;
730            matches.push(SearchMatch { line: line_idx, col: absolute_pos });
731            start_pos = absolute_pos + search_query.len();
732        }
733        return;
734    }
735
736    let mut search_line = String::with_capacity(line.len());
737    let mut boundaries: Vec<(usize, usize)> =
738        Vec::with_capacity(line.len() + 1);
739    for (char_idx, ch) in line.chars().enumerate() {
740        boundaries.push((search_line.len(), char_idx));
741        for lower_ch in ch.to_lowercase() {
742            search_line.push(lower_ch);
743        }
744    }
745    boundaries.push((search_line.len(), line.chars().count()));
746
747    let mut start_pos = 0;
748    while let Some(relative_pos) = search_line[start_pos..].find(search_query) {
749        let absolute_pos = start_pos + relative_pos;
750        let col = match boundaries
751            .binary_search_by_key(&absolute_pos, |&(byte, _)| byte)
752        {
753            Ok(idx) => boundaries[idx].1,
754            Err(idx) => boundaries[idx.saturating_sub(1)].1,
755        };
756        matches.push(SearchMatch { line: line_idx, col });
757        start_pos = absolute_pos + search_query.len();
758    }
759}
760
761impl CodeEditor {
762    /// Refreshes search matches after buffer modification.
763    ///
764    /// Should be called after any operation that modifies the buffer.
765    /// If search is active, recalculates only the affected logical lines and
766    /// selects the match closest to the current cursor position.
767    pub(crate) fn refresh_search_matches_if_needed(&mut self) {
768        if self.search_matches_visible() && !self.search_state.query.is_empty()
769        {
770            let start_line = self.pre_edit_line.saturating_sub(1);
771            let old_end_exclusive = self.pre_edit_last_line.saturating_add(2);
772            self.search_state.update_matches_after_edit(
773                &self.buffer,
774                start_line,
775                old_end_exclusive,
776            );
777
778            // Select match closest to cursor to maintain context
779            self.search_state
780                .select_match_near_cursor(self.cursors.primary_position());
781        }
782    }
783
784    pub(crate) fn search_matches_visible(&self) -> bool {
785        self.search_state.is_open
786            || (self.vim_enabled && self.vim_state.last_search().is_some())
787    }
788
789    /// Returns whether the search dialog is currently open.
790    ///
791    /// Both [`Self::open_search_dialog`] and
792    /// [`Self::open_search_replace_dialog`] open it; only
793    /// [`Self::close_search_dialog`] closes it. A host driving the dialog from
794    /// its own toolbar needs this to keep that button's pressed state in sync
795    /// with the dialog the user may also have opened by keyboard.
796    ///
797    /// # Returns
798    ///
799    /// `true` while the dialog is shown, `false` otherwise
800    ///
801    /// # Example
802    ///
803    /// ```
804    /// use iced_code_editor::CodeEditor;
805    ///
806    /// let mut editor = CodeEditor::new("fn main() {}", "rs");
807    /// assert!(!editor.is_search_open());
808    ///
809    /// let _task = editor.open_search_dialog();
810    /// assert!(editor.is_search_open());
811    /// ```
812    #[must_use]
813    pub fn is_search_open(&self) -> bool {
814        self.search_state.is_open
815    }
816
817    /// Opens the search dialog programmatically.
818    ///
819    /// This is useful when wiring your own UI button instead of relying on
820    /// keyboard shortcuts.
821    ///
822    /// # Returns
823    ///
824    /// A `Task<Message>` that focuses the search input.
825    ///
826    /// # Example
827    ///
828    /// ```
829    /// use iced_code_editor::CodeEditor;
830    ///
831    /// let mut editor = CodeEditor::new("fn main() {}", "rs");
832    ///
833    /// // Returned to the host's `update`, the task focuses the query field.
834    /// let _task = editor.open_search_dialog();
835    ///
836    /// assert!(editor.is_search_open());
837    /// ```
838    pub fn open_search_dialog(&mut self) -> iced::Task<Message> {
839        self.update(&Message::OpenSearch)
840    }
841
842    /// Opens the search-and-replace dialog programmatically.
843    ///
844    /// This is useful when wiring your own UI button instead of relying on
845    /// keyboard shortcuts.
846    ///
847    /// # Returns
848    ///
849    /// A `Task<Message>` that focuses the search input.
850    ///
851    /// # Example
852    ///
853    /// ```
854    /// use iced_code_editor::CodeEditor;
855    ///
856    /// let mut editor = CodeEditor::new("fn main() {}", "rs");
857    ///
858    /// // Same dialog as `open_search_dialog`, with the replace row shown.
859    /// let _task = editor.open_search_replace_dialog();
860    ///
861    /// assert!(editor.is_search_open());
862    /// ```
863    pub fn open_search_replace_dialog(&mut self) -> iced::Task<Message> {
864        self.update(&Message::OpenSearchReplace)
865    }
866
867    /// Closes the search dialog programmatically.
868    ///
869    /// # Returns
870    ///
871    /// A `Task<Message>` for any follow-up UI work.
872    ///
873    /// # Example
874    ///
875    /// ```
876    /// use iced_code_editor::CodeEditor;
877    ///
878    /// let mut editor = CodeEditor::new("fn main() {}", "rs");
879    /// let _task = editor.open_search_dialog();
880    ///
881    /// let _task = editor.close_search_dialog();
882    ///
883    /// assert!(!editor.is_search_open());
884    /// ```
885    pub fn close_search_dialog(&mut self) -> iced::Task<Message> {
886        self.update(&Message::CloseSearch)
887    }
888}
889
890#[cfg(test)]
891mod tests {
892    use super::*;
893
894    #[test]
895    fn test_find_matches_case_sensitive() {
896        let buffer = TextBuffer::new("Hello World\nhello world");
897        let matches = find_matches(&buffer, "hello", true, None);
898
899        assert_eq!(matches.len(), 1);
900        assert_eq!(matches[0].line, 1);
901        assert_eq!(matches[0].col, 0);
902    }
903
904    #[test]
905    fn test_find_matches_case_insensitive() {
906        let buffer = TextBuffer::new("Hello World\nhello world");
907        let matches = find_matches(&buffer, "hello", false, None);
908
909        assert_eq!(matches.len(), 2);
910        assert_eq!(matches[0].line, 0);
911        assert_eq!(matches[0].col, 0);
912        assert_eq!(matches[1].line, 1);
913        assert_eq!(matches[1].col, 0);
914    }
915
916    #[test]
917    fn test_find_matches_case_insensitive_unicode_length_changing() {
918        // 'İ' (U+0130) lowercases to "i" + a combining dot above (U+0307):
919        // one character becomes two. Searching for "tanbul" still matches
920        // (the combining mark only affects the leading "İ"/"i"), which lets
921        // us check that the reported column is computed against the
922        // *original* line ("İstanbul": İ=0, s=1, t=2) rather than drifting
923        // by the length the lowercased prefix gained.
924        let buffer = TextBuffer::new("İstanbul");
925        let matches = find_matches(&buffer, "tanbul", false, None);
926
927        assert_eq!(matches.len(), 1);
928        assert_eq!(matches[0].line, 0);
929        assert_eq!(matches[0].col, 2);
930    }
931
932    #[test]
933    fn test_find_matches_case_insensitive_unicode_match_starts_after_expansion()
934    {
935        // The character whose lowercase form changes length ('İ') sits right
936        // before the match itself, so the reported column must point at the
937        // first lowercased character of the match, not the lowercased 'İ'.
938        let buffer = TextBuffer::new("İSTANBUL");
939        let matches = find_matches(&buffer, "istanbul", false, None);
940
941        // "İstanbul".to_lowercase() is "i\u{307}stanbul" (combining dot),
942        // which does not literally contain "istanbul" — so there is no match.
943        // This documents that behavior rather than assuming a match exists.
944        assert!(matches.is_empty());
945    }
946
947    #[test]
948    fn test_find_matches_case_insensitive_unicode_byte_shrinking() {
949        // 'ẞ' (U+1E9E, capital sharp S) lowercases to 'ß' — same character
950        // count, but fewer bytes (3 -> 2). This exercises the opposite
951        // direction of length change from the 'İ' case above.
952        let buffer = TextBuffer::new("StraẞE");
953        let matches = find_matches(&buffer, "e", false, None);
954
955        assert_eq!(matches.len(), 1);
956        assert_eq!(matches[0].col, 5);
957    }
958
959    #[test]
960    fn test_find_matches_multiple_occurrences() {
961        let buffer = TextBuffer::new("foo bar foo baz foo");
962        let matches = find_matches(&buffer, "foo", false, None);
963
964        assert_eq!(matches.len(), 3);
965        assert_eq!(matches[0].col, 0);
966        assert_eq!(matches[1].col, 8);
967        assert_eq!(matches[2].col, 16);
968    }
969
970    #[test]
971    fn test_find_matches_multiline() {
972        let buffer = TextBuffer::new("line1\nfoo\nline3\nfoo");
973        let matches = find_matches(&buffer, "foo", false, None);
974
975        assert_eq!(matches.len(), 2);
976        assert_eq!(matches[0].line, 1);
977        assert_eq!(matches[1].line, 3);
978    }
979
980    #[test]
981    fn test_find_matches_empty_query() {
982        let buffer = TextBuffer::new("Hello World");
983        let matches = find_matches(&buffer, "", false, None);
984
985        assert_eq!(matches.len(), 0);
986    }
987
988    #[test]
989    fn test_find_matches_no_results() {
990        let buffer = TextBuffer::new("Hello World");
991        let matches = find_matches(&buffer, "xyz", false, None);
992
993        assert_eq!(matches.len(), 0);
994    }
995
996    #[test]
997    fn test_search_state_navigation() {
998        let buffer = TextBuffer::new("foo bar foo baz foo");
999        let mut state = SearchState::new();
1000        state.set_query("foo".to_string(), &buffer);
1001
1002        assert_eq!(state.match_count(), 3);
1003        assert_eq!(state.current_match_index, Some(0));
1004
1005        state.next_match();
1006        assert_eq!(state.current_match_index, Some(1));
1007
1008        state.next_match();
1009        assert_eq!(state.current_match_index, Some(2));
1010
1011        // Test wrap-around
1012        state.next_match();
1013        assert_eq!(state.current_match_index, Some(0));
1014
1015        // Test previous
1016        state.previous_match();
1017        assert_eq!(state.current_match_index, Some(2));
1018    }
1019
1020    #[test]
1021    fn test_select_match_near_cursor_uses_sorted_candidates() {
1022        let buffer = TextBuffer::new("foo\nnone\nfoo bar foo\nnone\nfoo");
1023        let mut state = SearchState::new();
1024        state.set_query("foo".to_string(), &buffer);
1025
1026        state.select_match_near_cursor((2, 7));
1027        assert_eq!(state.current_match_index, Some(2));
1028        assert_eq!(
1029            state.current_match(),
1030            Some(SearchMatch { line: 2, col: 8 })
1031        );
1032
1033        state.select_match_near_cursor((4, 0));
1034        assert_eq!(
1035            state.current_match(),
1036            Some(SearchMatch { line: 4, col: 0 })
1037        );
1038    }
1039
1040    #[test]
1041    fn test_search_state_toggle_case() {
1042        let buffer = TextBuffer::new("Hello hello");
1043        let mut state = SearchState::new();
1044        state.set_query("hello".to_string(), &buffer);
1045
1046        assert_eq!(state.match_count(), 2);
1047
1048        state.toggle_case_sensitive(&buffer);
1049        assert_eq!(state.match_count(), 1);
1050
1051        state.toggle_case_sensitive(&buffer);
1052        assert_eq!(state.match_count(), 2);
1053    }
1054
1055    #[test]
1056    fn test_incremental_match_update_replaces_only_affected_lines() {
1057        let mut buffer = TextBuffer::new("foo\nfoo\nfoo");
1058        let mut state = SearchState::new();
1059        state.set_query("foo".to_string(), &buffer);
1060
1061        buffer.insert_char(1, 1, 'x');
1062        state.update_matches_after_edit(&buffer, 1, 2);
1063
1064        assert_eq!(
1065            state.matches,
1066            vec![
1067                SearchMatch { line: 0, col: 0 },
1068                SearchMatch { line: 2, col: 0 },
1069            ]
1070        );
1071    }
1072
1073    #[test]
1074    fn test_incremental_match_update_shifts_suffix_after_newline() {
1075        let mut buffer = TextBuffer::new("foo\nbar\nfoo");
1076        let mut state = SearchState::new();
1077        state.set_query("foo".to_string(), &buffer);
1078
1079        buffer.insert_newline(0, 0);
1080        state.update_matches_after_edit(&buffer, 0, 2);
1081
1082        assert_eq!(
1083            state.matches,
1084            vec![
1085                SearchMatch { line: 1, col: 0 },
1086                SearchMatch { line: 3, col: 0 },
1087            ]
1088        );
1089    }
1090
1091    #[test]
1092    fn test_incremental_match_update_clamps_index_when_list_shrinks() {
1093        // Regression: `current_match_index` was only reset when the match
1094        // list became fully empty. When an edit shrinks it without emptying
1095        // it, a stale index past the end made `current_match()` return
1096        // `None` even though matches still exist.
1097        let mut buffer = TextBuffer::new("foo\nfoo\nfoo");
1098        let mut state = SearchState::new();
1099        state.set_query("foo".to_string(), &buffer);
1100        assert_eq!(state.matches.len(), 3);
1101        state.current_match_index = Some(2);
1102
1103        // Line 2's "foo" is edited away; only two matches remain.
1104        buffer.replace_range(2, 0, 3, "bar");
1105        state.update_matches_after_edit(&buffer, 2, 3);
1106
1107        assert_eq!(state.matches.len(), 2);
1108        assert_eq!(state.current_match_index, Some(1));
1109        assert_eq!(
1110            state.current_match(),
1111            Some(SearchMatch { line: 1, col: 0 })
1112        );
1113    }
1114
1115    #[test]
1116    fn test_find_matches_large_buffer_parallel() {
1117        // Create a buffer with PARALLEL_SEARCH_THRESHOLD * 2 lines (triggers parallel path)
1118        let mut content = String::new();
1119        let num_lines = PARALLEL_SEARCH_THRESHOLD * 2;
1120        for i in 0..num_lines {
1121            content.push_str(&format!("line {} foo\n", i));
1122        }
1123        let buffer = TextBuffer::new(&content);
1124
1125        let matches = find_matches(&buffer, "foo", false, None);
1126
1127        assert_eq!(matches.len(), num_lines);
1128        assert_eq!(matches[0].line, 0);
1129        assert_eq!(matches[num_lines - 1].line, num_lines - 1);
1130
1131        // Verify order is preserved (important!)
1132        for (i, m) in matches.iter().enumerate() {
1133            assert_eq!(m.line, i);
1134        }
1135    }
1136
1137    #[test]
1138    fn test_find_matches_limit() {
1139        // Create a buffer with more than MAX_MATCHES (10,000) matches
1140        // We'll put 11,000 "foo"s, one per line
1141        let mut content = String::new();
1142        for _ in 0..11_000 {
1143            content.push_str("foo\n");
1144        }
1145        let buffer = TextBuffer::new(&content);
1146
1147        let matches = find_matches(&buffer, "foo", false, Some(MAX_MATCHES));
1148
1149        // Should be capped at MAX_MATCHES
1150        assert_eq!(matches.len(), MAX_MATCHES);
1151    }
1152
1153    #[test]
1154    fn test_get_visible_match_range() {
1155        let matches = vec![
1156            SearchMatch { line: 1, col: 0 },
1157            SearchMatch { line: 2, col: 0 },
1158            SearchMatch { line: 5, col: 0 },
1159            SearchMatch { line: 5, col: 5 },
1160            SearchMatch { line: 10, col: 0 },
1161        ];
1162
1163        // All visible
1164        assert_eq!(get_visible_match_range(&matches, 0, 15), 0..5);
1165
1166        // None visible (before)
1167        assert_eq!(get_visible_match_range(&matches, 0, 0), 0..0);
1168
1169        // None visible (after)
1170        assert_eq!(get_visible_match_range(&matches, 11, 20), 5..5);
1171
1172        // None visible (middle gap)
1173        assert_eq!(get_visible_match_range(&matches, 3, 4), 2..2);
1174
1175        // Partial visible (start)
1176        assert_eq!(get_visible_match_range(&matches, 2, 10), 1..5);
1177
1178        // Partial visible (end)
1179        assert_eq!(get_visible_match_range(&matches, 0, 4), 0..2);
1180
1181        // Partial visible (middle)
1182        assert_eq!(get_visible_match_range(&matches, 2, 5), 1..4);
1183
1184        // Exact match line
1185        assert_eq!(get_visible_match_range(&matches, 5, 5), 2..4);
1186    }
1187
1188    #[test]
1189    fn test_get_visible_match_range_empty() {
1190        let matches = vec![];
1191        assert_eq!(get_visible_match_range(&matches, 0, 100), 0..0);
1192    }
1193
1194    #[test]
1195    fn test_is_search_open_tracks_both_ways_of_opening_the_dialog() {
1196        let mut editor = CodeEditor::new("fn main() {}", "rs");
1197        assert!(!editor.is_search_open());
1198
1199        let _task = editor.open_search_dialog();
1200        assert!(editor.is_search_open());
1201
1202        let _task = editor.close_search_dialog();
1203        assert!(!editor.is_search_open());
1204
1205        // The replace dialog is the same dialog with one more row, so the
1206        // predicate must report it as open too.
1207        let _task = editor.open_search_replace_dialog();
1208        assert!(editor.is_search_open());
1209    }
1210}
1211
1212#[cfg(test)]
1213mod advanced_state_tests {
1214    use super::*;
1215
1216    #[test]
1217    fn clearing_or_disabling_regex_discards_errors_and_stale_match_ranges() {
1218        let buffer = TextBuffer::new("aaa [");
1219        let mut state = SearchState::new();
1220        state.use_regex = true;
1221        state.set_query("a+".into(), &buffer);
1222        assert_eq!(state.match_end(state.matches[0]), (0, 3));
1223        state.set_query("[".into(), &buffer);
1224        assert!(state.pattern_error.is_some());
1225        assert!(state.matches.is_empty());
1226        assert_eq!(state.current_match_index, None);
1227        state.use_regex = false;
1228        state.update_matches(&buffer);
1229        assert!(state.pattern_error.is_none());
1230        assert_eq!(state.match_end(state.matches[0]), (0, 5));
1231        state.set_query(String::new(), &buffer);
1232        assert!(state.matches.is_empty());
1233        assert!(state.search_content.text().is_empty());
1234    }
1235
1236    #[test]
1237    fn multiline_selection_tracks_actual_range_and_cursor_inside_later_line() {
1238        let buffer = TextBuffer::new("xa\nb ya\nb");
1239        let mut state = SearchState::new();
1240        state.set_query("a\nb".into(), &buffer);
1241        assert_eq!(state.match_end(state.matches[0]), (1, 1));
1242        assert!(state.select_match_at_cursor((2, 1), Some(((1, 3), (2, 1)))));
1243        assert_eq!(state.current_match_index, Some(1));
1244        assert!(state.select_match_at_cursor((1, 0), None));
1245        assert_eq!(state.current_match_index, Some(0));
1246    }
1247
1248    #[test]
1249    fn advanced_matches_refresh_after_edits_that_shift_lines_or_cross_boundaries()
1250     {
1251        let mut buffer = TextBuffer::new("a\nb a\nb");
1252        let mut state = SearchState::new();
1253        state.set_query("a\nb".into(), &buffer);
1254        buffer.insert_newline(0, 0);
1255        state.update_matches_after_edit(&buffer, 0, 1);
1256        assert_eq!(
1257            state.matches,
1258            [SearchMatch { line: 1, col: 0 }, SearchMatch { line: 2, col: 2 }]
1259        );
1260        assert_eq!(state.match_end(state.matches[1]), (3, 1));
1261        buffer.delete_forward(1, 1);
1262        state.update_matches_after_edit(&buffer, 1, 3);
1263        assert_eq!(state.matches, [SearchMatch { line: 1, col: 3 }]);
1264        assert_eq!(state.match_end(state.matches[0]), (2, 1));
1265    }
1266}