1pub(crate) mod dialog;
9mod icons;
10mod pattern;
11pub(crate) mod shortcuts;
12mod update;
13
14use crate::buffer::TextBuffer;
15use crate::canvas_editor::{CodeEditor, Message};
16use iced::widget::Id;
17use std::borrow::Cow;
18use std::thread;
19
20#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24pub struct SearchMatch {
25 pub line: usize,
27 pub col: usize,
29}
30
31#[derive(Debug, Clone, Copy, PartialEq, Eq)]
33pub enum SearchFocusedField {
34 Search,
36 Replace,
38}
39
40#[derive(Debug, Clone)]
44pub struct SearchState {
45 pub query: String,
47 pub replace_with: String,
49 pub case_sensitive: bool,
51 pub whole_word: bool,
53 pub use_regex: bool,
55 pub multiline: bool,
57 pub search_content: iced::widget::text_editor::Content,
59 pub replace_content: iced::widget::text_editor::Content,
61 pub pattern_error: Option<String>,
63 details: Vec<pattern::MatchDetail>,
64 pub is_open: bool,
66 pub is_replace_mode: bool,
68 pub matches: Vec<SearchMatch>,
70 pub current_match_index: Option<usize>,
72 pub search_input_id: Id,
74 pub replace_input_id: Id,
76 pub focused_field: SearchFocusedField,
78 buffer_line_count: usize,
80}
81
82impl Default for SearchState {
83 fn default() -> Self {
84 Self {
85 query: String::new(),
86 replace_with: String::new(),
87 case_sensitive: false,
88 whole_word: false,
89 use_regex: false,
90 multiline: false,
91 search_content: iced::widget::text_editor::Content::new(),
92 replace_content: iced::widget::text_editor::Content::new(),
93 pattern_error: None,
94 details: Vec::new(),
95 is_open: false,
96 is_replace_mode: false,
97 matches: Vec::new(),
98 current_match_index: None,
99 search_input_id: Id::unique(),
100 replace_input_id: Id::unique(),
101 focused_field: SearchFocusedField::Search,
102 buffer_line_count: 0,
103 }
104 }
105}
106
107impl SearchState {
108 #[must_use]
110 pub fn new() -> Self {
111 Self::default()
112 }
113
114 pub fn open_search(&mut self) {
116 self.is_open = true;
117 self.is_replace_mode = false;
118 self.focused_field = SearchFocusedField::Search;
119 }
120
121 pub fn open_replace(&mut self) {
123 self.is_open = true;
124 self.is_replace_mode = true;
125 self.focused_field = SearchFocusedField::Search;
126 }
127
128 pub fn close(&mut self) {
130 self.is_open = false;
131 }
132
133 pub fn focus_next_field(&mut self) {
135 if self.is_replace_mode {
136 self.focused_field = match self.focused_field {
137 SearchFocusedField::Search => SearchFocusedField::Replace,
138 SearchFocusedField::Replace => SearchFocusedField::Search,
139 };
140 }
141 }
143
144 pub fn focus_previous_field(&mut self) {
146 if self.is_replace_mode {
147 self.focused_field = match self.focused_field {
148 SearchFocusedField::Search => SearchFocusedField::Replace,
149 SearchFocusedField::Replace => SearchFocusedField::Search,
150 };
151 }
152 }
154
155 pub fn set_query(&mut self, query: String, buffer: &TextBuffer) {
157 if self.search_content.text() != query {
158 self.search_content =
159 iced::widget::text_editor::Content::with_text(&query);
160 }
161 self.query = query;
162 self.update_matches(buffer);
163 }
164
165 pub fn set_replace_with(&mut self, replace_with: String) {
167 if self.replace_content.text() != replace_with {
168 self.replace_content =
169 iced::widget::text_editor::Content::with_text(&replace_with);
170 }
171 if !self.use_regex {
172 for detail in &mut self.details {
173 detail.replacement.clone_from(&replace_with);
174 }
175 }
176 self.replace_with = replace_with;
177 }
178
179 pub fn toggle_case_sensitive(&mut self, buffer: &TextBuffer) {
181 self.case_sensitive = !self.case_sensitive;
182 self.update_matches(buffer);
183 }
184
185 pub fn update_matches(&mut self, buffer: &TextBuffer) {
187 self.pattern_error = None;
188 if self.whole_word || self.use_regex || self.query.contains('\n') {
189 match pattern::find(self, buffer, Some(MAX_MATCHES)) {
190 Ok(details) => {
191 self.matches =
192 details.iter().map(|item| item.start).collect();
193 self.details = details;
194 }
195 Err(error) => {
196 self.matches.clear();
197 self.details.clear();
198 self.pattern_error = Some(error);
199 }
200 }
201 } else {
202 self.details.clear();
203 self.matches = find_matches(
204 buffer,
205 &self.query,
206 self.case_sensitive,
207 Some(MAX_MATCHES),
208 );
209 }
210 self.buffer_line_count = buffer.line_count();
211
212 if self.matches.is_empty() {
214 self.current_match_index = None;
215 } else if self.current_match_index.is_none() {
216 self.current_match_index = Some(0);
217 } else if let Some(idx) = self.current_match_index {
218 if idx >= self.matches.len() {
220 self.current_match_index =
221 Some(self.matches.len().saturating_sub(1));
222 }
223 }
224 }
225
226 pub(crate) fn update_matches_after_edit(
232 &mut self,
233 buffer: &TextBuffer,
234 start_line: usize,
235 old_end_exclusive: usize,
236 ) {
237 if self.query.is_empty()
238 || self.buffer_line_count == 0
239 || self.whole_word
240 || self.use_regex
241 || self.query.contains('\n')
242 {
243 self.update_matches(buffer);
244 return;
245 }
246
247 let old_line_count = self.buffer_line_count;
248 let new_line_count = buffer.line_count();
249 let start_line = start_line.min(old_line_count).min(new_line_count);
250 let old_end_exclusive =
251 old_end_exclusive.min(old_line_count).max(start_line);
252 let new_end_exclusive = if new_line_count >= old_line_count {
253 old_end_exclusive
254 .saturating_add(new_line_count - old_line_count)
255 .min(new_line_count)
256 } else {
257 old_end_exclusive
258 .saturating_sub(old_line_count - new_line_count)
259 .max(start_line)
260 .min(new_line_count)
261 };
262
263 let replace_start =
264 self.matches.partition_point(|item| item.line < start_line);
265 let replace_end =
266 self.matches.partition_point(|item| item.line < old_end_exclusive);
267 let replacement = find_matches_in_range(
268 buffer,
269 &self.query,
270 self.case_sensitive,
271 start_line,
272 new_end_exclusive,
273 Some(MAX_MATCHES),
274 );
275 let replacement_len = replacement.len();
276
277 self.matches.splice(replace_start..replace_end, replacement);
278 let shifted_suffix_start = replace_start + replacement_len;
279 for item in &mut self.matches[shifted_suffix_start..] {
280 item.line = if new_line_count >= old_line_count {
281 item.line.saturating_add(new_line_count - old_line_count)
282 } else {
283 item.line.saturating_sub(old_line_count - new_line_count)
284 };
285 }
286 self.matches.truncate(MAX_MATCHES);
287 self.buffer_line_count = new_line_count;
288
289 if self.matches.is_empty() {
294 self.current_match_index = None;
295 } else if let Some(idx) = self.current_match_index
296 && idx >= self.matches.len()
297 {
298 self.current_match_index = Some(self.matches.len() - 1);
299 }
300 }
301
302 pub fn next_match(&mut self) {
304 if self.matches.is_empty() {
305 return;
306 }
307
308 self.current_match_index = Some(match self.current_match_index {
309 Some(idx) => {
310 if idx + 1 >= self.matches.len() {
311 0 } else {
313 idx + 1
314 }
315 }
316 None => 0,
317 });
318 }
319
320 pub fn previous_match(&mut self) {
322 if self.matches.is_empty() {
323 return;
324 }
325
326 self.current_match_index = Some(match self.current_match_index {
327 Some(idx) => {
328 if idx == 0 {
329 self.matches.len() - 1 } else {
331 idx - 1
332 }
333 }
334 None => self.matches.len() - 1,
335 });
336 }
337
338 #[must_use]
340 pub fn current_match(&self) -> Option<SearchMatch> {
341 self.current_match_index.and_then(|idx| self.matches.get(idx).copied())
342 }
343
344 #[must_use]
346 pub fn match_count(&self) -> usize {
347 self.matches.len()
348 }
349
350 pub fn select_match_at_cursor(
361 &mut self,
362 cursor: (usize, usize),
363 selection: Option<((usize, usize), (usize, usize))>,
364 ) -> bool {
365 if self.matches.is_empty() || self.query.is_empty() {
366 return false;
367 }
368
369 let exact_selection_index = selection.and_then(|(start, end)| {
370 self.matches_on_line(start.0).find(|&index| {
371 let match_item = self.matches[index];
372 (match_item.line, match_item.col) == start
373 && self.match_end(match_item) == end
374 })
375 });
376 let containing_index = self.details.iter().position(|detail| {
377 (detail.start.line, detail.start.col) <= cursor
378 && cursor <= detail.end
379 });
380 let cursor_index =
381 exact_selection_index.or(containing_index).or_else(|| {
382 let line_matches = self.matches_on_line(cursor.0);
383 line_matches
384 .clone()
385 .find(|&index| {
386 let match_item = self.matches[index];
387 (match_item.col..=self.match_end(match_item).1)
388 .contains(&cursor.1)
389 })
390 .or_else(|| {
391 line_matches.min_by_key(|&index| {
392 let match_item = self.matches[index];
393 let match_end = self.match_end(match_item).1;
394 if cursor.1 < match_item.col {
395 match_item.col - cursor.1
396 } else {
397 cursor.1.saturating_sub(match_end)
398 }
399 })
400 })
401 });
402
403 let Some(index) = cursor_index else {
404 return false;
405 };
406 if self.current_match_index == Some(index) {
407 return false;
408 }
409
410 self.current_match_index = Some(index);
411 true
412 }
413
414 pub(crate) fn match_end(&self, item: SearchMatch) -> (usize, usize) {
416 self.details
417 .binary_search_by_key(&(item.line, item.col), |detail| {
418 (detail.start.line, detail.start.col)
419 })
420 .ok()
421 .map(|index| self.details[index].end)
422 .unwrap_or((item.line, item.col + self.query.chars().count()))
423 }
424
425 pub(crate) fn replacement(&self, item: SearchMatch) -> (usize, String) {
426 self.details
427 .binary_search_by_key(&(item.line, item.col), |detail| {
428 (detail.start.line, detail.start.col)
429 })
430 .ok()
431 .map(|index| {
432 (
433 self.details[index].len,
434 self.details[index].replacement.clone(),
435 )
436 })
437 .unwrap_or((self.query.chars().count(), self.replace_with.clone()))
438 }
439
440 fn matches_on_line(&self, line: usize) -> std::ops::Range<usize> {
442 let start = self.matches.partition_point(|item| item.line < line);
443 let end = self.matches.partition_point(|item| item.line <= line);
444 start..end
445 }
446
447 pub fn select_match_near_cursor(&mut self, cursor: (usize, usize)) {
452 if self.matches.is_empty() {
453 self.current_match_index = None;
454 return;
455 }
456
457 let (cursor_line, cursor_col) = cursor;
458 let insertion = self.matches.partition_point(|item| {
459 (item.line, item.col) < (cursor_line, cursor_col)
460 });
461 let mut left = insertion.checked_sub(1);
462 let mut right = (insertion < self.matches.len()).then_some(insertion);
463 let mut closest_index = insertion.min(self.matches.len() - 1);
464 let mut closest_distance = usize::MAX;
465
466 while left.is_some() || right.is_some() {
467 let left_line_distance = left.map_or(usize::MAX, |index| {
468 self.matches[index]
469 .line
470 .abs_diff(cursor_line)
471 .saturating_mul(1000)
472 });
473 let right_line_distance = right.map_or(usize::MAX, |index| {
474 self.matches[index]
475 .line
476 .abs_diff(cursor_line)
477 .saturating_mul(1000)
478 });
479
480 if left_line_distance.min(right_line_distance) > closest_distance {
481 break;
482 }
483
484 let index = match (left, right) {
485 (Some(index), Some(_))
486 if left_line_distance <= right_line_distance =>
487 {
488 left = index.checked_sub(1);
489 index
490 }
491 (_, Some(index)) => {
492 right =
493 (index + 1 < self.matches.len()).then_some(index + 1);
494 index
495 }
496 (Some(index), None) => {
497 left = index.checked_sub(1);
498 index
499 }
500 (None, None) => break,
501 };
502 let item = self.matches[index];
503 let distance = item
504 .line
505 .abs_diff(cursor_line)
506 .saturating_mul(1000)
507 .saturating_add(item.col.abs_diff(cursor_col));
508 if distance < closest_distance {
509 closest_distance = distance;
510 closest_index = index;
511 if distance == 0 {
512 break;
513 }
514 }
515 }
516
517 self.current_match_index = Some(closest_index);
518 }
519}
520
521#[must_use]
534pub fn find_matches(
535 buffer: &TextBuffer,
536 query: &str,
537 case_sensitive: bool,
538 limit: Option<usize>,
539) -> Vec<SearchMatch> {
540 if query.is_empty() {
541 return Vec::new();
542 }
543
544 let line_count = buffer.line_count();
545
546 if line_count > PARALLEL_SEARCH_THRESHOLD {
549 let num_threads =
550 std::thread::available_parallelism().map(|n| n.get()).unwrap_or(1);
551
552 if num_threads > 1 {
553 let chunk_size = line_count.div_ceil(num_threads);
554
555 return thread::scope(|s| {
556 let mut handles = Vec::with_capacity(num_threads);
557
558 for i in 0..num_threads {
559 let start = i * chunk_size;
560 let end = (start + chunk_size).min(line_count);
561
562 if start >= end {
563 break;
564 }
565
566 handles.push(s.spawn(move || {
567 find_matches_in_range(
568 buffer,
569 query,
570 case_sensitive,
571 start,
572 end,
573 limit,
574 )
575 }));
576 }
577
578 let mut matches = Vec::new();
579 for handle in handles {
580 if let Ok(mut chunk_matches) = handle.join() {
581 matches.append(&mut chunk_matches);
582 if let Some(l) = limit
583 && matches.len() >= l
584 {
585 matches.truncate(l);
586 break;
587 }
588 }
589 }
590 matches
591 });
592 }
593 }
594
595 find_matches_in_range(buffer, query, case_sensitive, 0, line_count, limit)
596}
597
598const PARALLEL_SEARCH_THRESHOLD: usize = 1000;
600
601pub const MAX_MATCHES: usize = 10_000;
603
604pub fn get_visible_match_range(
609 matches: &[SearchMatch],
610 min_logical_line: usize,
611 max_logical_line: usize,
612) -> std::ops::Range<usize> {
613 if matches.is_empty() {
614 return 0..0;
615 }
616
617 let start_idx = matches.partition_point(|m| m.line < min_logical_line);
619
620 let mut end_idx = start_idx;
623 for match_item in matches.iter().skip(start_idx) {
624 if match_item.line > max_logical_line {
625 break;
626 }
627 end_idx += 1;
628 }
629
630 start_idx..end_idx
631}
632
633fn find_matches_in_range(
634 buffer: &TextBuffer,
635 query: &str,
636 case_sensitive: bool,
637 start_line: usize,
638 end_line: usize,
639 limit: Option<usize>,
640) -> Vec<SearchMatch> {
641 let mut matches = Vec::new();
642 let search_query = if case_sensitive {
643 Cow::Borrowed(query)
644 } else {
645 Cow::Owned(query.to_lowercase())
646 };
647
648 for line_idx in start_line..end_line {
649 if let Some(l) = limit
651 && matches.len() >= l
652 {
653 break;
654 }
655
656 let line = buffer.line(line_idx);
657
658 if line.len() < query.len() {
660 continue;
661 }
662
663 if case_sensitive {
664 find_matches_case_sensitive(
665 line,
666 search_query.as_ref(),
667 line_idx,
668 &mut matches,
669 );
670 } else {
671 find_matches_case_insensitive(
672 line,
673 search_query.as_ref(),
674 line_idx,
675 &mut matches,
676 );
677 }
678 }
679
680 matches
681}
682
683fn find_matches_case_sensitive(
689 line: &str,
690 search_query: &str,
691 line_idx: usize,
692 matches: &mut Vec<SearchMatch>,
693) {
694 let mut start_pos = 0;
695 while let Some(relative_pos) = line[start_pos..].find(search_query) {
696 let absolute_pos = start_pos + relative_pos;
697 let col = line[..absolute_pos].chars().count();
698 matches.push(SearchMatch { line: line_idx, col });
699 start_pos = absolute_pos + search_query.len();
700 }
701}
702
703fn find_matches_case_insensitive(
715 line: &str,
716 search_query: &str,
717 line_idx: usize,
718 matches: &mut Vec<SearchMatch>,
719) {
720 if line.is_ascii() {
724 let search_line = line.to_ascii_lowercase();
725 let mut start_pos = 0;
726 while let Some(relative_pos) =
727 search_line[start_pos..].find(search_query)
728 {
729 let absolute_pos = start_pos + relative_pos;
730 matches.push(SearchMatch { line: line_idx, col: absolute_pos });
731 start_pos = absolute_pos + search_query.len();
732 }
733 return;
734 }
735
736 let mut search_line = String::with_capacity(line.len());
737 let mut boundaries: Vec<(usize, usize)> =
738 Vec::with_capacity(line.len() + 1);
739 for (char_idx, ch) in line.chars().enumerate() {
740 boundaries.push((search_line.len(), char_idx));
741 for lower_ch in ch.to_lowercase() {
742 search_line.push(lower_ch);
743 }
744 }
745 boundaries.push((search_line.len(), line.chars().count()));
746
747 let mut start_pos = 0;
748 while let Some(relative_pos) = search_line[start_pos..].find(search_query) {
749 let absolute_pos = start_pos + relative_pos;
750 let col = match boundaries
751 .binary_search_by_key(&absolute_pos, |&(byte, _)| byte)
752 {
753 Ok(idx) => boundaries[idx].1,
754 Err(idx) => boundaries[idx.saturating_sub(1)].1,
755 };
756 matches.push(SearchMatch { line: line_idx, col });
757 start_pos = absolute_pos + search_query.len();
758 }
759}
760
761impl CodeEditor {
762 pub(crate) fn refresh_search_matches_if_needed(&mut self) {
768 if self.search_matches_visible() && !self.search_state.query.is_empty()
769 {
770 let start_line = self.pre_edit_line.saturating_sub(1);
771 let old_end_exclusive = self.pre_edit_last_line.saturating_add(2);
772 self.search_state.update_matches_after_edit(
773 &self.buffer,
774 start_line,
775 old_end_exclusive,
776 );
777
778 self.search_state
780 .select_match_near_cursor(self.cursors.primary_position());
781 }
782 }
783
784 pub(crate) fn search_matches_visible(&self) -> bool {
785 self.search_state.is_open
786 || (self.vim_enabled && self.vim_state.last_search().is_some())
787 }
788
789 #[must_use]
813 pub fn is_search_open(&self) -> bool {
814 self.search_state.is_open
815 }
816
817 pub fn open_search_dialog(&mut self) -> iced::Task<Message> {
839 self.update(&Message::OpenSearch)
840 }
841
842 pub fn open_search_replace_dialog(&mut self) -> iced::Task<Message> {
864 self.update(&Message::OpenSearchReplace)
865 }
866
867 pub fn close_search_dialog(&mut self) -> iced::Task<Message> {
886 self.update(&Message::CloseSearch)
887 }
888}
889
890#[cfg(test)]
891mod tests {
892 use super::*;
893
894 #[test]
895 fn test_find_matches_case_sensitive() {
896 let buffer = TextBuffer::new("Hello World\nhello world");
897 let matches = find_matches(&buffer, "hello", true, None);
898
899 assert_eq!(matches.len(), 1);
900 assert_eq!(matches[0].line, 1);
901 assert_eq!(matches[0].col, 0);
902 }
903
904 #[test]
905 fn test_find_matches_case_insensitive() {
906 let buffer = TextBuffer::new("Hello World\nhello world");
907 let matches = find_matches(&buffer, "hello", false, None);
908
909 assert_eq!(matches.len(), 2);
910 assert_eq!(matches[0].line, 0);
911 assert_eq!(matches[0].col, 0);
912 assert_eq!(matches[1].line, 1);
913 assert_eq!(matches[1].col, 0);
914 }
915
916 #[test]
917 fn test_find_matches_case_insensitive_unicode_length_changing() {
918 let buffer = TextBuffer::new("İstanbul");
925 let matches = find_matches(&buffer, "tanbul", false, None);
926
927 assert_eq!(matches.len(), 1);
928 assert_eq!(matches[0].line, 0);
929 assert_eq!(matches[0].col, 2);
930 }
931
932 #[test]
933 fn test_find_matches_case_insensitive_unicode_match_starts_after_expansion()
934 {
935 let buffer = TextBuffer::new("İSTANBUL");
939 let matches = find_matches(&buffer, "istanbul", false, None);
940
941 assert!(matches.is_empty());
945 }
946
947 #[test]
948 fn test_find_matches_case_insensitive_unicode_byte_shrinking() {
949 let buffer = TextBuffer::new("StraẞE");
953 let matches = find_matches(&buffer, "e", false, None);
954
955 assert_eq!(matches.len(), 1);
956 assert_eq!(matches[0].col, 5);
957 }
958
959 #[test]
960 fn test_find_matches_multiple_occurrences() {
961 let buffer = TextBuffer::new("foo bar foo baz foo");
962 let matches = find_matches(&buffer, "foo", false, None);
963
964 assert_eq!(matches.len(), 3);
965 assert_eq!(matches[0].col, 0);
966 assert_eq!(matches[1].col, 8);
967 assert_eq!(matches[2].col, 16);
968 }
969
970 #[test]
971 fn test_find_matches_multiline() {
972 let buffer = TextBuffer::new("line1\nfoo\nline3\nfoo");
973 let matches = find_matches(&buffer, "foo", false, None);
974
975 assert_eq!(matches.len(), 2);
976 assert_eq!(matches[0].line, 1);
977 assert_eq!(matches[1].line, 3);
978 }
979
980 #[test]
981 fn test_find_matches_empty_query() {
982 let buffer = TextBuffer::new("Hello World");
983 let matches = find_matches(&buffer, "", false, None);
984
985 assert_eq!(matches.len(), 0);
986 }
987
988 #[test]
989 fn test_find_matches_no_results() {
990 let buffer = TextBuffer::new("Hello World");
991 let matches = find_matches(&buffer, "xyz", false, None);
992
993 assert_eq!(matches.len(), 0);
994 }
995
996 #[test]
997 fn test_search_state_navigation() {
998 let buffer = TextBuffer::new("foo bar foo baz foo");
999 let mut state = SearchState::new();
1000 state.set_query("foo".to_string(), &buffer);
1001
1002 assert_eq!(state.match_count(), 3);
1003 assert_eq!(state.current_match_index, Some(0));
1004
1005 state.next_match();
1006 assert_eq!(state.current_match_index, Some(1));
1007
1008 state.next_match();
1009 assert_eq!(state.current_match_index, Some(2));
1010
1011 state.next_match();
1013 assert_eq!(state.current_match_index, Some(0));
1014
1015 state.previous_match();
1017 assert_eq!(state.current_match_index, Some(2));
1018 }
1019
1020 #[test]
1021 fn test_select_match_near_cursor_uses_sorted_candidates() {
1022 let buffer = TextBuffer::new("foo\nnone\nfoo bar foo\nnone\nfoo");
1023 let mut state = SearchState::new();
1024 state.set_query("foo".to_string(), &buffer);
1025
1026 state.select_match_near_cursor((2, 7));
1027 assert_eq!(state.current_match_index, Some(2));
1028 assert_eq!(
1029 state.current_match(),
1030 Some(SearchMatch { line: 2, col: 8 })
1031 );
1032
1033 state.select_match_near_cursor((4, 0));
1034 assert_eq!(
1035 state.current_match(),
1036 Some(SearchMatch { line: 4, col: 0 })
1037 );
1038 }
1039
1040 #[test]
1041 fn test_search_state_toggle_case() {
1042 let buffer = TextBuffer::new("Hello hello");
1043 let mut state = SearchState::new();
1044 state.set_query("hello".to_string(), &buffer);
1045
1046 assert_eq!(state.match_count(), 2);
1047
1048 state.toggle_case_sensitive(&buffer);
1049 assert_eq!(state.match_count(), 1);
1050
1051 state.toggle_case_sensitive(&buffer);
1052 assert_eq!(state.match_count(), 2);
1053 }
1054
1055 #[test]
1056 fn test_incremental_match_update_replaces_only_affected_lines() {
1057 let mut buffer = TextBuffer::new("foo\nfoo\nfoo");
1058 let mut state = SearchState::new();
1059 state.set_query("foo".to_string(), &buffer);
1060
1061 buffer.insert_char(1, 1, 'x');
1062 state.update_matches_after_edit(&buffer, 1, 2);
1063
1064 assert_eq!(
1065 state.matches,
1066 vec![
1067 SearchMatch { line: 0, col: 0 },
1068 SearchMatch { line: 2, col: 0 },
1069 ]
1070 );
1071 }
1072
1073 #[test]
1074 fn test_incremental_match_update_shifts_suffix_after_newline() {
1075 let mut buffer = TextBuffer::new("foo\nbar\nfoo");
1076 let mut state = SearchState::new();
1077 state.set_query("foo".to_string(), &buffer);
1078
1079 buffer.insert_newline(0, 0);
1080 state.update_matches_after_edit(&buffer, 0, 2);
1081
1082 assert_eq!(
1083 state.matches,
1084 vec![
1085 SearchMatch { line: 1, col: 0 },
1086 SearchMatch { line: 3, col: 0 },
1087 ]
1088 );
1089 }
1090
1091 #[test]
1092 fn test_incremental_match_update_clamps_index_when_list_shrinks() {
1093 let mut buffer = TextBuffer::new("foo\nfoo\nfoo");
1098 let mut state = SearchState::new();
1099 state.set_query("foo".to_string(), &buffer);
1100 assert_eq!(state.matches.len(), 3);
1101 state.current_match_index = Some(2);
1102
1103 buffer.replace_range(2, 0, 3, "bar");
1105 state.update_matches_after_edit(&buffer, 2, 3);
1106
1107 assert_eq!(state.matches.len(), 2);
1108 assert_eq!(state.current_match_index, Some(1));
1109 assert_eq!(
1110 state.current_match(),
1111 Some(SearchMatch { line: 1, col: 0 })
1112 );
1113 }
1114
1115 #[test]
1116 fn test_find_matches_large_buffer_parallel() {
1117 let mut content = String::new();
1119 let num_lines = PARALLEL_SEARCH_THRESHOLD * 2;
1120 for i in 0..num_lines {
1121 content.push_str(&format!("line {} foo\n", i));
1122 }
1123 let buffer = TextBuffer::new(&content);
1124
1125 let matches = find_matches(&buffer, "foo", false, None);
1126
1127 assert_eq!(matches.len(), num_lines);
1128 assert_eq!(matches[0].line, 0);
1129 assert_eq!(matches[num_lines - 1].line, num_lines - 1);
1130
1131 for (i, m) in matches.iter().enumerate() {
1133 assert_eq!(m.line, i);
1134 }
1135 }
1136
1137 #[test]
1138 fn test_find_matches_limit() {
1139 let mut content = String::new();
1142 for _ in 0..11_000 {
1143 content.push_str("foo\n");
1144 }
1145 let buffer = TextBuffer::new(&content);
1146
1147 let matches = find_matches(&buffer, "foo", false, Some(MAX_MATCHES));
1148
1149 assert_eq!(matches.len(), MAX_MATCHES);
1151 }
1152
1153 #[test]
1154 fn test_get_visible_match_range() {
1155 let matches = vec![
1156 SearchMatch { line: 1, col: 0 },
1157 SearchMatch { line: 2, col: 0 },
1158 SearchMatch { line: 5, col: 0 },
1159 SearchMatch { line: 5, col: 5 },
1160 SearchMatch { line: 10, col: 0 },
1161 ];
1162
1163 assert_eq!(get_visible_match_range(&matches, 0, 15), 0..5);
1165
1166 assert_eq!(get_visible_match_range(&matches, 0, 0), 0..0);
1168
1169 assert_eq!(get_visible_match_range(&matches, 11, 20), 5..5);
1171
1172 assert_eq!(get_visible_match_range(&matches, 3, 4), 2..2);
1174
1175 assert_eq!(get_visible_match_range(&matches, 2, 10), 1..5);
1177
1178 assert_eq!(get_visible_match_range(&matches, 0, 4), 0..2);
1180
1181 assert_eq!(get_visible_match_range(&matches, 2, 5), 1..4);
1183
1184 assert_eq!(get_visible_match_range(&matches, 5, 5), 2..4);
1186 }
1187
1188 #[test]
1189 fn test_get_visible_match_range_empty() {
1190 let matches = vec![];
1191 assert_eq!(get_visible_match_range(&matches, 0, 100), 0..0);
1192 }
1193
1194 #[test]
1195 fn test_is_search_open_tracks_both_ways_of_opening_the_dialog() {
1196 let mut editor = CodeEditor::new("fn main() {}", "rs");
1197 assert!(!editor.is_search_open());
1198
1199 let _task = editor.open_search_dialog();
1200 assert!(editor.is_search_open());
1201
1202 let _task = editor.close_search_dialog();
1203 assert!(!editor.is_search_open());
1204
1205 let _task = editor.open_search_replace_dialog();
1208 assert!(editor.is_search_open());
1209 }
1210}
1211
1212#[cfg(test)]
1213mod advanced_state_tests {
1214 use super::*;
1215
1216 #[test]
1217 fn clearing_or_disabling_regex_discards_errors_and_stale_match_ranges() {
1218 let buffer = TextBuffer::new("aaa [");
1219 let mut state = SearchState::new();
1220 state.use_regex = true;
1221 state.set_query("a+".into(), &buffer);
1222 assert_eq!(state.match_end(state.matches[0]), (0, 3));
1223 state.set_query("[".into(), &buffer);
1224 assert!(state.pattern_error.is_some());
1225 assert!(state.matches.is_empty());
1226 assert_eq!(state.current_match_index, None);
1227 state.use_regex = false;
1228 state.update_matches(&buffer);
1229 assert!(state.pattern_error.is_none());
1230 assert_eq!(state.match_end(state.matches[0]), (0, 5));
1231 state.set_query(String::new(), &buffer);
1232 assert!(state.matches.is_empty());
1233 assert!(state.search_content.text().is_empty());
1234 }
1235
1236 #[test]
1237 fn multiline_selection_tracks_actual_range_and_cursor_inside_later_line() {
1238 let buffer = TextBuffer::new("xa\nb ya\nb");
1239 let mut state = SearchState::new();
1240 state.set_query("a\nb".into(), &buffer);
1241 assert_eq!(state.match_end(state.matches[0]), (1, 1));
1242 assert!(state.select_match_at_cursor((2, 1), Some(((1, 3), (2, 1)))));
1243 assert_eq!(state.current_match_index, Some(1));
1244 assert!(state.select_match_at_cursor((1, 0), None));
1245 assert_eq!(state.current_match_index, Some(0));
1246 }
1247
1248 #[test]
1249 fn advanced_matches_refresh_after_edits_that_shift_lines_or_cross_boundaries()
1250 {
1251 let mut buffer = TextBuffer::new("a\nb a\nb");
1252 let mut state = SearchState::new();
1253 state.set_query("a\nb".into(), &buffer);
1254 buffer.insert_newline(0, 0);
1255 state.update_matches_after_edit(&buffer, 0, 1);
1256 assert_eq!(
1257 state.matches,
1258 [SearchMatch { line: 1, col: 0 }, SearchMatch { line: 2, col: 2 }]
1259 );
1260 assert_eq!(state.match_end(state.matches[1]), (3, 1));
1261 buffer.delete_forward(1, 1);
1262 state.update_matches_after_edit(&buffer, 1, 3);
1263 assert_eq!(state.matches, [SearchMatch { line: 1, col: 3 }]);
1264 assert_eq!(state.match_end(state.matches[0]), (2, 1));
1265 }
1266}