1use editor::{scroll::Autoscroll, styled_runs_for_code_label, Bias, Editor};
2use fuzzy::{StringMatch, StringMatchCandidate};
3use gpui::{
4 rems, AppContext, DismissEvent, FontWeight, Model, ParentElement, StyledText, Task, View,
5 ViewContext, WeakView, WindowContext,
6};
7use ordered_float::OrderedFloat;
8use picker::{Picker, PickerDelegate};
9use project::{Project, Symbol};
10use std::{borrow::Cow, cmp::Reverse, sync::Arc};
11use theme::ActiveTheme;
12use util::ResultExt;
13use workspace::{
14 ui::{v_flex, Color, Label, LabelCommon, LabelLike, ListItem, ListItemSpacing, Selectable},
15 Workspace,
16};
17
18pub fn init(cx: &mut AppContext) {
19 cx.observe_new_views(
20 |workspace: &mut Workspace, _: &mut ViewContext<Workspace>| {
21 workspace.register_action(|workspace, _: &workspace::ToggleProjectSymbols, cx| {
22 let project = workspace.project().clone();
23 let handle = cx.view().downgrade();
24 workspace.toggle_modal(cx, move |cx| {
25 let delegate = ProjectSymbolsDelegate::new(handle, project);
26 Picker::uniform_list(delegate, cx).width(rems(34.))
27 })
28 });
29 },
30 )
31 .detach();
32}
33
34pub type ProjectSymbols = View<Picker<ProjectSymbolsDelegate>>;
35
36pub struct ProjectSymbolsDelegate {
37 workspace: WeakView<Workspace>,
38 project: Model<Project>,
39 selected_match_index: usize,
40 symbols: Vec<Symbol>,
41 visible_match_candidates: Vec<StringMatchCandidate>,
42 external_match_candidates: Vec<StringMatchCandidate>,
43 show_worktree_root_name: bool,
44 matches: Vec<StringMatch>,
45}
46
47impl ProjectSymbolsDelegate {
48 fn new(workspace: WeakView<Workspace>, project: Model<Project>) -> Self {
49 Self {
50 workspace,
51 project,
52 selected_match_index: 0,
53 symbols: Default::default(),
54 visible_match_candidates: Default::default(),
55 external_match_candidates: Default::default(),
56 matches: Default::default(),
57 show_worktree_root_name: false,
58 }
59 }
60
61 fn filter(&mut self, query: &str, cx: &mut ViewContext<Picker<Self>>) {
62 const MAX_MATCHES: usize = 100;
63 let mut visible_matches = cx.background_executor().block(fuzzy::match_strings(
64 &self.visible_match_candidates,
65 query,
66 false,
67 MAX_MATCHES,
68 &Default::default(),
69 cx.background_executor().clone(),
70 ));
71 let mut external_matches = cx.background_executor().block(fuzzy::match_strings(
72 &self.external_match_candidates,
73 query,
74 false,
75 MAX_MATCHES - visible_matches.len().min(MAX_MATCHES),
76 &Default::default(),
77 cx.background_executor().clone(),
78 ));
79 let sort_key_for_match = |mat: &StringMatch| {
80 let symbol = &self.symbols[mat.candidate_id];
81 (
82 Reverse(OrderedFloat(mat.score)),
83 &symbol.label.text[symbol.label.filter_range.clone()],
84 )
85 };
86
87 visible_matches.sort_unstable_by_key(sort_key_for_match);
88 external_matches.sort_unstable_by_key(sort_key_for_match);
89 let mut matches = visible_matches;
90 matches.append(&mut external_matches);
91
92 for mat in &mut matches {
93 let symbol = &self.symbols[mat.candidate_id];
94 let filter_start = symbol.label.filter_range.start;
95 for position in &mut mat.positions {
96 *position += filter_start;
97 }
98 }
99
100 self.matches = matches;
101 self.set_selected_index(0, cx);
102 }
103}
104
105impl PickerDelegate for ProjectSymbolsDelegate {
106 type ListItem = ListItem;
107 fn placeholder_text(&self, _cx: &mut WindowContext) -> Arc<str> {
108 "Search project symbols...".into()
109 }
110
111 fn confirm(&mut self, secondary: bool, cx: &mut ViewContext<Picker<Self>>) {
112 if let Some(symbol) = self
113 .matches
114 .get(self.selected_match_index)
115 .map(|mat| self.symbols[mat.candidate_id].clone())
116 {
117 let buffer = self.project.update(cx, |project, cx| {
118 project.open_buffer_for_symbol(&symbol, cx)
119 });
120 let symbol = symbol.clone();
121 let workspace = self.workspace.clone();
122 cx.spawn(|_, mut cx| async move {
123 let buffer = buffer.await?;
124 workspace.update(&mut cx, |workspace, cx| {
125 let position = buffer
126 .read(cx)
127 .clip_point_utf16(symbol.range.start, Bias::Left);
128 let pane = if secondary {
129 workspace.adjacent_pane(cx)
130 } else {
131 workspace.active_pane().clone()
132 };
133
134 let editor = workspace.open_project_item::<Editor>(pane, buffer, cx);
135
136 editor.update(cx, |editor, cx| {
137 editor.change_selections(Some(Autoscroll::center()), cx, |s| {
138 s.select_ranges([position..position])
139 });
140 });
141 })?;
142 Ok::<_, anyhow::Error>(())
143 })
144 .detach_and_log_err(cx);
145 cx.emit(DismissEvent);
146 }
147 }
148
149 fn dismissed(&mut self, _cx: &mut ViewContext<Picker<Self>>) {}
150
151 fn match_count(&self) -> usize {
152 self.matches.len()
153 }
154
155 fn selected_index(&self) -> usize {
156 self.selected_match_index
157 }
158
159 fn set_selected_index(&mut self, ix: usize, _cx: &mut ViewContext<Picker<Self>>) {
160 self.selected_match_index = ix;
161 }
162
163 fn update_matches(&mut self, query: String, cx: &mut ViewContext<Picker<Self>>) -> Task<()> {
164 self.filter(&query, cx);
165 self.show_worktree_root_name = self.project.read(cx).visible_worktrees(cx).count() > 1;
166 let symbols = self
167 .project
168 .update(cx, |project, cx| project.symbols(&query, cx));
169 cx.spawn(|this, mut cx| async move {
170 let symbols = symbols.await.log_err();
171 if let Some(symbols) = symbols {
172 this.update(&mut cx, |this, cx| {
173 let delegate = &mut this.delegate;
174 let project = delegate.project.read(cx);
175 let (visible_match_candidates, external_match_candidates) = symbols
176 .iter()
177 .enumerate()
178 .map(|(id, symbol)| {
179 StringMatchCandidate::new(
180 id,
181 symbol.label.text[symbol.label.filter_range.clone()].to_string(),
182 )
183 })
184 .partition(|candidate| {
185 project
186 .entry_for_path(&symbols[candidate.id].path, cx)
187 .map_or(false, |e| !e.is_ignored)
188 });
189
190 delegate.visible_match_candidates = visible_match_candidates;
191 delegate.external_match_candidates = external_match_candidates;
192 delegate.symbols = symbols;
193 delegate.filter(&query, cx);
194 })
195 .log_err();
196 }
197 })
198 }
199
200 fn render_match(
201 &self,
202 ix: usize,
203 selected: bool,
204 cx: &mut ViewContext<Picker<Self>>,
205 ) -> Option<Self::ListItem> {
206 let string_match = &self.matches[ix];
207 let symbol = &self.symbols[string_match.candidate_id];
208 let syntax_runs = styled_runs_for_code_label(&symbol.label, cx.theme().syntax());
209
210 let mut path = symbol.path.path.to_string_lossy();
211 if self.show_worktree_root_name {
212 let project = self.project.read(cx);
213 if let Some(worktree) = project.worktree_for_id(symbol.path.worktree_id, cx) {
214 path = Cow::Owned(format!(
215 "{}{}{}",
216 worktree.read(cx).root_name(),
217 std::path::MAIN_SEPARATOR,
218 path.as_ref()
219 ));
220 }
221 }
222 let label = symbol.label.text.clone();
223 let path = path.to_string().clone();
224
225 let highlights = gpui::combine_highlights(
226 string_match
227 .positions
228 .iter()
229 .map(|pos| (*pos..pos + 1, FontWeight::BOLD.into())),
230 syntax_runs.map(|(range, mut highlight)| {
231 // Ignore font weight for syntax highlighting, as we'll use it
232 // for fuzzy matches.
233 highlight.font_weight = None;
234 (range, highlight)
235 }),
236 );
237
238 Some(
239 ListItem::new(ix)
240 .inset(true)
241 .spacing(ListItemSpacing::Sparse)
242 .selected(selected)
243 .child(
244 v_flex()
245 .child(
246 LabelLike::new().child(
247 StyledText::new(label)
248 .with_highlights(&cx.text_style().clone(), highlights),
249 ),
250 )
251 .child(Label::new(path).color(Color::Muted)),
252 ),
253 )
254 }
255}
256
257#[cfg(test)]
258mod tests {
259 use super::*;
260 use futures::StreamExt;
261 use gpui::{SemanticVersion, TestAppContext, VisualContext};
262 use language::{FakeLspAdapter, Language, LanguageConfig, LanguageMatcher};
263 use project::FakeFs;
264 use serde_json::json;
265 use settings::SettingsStore;
266 use std::{path::Path, sync::Arc};
267
268 #[gpui::test]
269 async fn test_project_symbols(cx: &mut TestAppContext) {
270 init_test(cx);
271
272 let fs = FakeFs::new(cx.executor());
273 fs.insert_tree("/dir", json!({ "test.rs": "" })).await;
274
275 let project = Project::test(fs.clone(), ["/dir".as_ref()], cx).await;
276
277 let language_registry = project.read_with(cx, |project, _| project.languages().clone());
278 language_registry.add(Arc::new(Language::new(
279 LanguageConfig {
280 name: "Rust".into(),
281 matcher: LanguageMatcher {
282 path_suffixes: vec!["rs".to_string()],
283 ..Default::default()
284 },
285 ..Default::default()
286 },
287 None,
288 )));
289 let mut fake_servers =
290 language_registry.register_fake_lsp_adapter("Rust", FakeLspAdapter::default());
291
292 let _buffer = project
293 .update(cx, |project, cx| {
294 project.open_local_buffer("/dir/test.rs", cx)
295 })
296 .await
297 .unwrap();
298
299 // Set up fake language server to return fuzzy matches against
300 // a fixed set of symbol names.
301 let fake_symbols = [
302 symbol("one", "/external"),
303 symbol("ton", "/dir/test.rs"),
304 symbol("uno", "/dir/test.rs"),
305 ];
306 let fake_server = fake_servers.next().await.unwrap();
307 fake_server.handle_request::<lsp::WorkspaceSymbolRequest, _, _>(
308 move |params: lsp::WorkspaceSymbolParams, cx| {
309 let executor = cx.background_executor().clone();
310 let fake_symbols = fake_symbols.clone();
311 async move {
312 let candidates = fake_symbols
313 .iter()
314 .enumerate()
315 .map(|(id, symbol)| StringMatchCandidate::new(id, symbol.name.clone()))
316 .collect::<Vec<_>>();
317 let matches = if params.query.is_empty() {
318 Vec::new()
319 } else {
320 fuzzy::match_strings(
321 &candidates,
322 ¶ms.query,
323 true,
324 100,
325 &Default::default(),
326 executor.clone(),
327 )
328 .await
329 };
330
331 Ok(Some(lsp::WorkspaceSymbolResponse::Flat(
332 matches
333 .into_iter()
334 .map(|mat| fake_symbols[mat.candidate_id].clone())
335 .collect(),
336 )))
337 }
338 },
339 );
340
341 let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project.clone(), cx));
342
343 // Create the project symbols view.
344 let symbols = cx.new_view(|cx| {
345 Picker::uniform_list(
346 ProjectSymbolsDelegate::new(workspace.downgrade(), project.clone()),
347 cx,
348 )
349 });
350
351 // Spawn multiples updates before the first update completes,
352 // such that in the end, there are no matches. Testing for regression:
353 // https://github.com/zed-industries/zed/issues/861
354 symbols.update(cx, |p, cx| {
355 p.update_matches("o".to_string(), cx);
356 p.update_matches("on".to_string(), cx);
357 p.update_matches("onex".to_string(), cx);
358 });
359
360 cx.run_until_parked();
361 symbols.update(cx, |symbols, _| {
362 assert_eq!(symbols.delegate.matches.len(), 0);
363 });
364
365 // Spawn more updates such that in the end, there are matches.
366 symbols.update(cx, |p, cx| {
367 p.update_matches("one".to_string(), cx);
368 p.update_matches("on".to_string(), cx);
369 });
370
371 cx.run_until_parked();
372 symbols.update(cx, |symbols, _| {
373 let delegate = &symbols.delegate;
374 assert_eq!(delegate.matches.len(), 2);
375 assert_eq!(delegate.matches[0].string, "ton");
376 assert_eq!(delegate.matches[1].string, "one");
377 });
378
379 // Spawn more updates such that in the end, there are again no matches.
380 symbols.update(cx, |p, cx| {
381 p.update_matches("o".to_string(), cx);
382 p.update_matches("".to_string(), cx);
383 });
384
385 cx.run_until_parked();
386 symbols.update(cx, |symbols, _| {
387 assert_eq!(symbols.delegate.matches.len(), 0);
388 });
389 }
390
391 fn init_test(cx: &mut TestAppContext) {
392 cx.update(|cx| {
393 let store = SettingsStore::test(cx);
394 cx.set_global(store);
395 theme::init(theme::LoadThemes::JustBase, cx);
396 release_channel::init(SemanticVersion::default(), cx);
397 language::init(cx);
398 Project::init_settings(cx);
399 workspace::init_settings(cx);
400 editor::init(cx);
401 });
402 }
403
404 fn symbol(name: &str, path: impl AsRef<Path>) -> lsp::SymbolInformation {
405 #[allow(deprecated)]
406 lsp::SymbolInformation {
407 name: name.to_string(),
408 kind: lsp::SymbolKind::FUNCTION,
409 tags: None,
410 deprecated: None,
411 container_name: None,
412 location: lsp::Location::new(
413 lsp::Url::from_file_path(path.as_ref()).unwrap(),
414 lsp::Range::new(lsp::Position::new(0, 0), lsp::Position::new(0, 0)),
415 ),
416 }
417 }
418}