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    /// Opens the search dialog programmatically.
707    ///
708    /// This is useful when wiring your own UI button instead of relying on
709    /// keyboard shortcuts.
710    ///
711    /// # Returns
712    ///
713    /// A `Task<Message>` that focuses the search input.
714    pub fn open_search_dialog(&mut self) -> iced::Task<Message> {
715        self.update(&Message::OpenSearch)
716    }
717
718    /// Opens the search-and-replace dialog programmatically.
719    ///
720    /// This is useful when wiring your own UI button instead of relying on
721    /// keyboard shortcuts.
722    ///
723    /// # Returns
724    ///
725    /// A `Task<Message>` that focuses the search input.
726    pub fn open_search_replace_dialog(&mut self) -> iced::Task<Message> {
727        self.update(&Message::OpenSearchReplace)
728    }
729
730    /// Closes the search dialog programmatically.
731    ///
732    /// # Returns
733    ///
734    /// A `Task<Message>` for any follow-up UI work.
735    pub fn close_search_dialog(&mut self) -> iced::Task<Message> {
736        self.update(&Message::CloseSearch)
737    }
738}
739
740#[cfg(test)]
741mod tests {
742    use super::*;
743
744    #[test]
745    fn test_find_matches_case_sensitive() {
746        let buffer = TextBuffer::new("Hello World\nhello world");
747        let matches = find_matches(&buffer, "hello", true, None);
748
749        assert_eq!(matches.len(), 1);
750        assert_eq!(matches[0].line, 1);
751        assert_eq!(matches[0].col, 0);
752    }
753
754    #[test]
755    fn test_find_matches_case_insensitive() {
756        let buffer = TextBuffer::new("Hello World\nhello world");
757        let matches = find_matches(&buffer, "hello", false, None);
758
759        assert_eq!(matches.len(), 2);
760        assert_eq!(matches[0].line, 0);
761        assert_eq!(matches[0].col, 0);
762        assert_eq!(matches[1].line, 1);
763        assert_eq!(matches[1].col, 0);
764    }
765
766    #[test]
767    fn test_find_matches_case_insensitive_unicode_length_changing() {
768        // 'İ' (U+0130) lowercases to "i" + a combining dot above (U+0307):
769        // one character becomes two. Searching for "tanbul" still matches
770        // (the combining mark only affects the leading "İ"/"i"), which lets
771        // us check that the reported column is computed against the
772        // *original* line ("İstanbul": İ=0, s=1, t=2) rather than drifting
773        // by the length the lowercased prefix gained.
774        let buffer = TextBuffer::new("İstanbul");
775        let matches = find_matches(&buffer, "tanbul", false, None);
776
777        assert_eq!(matches.len(), 1);
778        assert_eq!(matches[0].line, 0);
779        assert_eq!(matches[0].col, 2);
780    }
781
782    #[test]
783    fn test_find_matches_case_insensitive_unicode_match_starts_after_expansion()
784    {
785        // The character whose lowercase form changes length ('İ') sits right
786        // before the match itself, so the reported column must point at the
787        // first lowercased character of the match, not the lowercased 'İ'.
788        let buffer = TextBuffer::new("İSTANBUL");
789        let matches = find_matches(&buffer, "istanbul", false, None);
790
791        // "İstanbul".to_lowercase() is "i\u{307}stanbul" (combining dot),
792        // which does not literally contain "istanbul" — so there is no match.
793        // This documents that behavior rather than assuming a match exists.
794        assert!(matches.is_empty());
795    }
796
797    #[test]
798    fn test_find_matches_case_insensitive_unicode_byte_shrinking() {
799        // 'ẞ' (U+1E9E, capital sharp S) lowercases to 'ß' — same character
800        // count, but fewer bytes (3 -> 2). This exercises the opposite
801        // direction of length change from the 'İ' case above.
802        let buffer = TextBuffer::new("StraẞE");
803        let matches = find_matches(&buffer, "e", false, None);
804
805        assert_eq!(matches.len(), 1);
806        assert_eq!(matches[0].col, 5);
807    }
808
809    #[test]
810    fn test_find_matches_multiple_occurrences() {
811        let buffer = TextBuffer::new("foo bar foo baz foo");
812        let matches = find_matches(&buffer, "foo", false, None);
813
814        assert_eq!(matches.len(), 3);
815        assert_eq!(matches[0].col, 0);
816        assert_eq!(matches[1].col, 8);
817        assert_eq!(matches[2].col, 16);
818    }
819
820    #[test]
821    fn test_find_matches_multiline() {
822        let buffer = TextBuffer::new("line1\nfoo\nline3\nfoo");
823        let matches = find_matches(&buffer, "foo", false, None);
824
825        assert_eq!(matches.len(), 2);
826        assert_eq!(matches[0].line, 1);
827        assert_eq!(matches[1].line, 3);
828    }
829
830    #[test]
831    fn test_find_matches_empty_query() {
832        let buffer = TextBuffer::new("Hello World");
833        let matches = find_matches(&buffer, "", false, None);
834
835        assert_eq!(matches.len(), 0);
836    }
837
838    #[test]
839    fn test_find_matches_no_results() {
840        let buffer = TextBuffer::new("Hello World");
841        let matches = find_matches(&buffer, "xyz", false, None);
842
843        assert_eq!(matches.len(), 0);
844    }
845
846    #[test]
847    fn test_search_state_navigation() {
848        let buffer = TextBuffer::new("foo bar foo baz foo");
849        let mut state = SearchState::new();
850        state.set_query("foo".to_string(), &buffer);
851
852        assert_eq!(state.match_count(), 3);
853        assert_eq!(state.current_match_index, Some(0));
854
855        state.next_match();
856        assert_eq!(state.current_match_index, Some(1));
857
858        state.next_match();
859        assert_eq!(state.current_match_index, Some(2));
860
861        // Test wrap-around
862        state.next_match();
863        assert_eq!(state.current_match_index, Some(0));
864
865        // Test previous
866        state.previous_match();
867        assert_eq!(state.current_match_index, Some(2));
868    }
869
870    #[test]
871    fn test_select_match_near_cursor_uses_sorted_candidates() {
872        let buffer = TextBuffer::new("foo\nnone\nfoo bar foo\nnone\nfoo");
873        let mut state = SearchState::new();
874        state.set_query("foo".to_string(), &buffer);
875
876        state.select_match_near_cursor((2, 7));
877        assert_eq!(state.current_match_index, Some(2));
878        assert_eq!(
879            state.current_match(),
880            Some(SearchMatch { line: 2, col: 8 })
881        );
882
883        state.select_match_near_cursor((4, 0));
884        assert_eq!(
885            state.current_match(),
886            Some(SearchMatch { line: 4, col: 0 })
887        );
888    }
889
890    #[test]
891    fn test_search_state_toggle_case() {
892        let buffer = TextBuffer::new("Hello hello");
893        let mut state = SearchState::new();
894        state.set_query("hello".to_string(), &buffer);
895
896        assert_eq!(state.match_count(), 2);
897
898        state.toggle_case_sensitive(&buffer);
899        assert_eq!(state.match_count(), 1);
900
901        state.toggle_case_sensitive(&buffer);
902        assert_eq!(state.match_count(), 2);
903    }
904
905    #[test]
906    fn test_incremental_match_update_replaces_only_affected_lines() {
907        let mut buffer = TextBuffer::new("foo\nfoo\nfoo");
908        let mut state = SearchState::new();
909        state.set_query("foo".to_string(), &buffer);
910
911        buffer.insert_char(1, 1, 'x');
912        state.update_matches_after_edit(&buffer, 1, 2);
913
914        assert_eq!(
915            state.matches,
916            vec![
917                SearchMatch { line: 0, col: 0 },
918                SearchMatch { line: 2, col: 0 },
919            ]
920        );
921    }
922
923    #[test]
924    fn test_incremental_match_update_shifts_suffix_after_newline() {
925        let mut buffer = TextBuffer::new("foo\nbar\nfoo");
926        let mut state = SearchState::new();
927        state.set_query("foo".to_string(), &buffer);
928
929        buffer.insert_newline(0, 0);
930        state.update_matches_after_edit(&buffer, 0, 2);
931
932        assert_eq!(
933            state.matches,
934            vec![
935                SearchMatch { line: 1, col: 0 },
936                SearchMatch { line: 3, col: 0 },
937            ]
938        );
939    }
940
941    #[test]
942    fn test_incremental_match_update_clamps_index_when_list_shrinks() {
943        // Regression: `current_match_index` was only reset when the match
944        // list became fully empty. When an edit shrinks it without emptying
945        // it, a stale index past the end made `current_match()` return
946        // `None` even though matches still exist.
947        let mut buffer = TextBuffer::new("foo\nfoo\nfoo");
948        let mut state = SearchState::new();
949        state.set_query("foo".to_string(), &buffer);
950        assert_eq!(state.matches.len(), 3);
951        state.current_match_index = Some(2);
952
953        // Line 2's "foo" is edited away; only two matches remain.
954        buffer.replace_range(2, 0, 3, "bar");
955        state.update_matches_after_edit(&buffer, 2, 3);
956
957        assert_eq!(state.matches.len(), 2);
958        assert_eq!(state.current_match_index, Some(1));
959        assert_eq!(
960            state.current_match(),
961            Some(SearchMatch { line: 1, col: 0 })
962        );
963    }
964
965    #[test]
966    fn test_find_matches_large_buffer_parallel() {
967        // Create a buffer with PARALLEL_SEARCH_THRESHOLD * 2 lines (triggers parallel path)
968        let mut content = String::new();
969        let num_lines = PARALLEL_SEARCH_THRESHOLD * 2;
970        for i in 0..num_lines {
971            content.push_str(&format!("line {} foo\n", i));
972        }
973        let buffer = TextBuffer::new(&content);
974
975        let matches = find_matches(&buffer, "foo", false, None);
976
977        assert_eq!(matches.len(), num_lines);
978        assert_eq!(matches[0].line, 0);
979        assert_eq!(matches[num_lines - 1].line, num_lines - 1);
980
981        // Verify order is preserved (important!)
982        for (i, m) in matches.iter().enumerate() {
983            assert_eq!(m.line, i);
984        }
985    }
986
987    #[test]
988    fn test_find_matches_limit() {
989        // Create a buffer with more than MAX_MATCHES (10,000) matches
990        // We'll put 11,000 "foo"s, one per line
991        let mut content = String::new();
992        for _ in 0..11_000 {
993            content.push_str("foo\n");
994        }
995        let buffer = TextBuffer::new(&content);
996
997        let matches = find_matches(&buffer, "foo", false, Some(MAX_MATCHES));
998
999        // Should be capped at MAX_MATCHES
1000        assert_eq!(matches.len(), MAX_MATCHES);
1001    }
1002
1003    #[test]
1004    fn test_get_visible_match_range() {
1005        let matches = vec![
1006            SearchMatch { line: 1, col: 0 },
1007            SearchMatch { line: 2, col: 0 },
1008            SearchMatch { line: 5, col: 0 },
1009            SearchMatch { line: 5, col: 5 },
1010            SearchMatch { line: 10, col: 0 },
1011        ];
1012
1013        // All visible
1014        assert_eq!(get_visible_match_range(&matches, 0, 15), 0..5);
1015
1016        // None visible (before)
1017        assert_eq!(get_visible_match_range(&matches, 0, 0), 0..0);
1018
1019        // None visible (after)
1020        assert_eq!(get_visible_match_range(&matches, 11, 20), 5..5);
1021
1022        // None visible (middle gap)
1023        assert_eq!(get_visible_match_range(&matches, 3, 4), 2..2);
1024
1025        // Partial visible (start)
1026        assert_eq!(get_visible_match_range(&matches, 2, 10), 1..5);
1027
1028        // Partial visible (end)
1029        assert_eq!(get_visible_match_range(&matches, 0, 4), 0..2);
1030
1031        // Partial visible (middle)
1032        assert_eq!(get_visible_match_range(&matches, 2, 5), 1..4);
1033
1034        // Exact match line
1035        assert_eq!(get_visible_match_range(&matches, 5, 5), 2..4);
1036    }
1037
1038    #[test]
1039    fn test_get_visible_match_range_empty() {
1040        let matches = vec![];
1041        assert_eq!(get_visible_match_range(&matches, 0, 100), 0..0);
1042    }
1043}