1use editor::{Bias, Editor, SelectionEffects, scroll::Autoscroll, styled_runs_for_code_label};
2use fuzzy::{StringMatch, StringMatchCandidate};
3use gpui::{
4 App, Context, DismissEvent, Entity, HighlightStyle, ParentElement, StyledText, Task, TextStyle,
5 WeakEntity, Window, relative, rems,
6};
7use ordered_float::OrderedFloat;
8use picker::{Picker, PickerDelegate};
9use project::{Project, Symbol, lsp_store::SymbolLocation};
10use settings::Settings;
11use std::{cmp::Reverse, sync::Arc};
12use theme::ActiveTheme;
13use theme_settings::ThemeSettings;
14use util::ResultExt;
15use workspace::{
16 Workspace,
17 ui::{LabelLike, ListItem, ListItemSpacing, prelude::*},
18};
19
20pub fn init(cx: &mut App) {
21 cx.observe_new(
22 |workspace: &mut Workspace, _window, _: &mut Context<Workspace>| {
23 workspace.register_action(
24 |workspace, _: &workspace::ToggleProjectSymbols, window, cx| {
25 let project = workspace.project().clone();
26 let handle = cx.entity().downgrade();
27 workspace.toggle_modal(window, cx, move |window, cx| {
28 let delegate = ProjectSymbolsDelegate::new(handle, project);
29 Picker::uniform_list(delegate, window, cx).width(rems(34.))
30 })
31 },
32 );
33 },
34 )
35 .detach();
36}
37
38pub type ProjectSymbols = Entity<Picker<ProjectSymbolsDelegate>>;
39
40pub struct ProjectSymbolsDelegate {
41 workspace: WeakEntity<Workspace>,
42 project: Entity<Project>,
43 selected_match_index: usize,
44 symbols: Vec<Symbol>,
45 visible_match_candidates: Vec<StringMatchCandidate>,
46 external_match_candidates: Vec<StringMatchCandidate>,
47 show_worktree_root_name: bool,
48 matches: Vec<StringMatch>,
49}
50
51impl ProjectSymbolsDelegate {
52 fn new(workspace: WeakEntity<Workspace>, project: Entity<Project>) -> Self {
53 Self {
54 workspace,
55 project,
56 selected_match_index: 0,
57 symbols: Default::default(),
58 visible_match_candidates: Default::default(),
59 external_match_candidates: Default::default(),
60 matches: Default::default(),
61 show_worktree_root_name: false,
62 }
63 }
64
65 // Note if you make changes to this, also change `agent_ui::completion_provider::search_symbols`
66 fn filter(&mut self, query: &str, window: &mut Window, cx: &mut Context<Picker<Self>>) {
67 const MAX_MATCHES: usize = 100;
68 let mut visible_matches = cx.foreground_executor().block_on(fuzzy::match_strings(
69 &self.visible_match_candidates,
70 query,
71 false,
72 true,
73 MAX_MATCHES,
74 &Default::default(),
75 cx.background_executor().clone(),
76 ));
77 let mut external_matches = cx.foreground_executor().block_on(fuzzy::match_strings(
78 &self.external_match_candidates,
79 query,
80 false,
81 true,
82 MAX_MATCHES - visible_matches.len().min(MAX_MATCHES),
83 &Default::default(),
84 cx.background_executor().clone(),
85 ));
86 let sort_key_for_match = |mat: &StringMatch| {
87 let symbol = &self.symbols[mat.candidate_id];
88 (Reverse(OrderedFloat(mat.score)), symbol.label.filter_text())
89 };
90
91 visible_matches.sort_unstable_by_key(sort_key_for_match);
92 external_matches.sort_unstable_by_key(sort_key_for_match);
93 let mut matches = visible_matches;
94 matches.append(&mut external_matches);
95
96 for mat in &mut matches {
97 let symbol = &self.symbols[mat.candidate_id];
98 let filter_start = symbol.label.filter_range.start;
99 for position in &mut mat.positions {
100 *position += filter_start;
101 }
102 }
103
104 self.matches = matches;
105 self.set_selected_index(0, window, cx);
106 }
107}
108
109impl PickerDelegate for ProjectSymbolsDelegate {
110 type ListItem = ListItem;
111 fn placeholder_text(&self, _window: &mut Window, _cx: &mut App) -> Arc<str> {
112 "Search project symbols...".into()
113 }
114
115 fn confirm(&mut self, secondary: bool, window: &mut Window, cx: &mut Context<Picker<Self>>) {
116 if let Some(symbol) = self
117 .matches
118 .get(self.selected_match_index)
119 .map(|mat| self.symbols[mat.candidate_id].clone())
120 {
121 let buffer = self.project.update(cx, |project, cx| {
122 project.open_buffer_for_symbol(&symbol, cx)
123 });
124 let symbol = symbol.clone();
125 let workspace = self.workspace.clone();
126 cx.spawn_in(window, async move |_, cx| {
127 let buffer = buffer.await?;
128 workspace.update_in(cx, |workspace, window, cx| {
129 let position = buffer
130 .read(cx)
131 .clip_point_utf16(symbol.range.start, Bias::Left);
132 let pane = if secondary {
133 workspace.adjacent_pane(window, cx)
134 } else {
135 workspace.active_pane().clone()
136 };
137
138 let editor = workspace.open_project_item::<Editor>(
139 pane, buffer, true, true, true, true, window, cx,
140 );
141
142 editor.update(cx, |editor, cx| {
143 editor.change_selections(
144 SelectionEffects::scroll(Autoscroll::center()),
145 window,
146 cx,
147 |s| s.select_ranges([position..position]),
148 );
149 });
150 })?;
151 anyhow::Ok(())
152 })
153 .detach_and_log_err(cx);
154 cx.emit(DismissEvent);
155 }
156 }
157
158 fn dismissed(&mut self, _window: &mut Window, _cx: &mut Context<Picker<Self>>) {}
159
160 fn match_count(&self) -> usize {
161 self.matches.len()
162 }
163
164 fn selected_index(&self) -> usize {
165 self.selected_match_index
166 }
167
168 fn set_selected_index(
169 &mut self,
170 ix: usize,
171 _window: &mut Window,
172 _cx: &mut Context<Picker<Self>>,
173 ) {
174 self.selected_match_index = ix;
175 }
176
177 fn update_matches(
178 &mut self,
179 query: String,
180 window: &mut Window,
181 cx: &mut Context<Picker<Self>>,
182 ) -> Task<()> {
183 // Try to support rust-analyzer's path based symbols feature which
184 // allows to search by rust path syntax, in that case we only want to
185 // filter names by the last segment
186 // Ideally this was a first class LSP feature (rich queries)
187 let query_filter = query
188 .rsplit_once("::")
189 .map_or(&*query, |(_, suffix)| suffix)
190 .to_owned();
191 self.filter(&query_filter, window, cx);
192 self.show_worktree_root_name = self.project.read(cx).visible_worktrees(cx).count() > 1;
193 let symbols = self
194 .project
195 .update(cx, |project, cx| project.symbols(&query, cx));
196 cx.spawn_in(window, async move |this, cx| {
197 let symbols = symbols.await.log_err();
198 if let Some(symbols) = symbols {
199 this.update_in(cx, |this, window, cx| {
200 let delegate = &mut this.delegate;
201 let project = delegate.project.read(cx);
202 let (visible_match_candidates, external_match_candidates) = symbols
203 .iter()
204 .enumerate()
205 .map(|(id, symbol)| {
206 StringMatchCandidate::new(id, symbol.label.filter_text())
207 })
208 .partition(|candidate| {
209 if let SymbolLocation::InProject(path) = &symbols[candidate.id].path {
210 project
211 .entry_for_path(path, cx)
212 .is_some_and(|e| !e.is_ignored)
213 } else {
214 false
215 }
216 });
217
218 delegate.visible_match_candidates = visible_match_candidates;
219 delegate.external_match_candidates = external_match_candidates;
220 delegate.symbols = symbols;
221 delegate.filter(&query_filter, window, cx);
222 })
223 .log_err();
224 }
225 })
226 }
227
228 fn render_match(
229 &self,
230 ix: usize,
231 selected: bool,
232 _window: &mut Window,
233 cx: &mut Context<Picker<Self>>,
234 ) -> Option<Self::ListItem> {
235 let path_style = self.project.read(cx).path_style(cx);
236 let string_match = &self.matches.get(ix)?;
237 let symbol = &self.symbols.get(string_match.candidate_id)?;
238 let theme = cx.theme();
239 let local_player = theme.players().local();
240 let syntax_runs = styled_runs_for_code_label(&symbol.label, theme.syntax(), &local_player);
241
242 let path = match &symbol.path {
243 SymbolLocation::InProject(project_path) => {
244 let project = self.project.read(cx);
245 let mut path = project_path.path.clone();
246 if self.show_worktree_root_name
247 && let Some(worktree) = project.worktree_for_id(project_path.worktree_id, cx)
248 {
249 path = worktree.read(cx).root_name().join(&path);
250 }
251 path.display(path_style).into_owned().into()
252 }
253 SymbolLocation::OutsideProject {
254 abs_path,
255 signature: _,
256 } => abs_path.to_string_lossy(),
257 };
258 let label = symbol.label.text.clone();
259 let line_number = symbol.range.start.0.row + 1;
260 let path = path.into_owned();
261
262 let settings = ThemeSettings::get_global(cx);
263
264 let text_style = TextStyle {
265 color: cx.theme().colors().text,
266 font_family: settings.buffer_font.family.clone(),
267 font_features: settings.buffer_font.features.clone(),
268 font_fallbacks: settings.buffer_font.fallbacks.clone(),
269 font_size: settings.buffer_font_size(cx).into(),
270 font_weight: settings.buffer_font.weight,
271 line_height: relative(1.),
272 ..Default::default()
273 };
274
275 let highlight_style = HighlightStyle {
276 background_color: Some(cx.theme().colors().text_accent.alpha(0.3)),
277 ..Default::default()
278 };
279 let custom_highlights = string_match
280 .positions
281 .iter()
282 .map(|pos| (*pos..pos + 1, highlight_style));
283
284 let highlights = gpui::combine_highlights(custom_highlights, syntax_runs);
285
286 Some(
287 ListItem::new(ix)
288 .inset(true)
289 .spacing(ListItemSpacing::Sparse)
290 .toggle_state(selected)
291 .child(
292 v_flex()
293 .child(LabelLike::new().child(
294 StyledText::new(label).with_default_highlights(&text_style, highlights),
295 ))
296 .child(
297 h_flex()
298 .child(Label::new(path).size(LabelSize::Small).color(Color::Muted))
299 .child(
300 Label::new(format!(":{}", line_number))
301 .size(LabelSize::Small)
302 .color(Color::Placeholder),
303 ),
304 ),
305 ),
306 )
307 }
308}
309
310#[cfg(test)]
311mod tests {
312 use super::*;
313 use futures::StreamExt;
314 use gpui::{TestAppContext, VisualContext};
315 use language::{FakeLspAdapter, Language, LanguageConfig, LanguageMatcher};
316 use lsp::OneOf;
317 use project::FakeFs;
318 use serde_json::json;
319 use settings::SettingsStore;
320 use std::{path::Path, sync::Arc};
321 use util::path;
322 use workspace::MultiWorkspace;
323
324 #[gpui::test]
325 async fn test_project_symbols(cx: &mut TestAppContext) {
326 init_test(cx);
327
328 let fs = FakeFs::new(cx.executor());
329 fs.insert_tree(path!("/dir"), json!({ "test.rs": "" }))
330 .await;
331
332 let project = Project::test(fs.clone(), [path!("/dir").as_ref()], cx).await;
333
334 let language_registry = project.read_with(cx, |project, _| project.languages().clone());
335 language_registry.add(Arc::new(Language::new(
336 LanguageConfig {
337 name: "Rust".into(),
338 matcher: LanguageMatcher {
339 path_suffixes: vec!["rs".to_string()],
340 ..Default::default()
341 },
342 ..Default::default()
343 },
344 None,
345 )));
346 let mut fake_servers = language_registry.register_fake_lsp(
347 "Rust",
348 FakeLspAdapter {
349 capabilities: lsp::ServerCapabilities {
350 workspace_symbol_provider: Some(OneOf::Left(true)),
351 ..Default::default()
352 },
353 ..Default::default()
354 },
355 );
356
357 let _buffer = project
358 .update(cx, |project, cx| {
359 project.open_local_buffer_with_lsp(path!("/dir/test.rs"), cx)
360 })
361 .await
362 .unwrap();
363
364 // Set up fake language server to return fuzzy matches against
365 // a fixed set of symbol names.
366 let fake_symbols = [
367 symbol("one", path!("/external")),
368 symbol("ton", path!("/dir/test.rs")),
369 symbol("uno", path!("/dir/test.rs")),
370 ];
371 let fake_server = fake_servers.next().await.unwrap();
372 fake_server.set_request_handler::<lsp::WorkspaceSymbolRequest, _, _>(
373 move |params: lsp::WorkspaceSymbolParams, cx| {
374 let executor = cx.background_executor().clone();
375 let fake_symbols = fake_symbols.clone();
376 async move {
377 let (query, prefixed) = match params.query.strip_prefix("dir::") {
378 Some(query) => (query, true),
379 None => (&*params.query, false),
380 };
381 let candidates = fake_symbols
382 .iter()
383 .enumerate()
384 .filter(|(_, symbol)| {
385 !prefixed || symbol.location.uri.path().contains("dir")
386 })
387 .map(|(id, symbol)| StringMatchCandidate::new(id, &symbol.name))
388 .collect::<Vec<_>>();
389 let matches = if query.is_empty() {
390 Vec::new()
391 } else {
392 fuzzy::match_strings(
393 &candidates,
394 &query,
395 true,
396 true,
397 100,
398 &Default::default(),
399 executor.clone(),
400 )
401 .await
402 };
403
404 Ok(Some(lsp::WorkspaceSymbolResponse::Flat(
405 matches
406 .into_iter()
407 .map(|mat| fake_symbols[mat.candidate_id].clone())
408 .collect(),
409 )))
410 }
411 },
412 );
413
414 let (multi_workspace, cx) =
415 cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
416 let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
417
418 // Create the project symbols view.
419 let symbols = cx.new_window_entity(|window, cx| {
420 Picker::uniform_list(
421 ProjectSymbolsDelegate::new(workspace.downgrade(), project.clone()),
422 window,
423 cx,
424 )
425 });
426
427 // Spawn multiples updates before the first update completes,
428 // such that in the end, there are no matches. Testing for regression:
429 // https://github.com/zed-industries/zed/issues/861
430 symbols.update_in(cx, |p, window, cx| {
431 p.update_matches("o".to_string(), window, cx);
432 p.update_matches("on".to_string(), window, cx);
433 p.update_matches("onex".to_string(), window, cx);
434 });
435
436 cx.run_until_parked();
437 symbols.read_with(cx, |symbols, _| {
438 assert_eq!(symbols.delegate.matches.len(), 0);
439 });
440
441 // Spawn more updates such that in the end, there are matches.
442 symbols.update_in(cx, |p, window, cx| {
443 p.update_matches("one".to_string(), window, cx);
444 p.update_matches("on".to_string(), window, cx);
445 });
446
447 cx.run_until_parked();
448 symbols.read_with(cx, |symbols, _| {
449 let delegate = &symbols.delegate;
450 assert_eq!(delegate.matches.len(), 2);
451 assert_eq!(delegate.matches[0].string, "ton");
452 assert_eq!(delegate.matches[1].string, "one");
453 });
454
455 // Spawn more updates such that in the end, there are again no matches.
456 symbols.update_in(cx, |p, window, cx| {
457 p.update_matches("o".to_string(), window, cx);
458 p.update_matches("".to_string(), window, cx);
459 });
460
461 cx.run_until_parked();
462 symbols.read_with(cx, |symbols, _| {
463 assert_eq!(symbols.delegate.matches.len(), 0);
464 });
465
466 // Check that rust-analyzer path style symbols work
467 symbols.update_in(cx, |p, window, cx| {
468 p.update_matches("dir::to".to_string(), window, cx);
469 });
470
471 cx.run_until_parked();
472 symbols.read_with(cx, |symbols, _| {
473 assert_eq!(symbols.delegate.matches.len(), 1);
474 });
475 }
476
477 fn init_test(cx: &mut TestAppContext) {
478 cx.update(|cx| {
479 let store = SettingsStore::test(cx);
480 cx.set_global(store);
481 theme_settings::init(theme::LoadThemes::JustBase, cx);
482 release_channel::init(semver::Version::new(0, 0, 0), cx);
483 editor::init(cx);
484 });
485 }
486
487 fn symbol(name: &str, path: impl AsRef<Path>) -> lsp::SymbolInformation {
488 #[allow(deprecated)]
489 lsp::SymbolInformation {
490 name: name.to_string(),
491 kind: lsp::SymbolKind::FUNCTION,
492 tags: None,
493 deprecated: None,
494 container_name: None,
495 location: lsp::Location::new(
496 lsp::Uri::from_file_path(path.as_ref()).unwrap(),
497 lsp::Range::new(lsp::Position::new(0, 0), lsp::Position::new(0, 0)),
498 ),
499 }
500 }
501}