1use crate::{BufferSnapshot, Point, ToPoint};
2use fuzzy::{StringMatch, StringMatchCandidate};
3use gpui::{BackgroundExecutor, HighlightStyle};
4use std::ops::Range;
5
6/// An outline of all the symbols contained in a buffer.
7#[derive(Debug)]
8pub struct Outline<T> {
9 pub items: Vec<OutlineItem<T>>,
10 candidates: Vec<StringMatchCandidate>,
11 pub path_candidates: Vec<StringMatchCandidate>,
12 path_candidate_prefixes: Vec<usize>,
13}
14
15#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
16pub struct OutlineItem<T> {
17 pub depth: usize,
18 pub range: Range<T>,
19 pub text: String,
20 pub highlight_ranges: Vec<(Range<usize>, HighlightStyle)>,
21 pub name_ranges: Vec<Range<usize>>,
22 pub body_range: Option<Range<T>>,
23 pub annotation_range: Option<Range<T>>,
24}
25
26#[derive(Clone, Debug, Eq, PartialEq)]
27pub struct SymbolPath(pub String);
28
29impl<T: ToPoint> OutlineItem<T> {
30 /// Converts to an equivalent outline item, but with parameterized over Points.
31 pub fn to_point(&self, buffer: &BufferSnapshot) -> OutlineItem<Point> {
32 OutlineItem {
33 depth: self.depth,
34 range: self.range.start.to_point(buffer)..self.range.end.to_point(buffer),
35 text: self.text.clone(),
36 highlight_ranges: self.highlight_ranges.clone(),
37 name_ranges: self.name_ranges.clone(),
38 body_range: self
39 .body_range
40 .as_ref()
41 .map(|r| r.start.to_point(buffer)..r.end.to_point(buffer)),
42 annotation_range: self
43 .annotation_range
44 .as_ref()
45 .map(|r| r.start.to_point(buffer)..r.end.to_point(buffer)),
46 }
47 }
48}
49
50impl<T> Outline<T> {
51 pub fn new(items: Vec<OutlineItem<T>>) -> Self {
52 let mut candidates = Vec::new();
53 let mut path_candidates = Vec::new();
54 let mut path_candidate_prefixes = Vec::new();
55 let mut path_text = String::new();
56 let mut path_stack = Vec::new();
57
58 for (id, item) in items.iter().enumerate() {
59 if item.depth < path_stack.len() {
60 path_stack.truncate(item.depth);
61 path_text.truncate(path_stack.last().copied().unwrap_or(0));
62 }
63 if !path_text.is_empty() {
64 path_text.push(' ');
65 }
66 path_candidate_prefixes.push(path_text.len());
67 path_text.push_str(&item.text);
68 path_stack.push(path_text.len());
69
70 let candidate_text = item
71 .name_ranges
72 .iter()
73 .map(|range| &item.text[range.start..range.end])
74 .collect::<String>();
75
76 path_candidates.push(StringMatchCandidate::new(id, &path_text));
77 candidates.push(StringMatchCandidate::new(id, &candidate_text));
78 }
79
80 Self {
81 candidates,
82 path_candidates,
83 path_candidate_prefixes,
84 items,
85 }
86 }
87
88 /// Find the most similar symbol to the provided query using normalized Levenshtein distance.
89 pub fn find_most_similar(&self, query: &str) -> Option<(SymbolPath, &OutlineItem<T>)> {
90 const SIMILARITY_THRESHOLD: f64 = 0.6;
91
92 let (position, similarity) = self
93 .path_candidates
94 .iter()
95 .enumerate()
96 .map(|(index, candidate)| {
97 let similarity = strsim::normalized_levenshtein(&candidate.string, query);
98 (index, similarity)
99 })
100 .max_by(|(_, a), (_, b)| a.partial_cmp(b).unwrap())?;
101
102 if similarity >= SIMILARITY_THRESHOLD {
103 self.path_candidates
104 .get(position)
105 .map(|candidate| SymbolPath(candidate.string.clone()))
106 .zip(self.items.get(position))
107 } else {
108 None
109 }
110 }
111
112 /// Find all outline symbols according to a longest subsequence match with the query, ordered descending by match score.
113 pub async fn search(&self, query: &str, executor: BackgroundExecutor) -> Vec<StringMatch> {
114 let query = query.trim_start();
115 let is_path_query = query.contains(' ');
116 let smart_case = query.chars().any(|c| c.is_uppercase());
117 let mut matches = fuzzy::match_strings(
118 if is_path_query {
119 &self.path_candidates
120 } else {
121 &self.candidates
122 },
123 query,
124 smart_case,
125 100,
126 &Default::default(),
127 executor.clone(),
128 )
129 .await;
130 matches.sort_unstable_by_key(|m| m.candidate_id);
131
132 let mut tree_matches = Vec::new();
133
134 let mut prev_item_ix = 0;
135 for mut string_match in matches {
136 let outline_match = &self.items[string_match.candidate_id];
137 string_match.string.clone_from(&outline_match.text);
138
139 if is_path_query {
140 let prefix_len = self.path_candidate_prefixes[string_match.candidate_id];
141 string_match
142 .positions
143 .retain(|position| *position >= prefix_len);
144 for position in &mut string_match.positions {
145 *position -= prefix_len;
146 }
147 } else {
148 let mut name_ranges = outline_match.name_ranges.iter();
149 let Some(mut name_range) = name_ranges.next() else {
150 continue;
151 };
152 let mut preceding_ranges_len = 0;
153 for position in &mut string_match.positions {
154 while *position >= preceding_ranges_len + name_range.len() {
155 preceding_ranges_len += name_range.len();
156 name_range = name_ranges.next().unwrap();
157 }
158 *position = name_range.start + (*position - preceding_ranges_len);
159 }
160 }
161
162 let insertion_ix = tree_matches.len();
163 let mut cur_depth = outline_match.depth;
164 for (ix, item) in self.items[prev_item_ix..string_match.candidate_id]
165 .iter()
166 .enumerate()
167 .rev()
168 {
169 if cur_depth == 0 {
170 break;
171 }
172
173 let candidate_index = ix + prev_item_ix;
174 if item.depth == cur_depth - 1 {
175 tree_matches.insert(
176 insertion_ix,
177 StringMatch {
178 candidate_id: candidate_index,
179 score: Default::default(),
180 positions: Default::default(),
181 string: Default::default(),
182 },
183 );
184 cur_depth -= 1;
185 }
186 }
187
188 prev_item_ix = string_match.candidate_id + 1;
189 tree_matches.push(string_match);
190 }
191
192 tree_matches
193 }
194}
195
196#[cfg(test)]
197mod tests {
198 use super::*;
199 use gpui::TestAppContext;
200
201 #[gpui::test]
202 async fn test_entries_with_no_names(cx: &mut TestAppContext) {
203 let outline = Outline::new(vec![
204 OutlineItem {
205 depth: 0,
206 range: Point::new(0, 0)..Point::new(5, 0),
207 text: "class Foo".to_string(),
208 highlight_ranges: vec![],
209 name_ranges: vec![6..9],
210 body_range: None,
211 annotation_range: None,
212 },
213 OutlineItem {
214 depth: 0,
215 range: Point::new(2, 0)..Point::new(2, 7),
216 text: "private".to_string(),
217 highlight_ranges: vec![],
218 name_ranges: vec![],
219 body_range: None,
220 annotation_range: None,
221 },
222 ]);
223 assert_eq!(
224 outline
225 .search(" ", cx.executor())
226 .await
227 .into_iter()
228 .map(|mat| mat.string)
229 .collect::<Vec<String>>(),
230 vec!["class Foo".to_string()]
231 );
232 }
233
234 #[test]
235 fn test_find_most_similar_with_low_similarity() {
236 let outline = Outline::new(vec![
237 OutlineItem {
238 depth: 0,
239 range: Point::new(0, 0)..Point::new(5, 0),
240 text: "fn process".to_string(),
241 highlight_ranges: vec![],
242 name_ranges: vec![3..10],
243 body_range: None,
244 annotation_range: None,
245 },
246 OutlineItem {
247 depth: 0,
248 range: Point::new(7, 0)..Point::new(12, 0),
249 text: "struct DataProcessor".to_string(),
250 highlight_ranges: vec![],
251 name_ranges: vec![7..20],
252 body_range: None,
253 annotation_range: None,
254 },
255 ]);
256 assert_eq!(
257 outline.find_most_similar("pub fn process"),
258 Some((SymbolPath("fn process".into()), &outline.items[0]))
259 );
260 assert_eq!(
261 outline.find_most_similar("async fn process"),
262 Some((SymbolPath("fn process".into()), &outline.items[0])),
263 );
264 assert_eq!(
265 outline.find_most_similar("struct Processor"),
266 Some((SymbolPath("struct DataProcessor".into()), &outline.items[1]))
267 );
268 assert_eq!(outline.find_most_similar("struct User"), None);
269 assert_eq!(outline.find_most_similar("struct"), None);
270 }
271}