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