1use language::{Point, TextBufferSnapshot};
2use std::{cmp, ops::Range};
3
4const REPLACEMENT_COST: u32 = 1;
5const INSERTION_COST: u32 = 3;
6const DELETION_COST: u32 = 10;
7
8/// A streaming fuzzy matcher that can process text chunks incrementally
9/// and return the best match found so far at each step.
10pub struct StreamingFuzzyMatcher {
11 snapshot: TextBufferSnapshot,
12 query_lines: Vec<String>,
13 line_hint: Option<u32>,
14 incomplete_line: String,
15 matches: Vec<Range<usize>>,
16 matrix: SearchMatrix,
17}
18
19impl StreamingFuzzyMatcher {
20 pub fn new(snapshot: TextBufferSnapshot) -> Self {
21 let buffer_line_count = snapshot.max_point().row as usize + 1;
22 Self {
23 snapshot,
24 query_lines: Vec::new(),
25 line_hint: None,
26 incomplete_line: String::new(),
27 matches: Vec::new(),
28 matrix: SearchMatrix::new(buffer_line_count + 1),
29 }
30 }
31
32 /// Returns the query lines.
33 pub fn query_lines(&self) -> &[String] {
34 &self.query_lines
35 }
36
37 /// Push a new chunk of text and get the best match found so far.
38 ///
39 /// This method accumulates text chunks and processes complete lines.
40 /// Partial lines are buffered internally until a newline is received.
41 ///
42 /// # Returns
43 ///
44 /// Returns `Some(range)` if a match has been found with the accumulated
45 /// query so far, or `None` if no suitable match exists yet.
46 pub fn push(&mut self, chunk: &str, line_hint: Option<u32>) -> Option<Range<usize>> {
47 if line_hint.is_some() {
48 self.line_hint = line_hint;
49 }
50
51 // Add the chunk to our incomplete line buffer
52 self.incomplete_line.push_str(chunk);
53 self.line_hint = line_hint;
54
55 if let Some((last_pos, _)) = self.incomplete_line.match_indices('\n').next_back() {
56 let complete_part = &self.incomplete_line[..=last_pos];
57
58 // Split into lines and add to query_lines
59 for line in complete_part.lines() {
60 self.query_lines.push(line.to_string());
61 }
62
63 self.incomplete_line.replace_range(..last_pos + 1, "");
64
65 self.matches = self.resolve_location_fuzzy();
66 }
67
68 let best_match = self.select_best_match();
69 best_match.or_else(|| self.matches.first().cloned())
70 }
71
72 /// Finish processing and return the final best match(es).
73 ///
74 /// This processes any remaining incomplete line before returning the final
75 /// match result.
76 pub fn finish(&mut self) -> Vec<Range<usize>> {
77 // Process any remaining incomplete line
78 if !self.incomplete_line.is_empty() {
79 self.query_lines.push(self.incomplete_line.clone());
80 self.incomplete_line.clear();
81 self.matches = self.resolve_location_fuzzy();
82 }
83 self.matches.clone()
84 }
85
86 fn resolve_location_fuzzy(&mut self) -> Vec<Range<usize>> {
87 let new_query_line_count = self.query_lines.len();
88 let old_query_line_count = self.matrix.rows.saturating_sub(1);
89 if new_query_line_count == old_query_line_count {
90 return Vec::new();
91 }
92
93 self.matrix.resize_rows(new_query_line_count + 1);
94
95 // Process only the new query lines
96 for row in old_query_line_count..new_query_line_count {
97 let query_line = self.query_lines[row].trim();
98 let leading_deletion_cost = (row + 1) as u32 * DELETION_COST;
99
100 self.matrix.set(
101 row + 1,
102 0,
103 SearchState::new(leading_deletion_cost, SearchDirection::Up),
104 );
105
106 let mut buffer_lines = self.snapshot.as_rope().chunks().lines();
107 let mut col = 0;
108 while let Some(buffer_line) = buffer_lines.next() {
109 let buffer_line = buffer_line.trim();
110 let up = SearchState::new(
111 self.matrix
112 .get(row, col + 1)
113 .cost
114 .saturating_add(DELETION_COST),
115 SearchDirection::Up,
116 );
117 let left = SearchState::new(
118 self.matrix
119 .get(row + 1, col)
120 .cost
121 .saturating_add(INSERTION_COST),
122 SearchDirection::Left,
123 );
124 let diagonal = SearchState::new(
125 if query_line == buffer_line {
126 self.matrix.get(row, col).cost
127 } else if fuzzy_eq(query_line, buffer_line) {
128 self.matrix.get(row, col).cost + REPLACEMENT_COST
129 } else {
130 self.matrix
131 .get(row, col)
132 .cost
133 .saturating_add(DELETION_COST + INSERTION_COST)
134 },
135 SearchDirection::Diagonal,
136 );
137 self.matrix
138 .set(row + 1, col + 1, up.min(left).min(diagonal));
139 col += 1;
140 }
141 }
142
143 // Find all matches with the best cost
144 let buffer_line_count = self.snapshot.max_point().row as usize + 1;
145 let mut best_cost = u32::MAX;
146 let mut matches_with_best_cost = Vec::new();
147
148 for col in 1..=buffer_line_count {
149 let cost = self.matrix.get(new_query_line_count, col).cost;
150 if cost < best_cost {
151 best_cost = cost;
152 matches_with_best_cost.clear();
153 matches_with_best_cost.push(col as u32);
154 } else if cost == best_cost {
155 matches_with_best_cost.push(col as u32);
156 }
157 }
158
159 // Find ranges for the matches
160 let mut valid_matches = Vec::new();
161 for &buffer_row_end in &matches_with_best_cost {
162 let mut matched_lines = 0;
163 let mut query_row = new_query_line_count;
164 let mut buffer_row_start = buffer_row_end;
165 while query_row > 0 && buffer_row_start > 0 {
166 let current = self.matrix.get(query_row, buffer_row_start as usize);
167 match current.direction {
168 SearchDirection::Diagonal => {
169 query_row -= 1;
170 buffer_row_start -= 1;
171 matched_lines += 1;
172 }
173 SearchDirection::Up => {
174 query_row -= 1;
175 }
176 SearchDirection::Left => {
177 buffer_row_start -= 1;
178 }
179 }
180 }
181
182 let matched_buffer_row_count = buffer_row_end - buffer_row_start;
183 let matched_ratio = matched_lines as f32
184 / (matched_buffer_row_count as f32).max(new_query_line_count as f32);
185 if matched_ratio >= 0.8 {
186 let buffer_start_ix = self
187 .snapshot
188 .point_to_offset(Point::new(buffer_row_start, 0));
189 let buffer_end_ix = self.snapshot.point_to_offset(Point::new(
190 buffer_row_end - 1,
191 self.snapshot.line_len(buffer_row_end - 1),
192 ));
193 valid_matches.push((buffer_row_start, buffer_start_ix..buffer_end_ix));
194 }
195 }
196
197 valid_matches.into_iter().map(|(_, range)| range).collect()
198 }
199
200 /// Return the best match with starting position close enough to line_hint.
201 pub fn select_best_match(&self) -> Option<Range<usize>> {
202 // Allow line hint to be off by that many lines.
203 // Higher values increase probability of applying edits to a wrong place,
204 // Lower values increase edits failures and overall conversation length.
205 const LINE_HINT_TOLERANCE: u32 = 200;
206
207 if self.matches.is_empty() {
208 return None;
209 }
210
211 if self.matches.len() == 1 {
212 return self.matches.first().cloned();
213 }
214
215 let Some(line_hint) = self.line_hint else {
216 // Multiple ambiguous matches
217 return None;
218 };
219
220 let mut best_match = None;
221 let mut best_distance = u32::MAX;
222
223 for range in &self.matches {
224 let start_point = self.snapshot.offset_to_point(range.start);
225 let start_line = start_point.row;
226 let distance = start_line.abs_diff(line_hint);
227
228 if distance <= LINE_HINT_TOLERANCE && distance < best_distance {
229 best_distance = distance;
230 best_match = Some(range.clone());
231 }
232 }
233
234 best_match
235 }
236}
237
238fn fuzzy_eq(left: &str, right: &str) -> bool {
239 const THRESHOLD: f64 = 0.8;
240
241 let min_levenshtein = left.len().abs_diff(right.len());
242 let min_normalized_levenshtein =
243 1. - (min_levenshtein as f64 / cmp::max(left.len(), right.len()) as f64);
244 if min_normalized_levenshtein < THRESHOLD {
245 return false;
246 }
247
248 strsim::normalized_levenshtein(left, right) >= THRESHOLD
249}
250
251#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
252enum SearchDirection {
253 Up,
254 Left,
255 Diagonal,
256}
257
258#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
259struct SearchState {
260 cost: u32,
261 direction: SearchDirection,
262}
263
264impl SearchState {
265 fn new(cost: u32, direction: SearchDirection) -> Self {
266 Self { cost, direction }
267 }
268}
269
270struct SearchMatrix {
271 cols: usize,
272 rows: usize,
273 data: Vec<SearchState>,
274}
275
276impl SearchMatrix {
277 fn new(cols: usize) -> Self {
278 SearchMatrix {
279 cols,
280 rows: 0,
281 data: Vec::new(),
282 }
283 }
284
285 fn resize_rows(&mut self, needed_rows: usize) {
286 debug_assert!(needed_rows > self.rows);
287 self.rows = needed_rows;
288 self.data.resize(
289 self.rows * self.cols,
290 SearchState::new(0, SearchDirection::Diagonal),
291 );
292 }
293
294 fn get(&self, row: usize, col: usize) -> SearchState {
295 debug_assert!(row < self.rows && col < self.cols);
296 self.data[row * self.cols + col]
297 }
298
299 fn set(&mut self, row: usize, col: usize, state: SearchState) {
300 debug_assert!(row < self.rows && col < self.cols);
301 self.data[row * self.cols + col] = state;
302 }
303}
304
305#[cfg(test)]
306mod tests {
307 use super::*;
308 use indoc::indoc;
309 use language::{BufferId, TextBuffer};
310 use rand::prelude::*;
311 use text::ReplicaId;
312 use util::test::{generate_marked_text, marked_text_ranges};
313
314 #[test]
315 fn test_empty_query() {
316 let buffer = TextBuffer::new(
317 ReplicaId::LOCAL,
318 BufferId::new(1).unwrap(),
319 "Hello world\nThis is a test\nFoo bar baz",
320 );
321 let snapshot = buffer.snapshot();
322
323 let mut finder = StreamingFuzzyMatcher::new(snapshot);
324 assert_eq!(push(&mut finder, ""), None);
325 assert_eq!(finish(finder), None);
326 }
327
328 #[test]
329 fn test_streaming_exact_match() {
330 let buffer = TextBuffer::new(
331 ReplicaId::LOCAL,
332 BufferId::new(1).unwrap(),
333 "Hello world\nThis is a test\nFoo bar baz",
334 );
335 let snapshot = buffer.snapshot();
336
337 let mut finder = StreamingFuzzyMatcher::new(snapshot);
338
339 // Push partial query
340 assert_eq!(push(&mut finder, "This"), None);
341
342 // Complete the line
343 assert_eq!(
344 push(&mut finder, " is a test\n"),
345 Some("This is a test".to_string())
346 );
347
348 // Finish should return the same result
349 assert_eq!(finish(finder), Some("This is a test".to_string()));
350 }
351
352 #[test]
353 fn test_streaming_fuzzy_match() {
354 let buffer = TextBuffer::new(
355 ReplicaId::LOCAL,
356 BufferId::new(1).unwrap(),
357 indoc! {"
358 function foo(a, b) {
359 return a + b;
360 }
361
362 function bar(x, y) {
363 return x * y;
364 }
365 "},
366 );
367 let snapshot = buffer.snapshot();
368
369 let mut finder = StreamingFuzzyMatcher::new(snapshot);
370
371 // Push a fuzzy query that should match the first function
372 assert_eq!(
373 push(&mut finder, "function foo(a, c) {\n").as_deref(),
374 Some("function foo(a, b) {")
375 );
376 assert_eq!(
377 push(&mut finder, " return a + c;\n}\n").as_deref(),
378 Some(concat!(
379 "function foo(a, b) {\n",
380 " return a + b;\n",
381 "}"
382 ))
383 );
384 }
385
386 #[test]
387 fn test_incremental_improvement() {
388 let buffer = TextBuffer::new(
389 ReplicaId::LOCAL,
390 BufferId::new(1).unwrap(),
391 "Line 1\nLine 2\nLine 3\nLine 4\nLine 5",
392 );
393 let snapshot = buffer.snapshot();
394
395 let mut finder = StreamingFuzzyMatcher::new(snapshot);
396
397 // No match initially
398 assert_eq!(push(&mut finder, "Lin"), None);
399
400 // Get a match when we complete a line
401 assert_eq!(push(&mut finder, "e 3\n"), Some("Line 3".to_string()));
402
403 // The match might change if we add more specific content
404 assert_eq!(
405 push(&mut finder, "Line 4\n"),
406 Some("Line 3\nLine 4".to_string())
407 );
408 assert_eq!(finish(finder), Some("Line 3\nLine 4".to_string()));
409 }
410
411 #[test]
412 fn test_incomplete_lines_buffering() {
413 let buffer = TextBuffer::new(
414 ReplicaId::LOCAL,
415 BufferId::new(1).unwrap(),
416 indoc! {"
417 The quick brown fox
418 jumps over the lazy dog
419 Pack my box with five dozen liquor jugs
420 "},
421 );
422 let snapshot = buffer.snapshot();
423
424 let mut finder = StreamingFuzzyMatcher::new(snapshot);
425
426 // Push text in small chunks across line boundaries
427 assert_eq!(push(&mut finder, "jumps "), None); // No newline yet
428 assert_eq!(push(&mut finder, "over the"), None); // Still no newline
429 assert_eq!(push(&mut finder, " lazy"), None); // Still incomplete
430
431 // Complete the line
432 assert_eq!(
433 push(&mut finder, " dog\n"),
434 Some("jumps over the lazy dog".to_string())
435 );
436 }
437
438 #[test]
439 fn test_multiline_fuzzy_match() {
440 let buffer = TextBuffer::new(
441 ReplicaId::LOCAL,
442 BufferId::new(1).unwrap(),
443 indoc! {r#"
444 impl Display for User {
445 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
446 write!(f, "User: {} ({})", self.name, self.email)
447 }
448 }
449
450 impl Debug for User {
451 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
452 f.debug_struct("User")
453 .field("name", &self.name)
454 .field("email", &self.email)
455 .finish()
456 }
457 }
458 "#},
459 );
460 let snapshot = buffer.snapshot();
461
462 let mut finder = StreamingFuzzyMatcher::new(snapshot);
463
464 assert_eq!(
465 push(&mut finder, "impl Debug for User {\n"),
466 Some("impl Debug for User {".to_string())
467 );
468 assert_eq!(
469 push(
470 &mut finder,
471 " fn fmt(&self, f: &mut Formatter) -> Result {\n"
472 )
473 .as_deref(),
474 Some(concat!(
475 "impl Debug for User {\n",
476 " fn fmt(&self, f: &mut Formatter) -> fmt::Result {"
477 ))
478 );
479 assert_eq!(
480 push(&mut finder, " f.debug_struct(\"User\")\n").as_deref(),
481 Some(concat!(
482 "impl Debug for User {\n",
483 " fn fmt(&self, f: &mut Formatter) -> fmt::Result {\n",
484 " f.debug_struct(\"User\")"
485 ))
486 );
487 assert_eq!(
488 push(
489 &mut finder,
490 " .field(\"name\", &self.username)\n"
491 )
492 .as_deref(),
493 Some(concat!(
494 "impl Debug for User {\n",
495 " fn fmt(&self, f: &mut Formatter) -> fmt::Result {\n",
496 " f.debug_struct(\"User\")\n",
497 " .field(\"name\", &self.name)"
498 ))
499 );
500 assert_eq!(
501 finish(finder).as_deref(),
502 Some(concat!(
503 "impl Debug for User {\n",
504 " fn fmt(&self, f: &mut Formatter) -> fmt::Result {\n",
505 " f.debug_struct(\"User\")\n",
506 " .field(\"name\", &self.name)"
507 ))
508 );
509 }
510
511 #[gpui::test(iterations = 100)]
512 fn test_resolve_location_single_line(mut rng: StdRng) {
513 assert_location_resolution(
514 concat!(
515 " Lorem\n",
516 "« ipsum»\n",
517 " dolor sit amet\n",
518 " consecteur",
519 ),
520 "ipsum",
521 &mut rng,
522 );
523 }
524
525 #[gpui::test(iterations = 100)]
526 fn test_resolve_location_multiline(mut rng: StdRng) {
527 assert_location_resolution(
528 concat!(
529 " Lorem\n",
530 "« ipsum\n",
531 " dolor sit amet»\n",
532 " consecteur",
533 ),
534 "ipsum\ndolor sit amet",
535 &mut rng,
536 );
537 }
538
539 #[gpui::test(iterations = 100)]
540 fn test_resolve_location_function_with_typo(mut rng: StdRng) {
541 assert_location_resolution(
542 indoc! {"
543 «fn foo1(a: usize) -> usize {
544 40
545 }»
546
547 fn foo2(b: usize) -> usize {
548 42
549 }
550 "},
551 "fn foo1(a: usize) -> u32 {\n40\n}",
552 &mut rng,
553 );
554 }
555
556 #[gpui::test(iterations = 100)]
557 fn test_resolve_location_class_methods(mut rng: StdRng) {
558 assert_location_resolution(
559 indoc! {"
560 class Something {
561 one() { return 1; }
562 « two() { return 2222; }
563 three() { return 333; }
564 four() { return 4444; }
565 five() { return 5555; }
566 six() { return 6666; }»
567 seven() { return 7; }
568 eight() { return 8; }
569 }
570 "},
571 indoc! {"
572 two() { return 2222; }
573 four() { return 4444; }
574 five() { return 5555; }
575 six() { return 6666; }
576 "},
577 &mut rng,
578 );
579 }
580
581 #[gpui::test(iterations = 100)]
582 fn test_resolve_location_imports_no_match(mut rng: StdRng) {
583 assert_location_resolution(
584 indoc! {"
585 use std::ops::Range;
586 use std::sync::Mutex;
587 use std::{
588 collections::HashMap,
589 env,
590 ffi::{OsStr, OsString},
591 fs,
592 io::{BufRead, BufReader},
593 mem,
594 path::{Path, PathBuf},
595 process::Command,
596 sync::LazyLock,
597 time::SystemTime,
598 };
599 "},
600 indoc! {"
601 use std::collections::{HashMap, HashSet};
602 use std::ffi::{OsStr, OsString};
603 use std::fmt::Write as _;
604 use std::fs;
605 use std::io::{BufReader, Read, Write};
606 use std::mem;
607 use std::path::{Path, PathBuf};
608 use std::process::Command;
609 use std::sync::Arc;
610 "},
611 &mut rng,
612 );
613 }
614
615 #[gpui::test(iterations = 100)]
616 fn test_resolve_location_nested_closure(mut rng: StdRng) {
617 assert_location_resolution(
618 indoc! {"
619 impl Foo {
620 fn new() -> Self {
621 Self {
622 subscriptions: vec![
623 cx.observe_window_activation(window, |editor, window, cx| {
624 let active = window.is_window_active();
625 editor.blink_manager.update(cx, |blink_manager, cx| {
626 if active {
627 blink_manager.enable(cx);
628 } else {
629 blink_manager.disable(cx);
630 }
631 });
632 }),
633 ];
634 }
635 }
636 }
637 "},
638 concat!(
639 " editor.blink_manager.update(cx, |blink_manager, cx| {\n",
640 " blink_manager.enable(cx);\n",
641 " });",
642 ),
643 &mut rng,
644 );
645 }
646
647 #[gpui::test(iterations = 100)]
648 fn test_resolve_location_tool_invocation(mut rng: StdRng) {
649 assert_location_resolution(
650 indoc! {r#"
651 let tool = cx
652 .update(|cx| working_set.tool(&tool_name, cx))
653 .map_err(|err| {
654 anyhow!("Failed to look up tool '{}': {}", tool_name, err)
655 })?;
656
657 let Some(tool) = tool else {
658 return Err(anyhow!("Tool '{}' not found", tool_name));
659 };
660
661 let project = project.clone();
662 let action_log = action_log.clone();
663 let messages = messages.clone();
664 let tool_result = cx
665 .update(|cx| tool.run(invocation.input, &messages, project, action_log, cx))
666 .map_err(|err| anyhow!("Failed to start tool '{}': {}", tool_name, err))?;
667
668 tasks.push(tool_result.output);
669 "#},
670 concat!(
671 "let tool_result = cx\n",
672 " .update(|cx| tool.run(invocation.input, &messages, project, action_log, cx))\n",
673 " .output;",
674 ),
675 &mut rng,
676 );
677 }
678
679 #[gpui::test]
680 fn test_line_hint_selection() {
681 let text = indoc! {r#"
682 fn first_function() {
683 return 42;
684 }
685
686 fn second_function() {
687 return 42;
688 }
689
690 fn third_function() {
691 return 42;
692 }
693 "#};
694
695 let buffer = TextBuffer::new(
696 ReplicaId::LOCAL,
697 BufferId::new(1).unwrap(),
698 text.to_string(),
699 );
700 let snapshot = buffer.snapshot();
701 let mut matcher = StreamingFuzzyMatcher::new(snapshot.clone());
702
703 // Given a query that matches all three functions
704 let query = "return 42;\n";
705
706 // Test with line hint pointing to second function (around line 5)
707 let best_match = matcher.push(query, Some(5)).expect("Failed to match query");
708
709 let matched_text = snapshot
710 .text_for_range(best_match.clone())
711 .collect::<String>();
712 assert!(matched_text.contains("return 42;"));
713 assert_eq!(
714 best_match,
715 63..77,
716 "Expected to match `second_function` based on the line hint"
717 );
718
719 let mut matcher = StreamingFuzzyMatcher::new(snapshot);
720 matcher.push(query, None);
721 matcher.finish();
722 let best_match = matcher.select_best_match();
723 assert!(
724 best_match.is_none(),
725 "Best match should be None when query cannot be uniquely resolved"
726 );
727 }
728
729 #[track_caller]
730 fn assert_location_resolution(text_with_expected_range: &str, query: &str, rng: &mut StdRng) {
731 let (text, expected_ranges) = marked_text_ranges(text_with_expected_range, false);
732 let buffer = TextBuffer::new(ReplicaId::LOCAL, BufferId::new(1).unwrap(), text.clone());
733 let snapshot = buffer.snapshot();
734
735 let mut matcher = StreamingFuzzyMatcher::new(snapshot);
736
737 // Split query into random chunks
738 let chunks = to_random_chunks(rng, query);
739
740 // Push chunks incrementally
741 for chunk in &chunks {
742 matcher.push(chunk, None);
743 }
744
745 let actual_ranges = matcher.finish();
746
747 // If no expected ranges, we expect no match
748 if expected_ranges.is_empty() {
749 assert!(
750 actual_ranges.is_empty(),
751 "Expected no match for query: {:?}, but found: {:?}",
752 query,
753 actual_ranges
754 );
755 } else {
756 let text_with_actual_range = generate_marked_text(&text, &actual_ranges, false);
757 pretty_assertions::assert_eq!(
758 text_with_actual_range,
759 text_with_expected_range,
760 indoc! {"
761 Query: {:?}
762 Chunks: {:?}
763 Expected marked text: {}
764 Actual marked text: {}
765 Expected ranges: {:?}
766 Actual ranges: {:?}"
767 },
768 query,
769 chunks,
770 text_with_expected_range,
771 text_with_actual_range,
772 expected_ranges,
773 actual_ranges
774 );
775 }
776 }
777
778 fn to_random_chunks(rng: &mut StdRng, input: &str) -> Vec<String> {
779 let chunk_count = rng.random_range(1..=cmp::min(input.len(), 50));
780 let mut chunk_indices = (0..input.len()).choose_multiple(rng, chunk_count);
781 chunk_indices.sort();
782 chunk_indices.push(input.len());
783
784 let mut chunks = Vec::new();
785 let mut last_ix = 0;
786 for chunk_ix in chunk_indices {
787 chunks.push(input[last_ix..chunk_ix].to_string());
788 last_ix = chunk_ix;
789 }
790 chunks
791 }
792
793 fn push(finder: &mut StreamingFuzzyMatcher, chunk: &str) -> Option<String> {
794 finder
795 .push(chunk, None)
796 .map(|range| finder.snapshot.text_for_range(range).collect::<String>())
797 }
798
799 fn finish(mut finder: StreamingFuzzyMatcher) -> Option<String> {
800 let snapshot = finder.snapshot.clone();
801 let matches = finder.finish();
802 matches
803 .first()
804 .map(|range| snapshot.text_for_range(range.clone()).collect::<String>())
805 }
806}