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