project_symbols.rs

  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                        let multibuffer_snapshot = editor.buffer().read(cx).snapshot(cx);
144                        let Some(buffer_snapshot) = multibuffer_snapshot.as_singleton() else {
145                            return;
146                        };
147                        let text_anchor = buffer_snapshot.anchor_before(position);
148                        let Some(anchor) = multibuffer_snapshot.anchor_in_buffer(text_anchor)
149                        else {
150                            return;
151                        };
152                        editor.change_selections(
153                            SelectionEffects::scroll(Autoscroll::center()),
154                            window,
155                            cx,
156                            |s| s.select_ranges([anchor..anchor]),
157                        );
158                    });
159                })?;
160                anyhow::Ok(())
161            })
162            .detach_and_log_err(cx);
163            cx.emit(DismissEvent);
164        }
165    }
166
167    fn dismissed(&mut self, _window: &mut Window, _cx: &mut Context<Picker<Self>>) {}
168
169    fn match_count(&self) -> usize {
170        self.matches.len()
171    }
172
173    fn selected_index(&self) -> usize {
174        self.selected_match_index
175    }
176
177    fn set_selected_index(
178        &mut self,
179        ix: usize,
180        _window: &mut Window,
181        _cx: &mut Context<Picker<Self>>,
182    ) {
183        self.selected_match_index = ix;
184    }
185
186    fn update_matches(
187        &mut self,
188        query: String,
189        window: &mut Window,
190        cx: &mut Context<Picker<Self>>,
191    ) -> Task<()> {
192        // Try to support rust-analyzer's path based symbols feature which
193        // allows to search by rust path syntax, in that case we only want to
194        // filter names by the last segment
195        // Ideally this was a first class LSP feature (rich queries)
196        let query_filter = query
197            .rsplit_once("::")
198            .map_or(&*query, |(_, suffix)| suffix)
199            .to_owned();
200        self.filter(&query_filter, window, cx);
201        self.show_worktree_root_name = self.project.read(cx).visible_worktrees(cx).count() > 1;
202        let symbols = self
203            .project
204            .update(cx, |project, cx| project.symbols(&query, cx));
205        cx.spawn_in(window, async move |this, cx| {
206            let symbols = symbols.await.log_err();
207            if let Some(symbols) = symbols {
208                this.update_in(cx, |this, window, cx| {
209                    let delegate = &mut this.delegate;
210                    let project = delegate.project.read(cx);
211                    let (visible_match_candidates, external_match_candidates) = symbols
212                        .iter()
213                        .enumerate()
214                        .map(|(id, symbol)| {
215                            StringMatchCandidate::new(id, symbol.label.filter_text())
216                        })
217                        .partition(|candidate| {
218                            if let SymbolLocation::InProject(path) = &symbols[candidate.id].path {
219                                project
220                                    .entry_for_path(path, cx)
221                                    .is_some_and(|e| !e.is_ignored)
222                            } else {
223                                false
224                            }
225                        });
226
227                    delegate.visible_match_candidates = visible_match_candidates;
228                    delegate.external_match_candidates = external_match_candidates;
229                    delegate.symbols = symbols;
230                    delegate.filter(&query_filter, window, cx);
231                })
232                .log_err();
233            }
234        })
235    }
236
237    fn render_match(
238        &self,
239        ix: usize,
240        selected: bool,
241        _window: &mut Window,
242        cx: &mut Context<Picker<Self>>,
243    ) -> Option<Self::ListItem> {
244        let path_style = self.project.read(cx).path_style(cx);
245        let string_match = &self.matches.get(ix)?;
246        let symbol = &self.symbols.get(string_match.candidate_id)?;
247        let theme = cx.theme();
248        let local_player = theme.players().local();
249        let syntax_runs = styled_runs_for_code_label(&symbol.label, theme.syntax(), &local_player);
250
251        let path = match &symbol.path {
252            SymbolLocation::InProject(project_path) => {
253                let project = self.project.read(cx);
254                let mut path = project_path.path.clone();
255                if self.show_worktree_root_name
256                    && let Some(worktree) = project.worktree_for_id(project_path.worktree_id, cx)
257                {
258                    path = worktree.read(cx).root_name().join(&path);
259                }
260                path.display(path_style).into_owned().into()
261            }
262            SymbolLocation::OutsideProject {
263                abs_path,
264                signature: _,
265            } => abs_path.to_string_lossy(),
266        };
267        let label = symbol.label.text.clone();
268        let line_number = symbol.range.start.0.row + 1;
269        let path = path.into_owned();
270
271        let settings = ThemeSettings::get_global(cx);
272
273        let text_style = TextStyle {
274            color: cx.theme().colors().text,
275            font_family: settings.buffer_font.family.clone(),
276            font_features: settings.buffer_font.features.clone(),
277            font_fallbacks: settings.buffer_font.fallbacks.clone(),
278            font_size: settings.buffer_font_size(cx).into(),
279            font_weight: settings.buffer_font.weight,
280            line_height: relative(1.),
281            ..Default::default()
282        };
283
284        let highlight_style = HighlightStyle {
285            background_color: Some(cx.theme().colors().text_accent.alpha(0.3)),
286            ..Default::default()
287        };
288        let custom_highlights = string_match
289            .positions
290            .iter()
291            .map(|pos| (*pos..label.ceil_char_boundary(pos + 1), highlight_style));
292
293        let highlights = gpui::combine_highlights(custom_highlights, syntax_runs);
294
295        Some(
296            ListItem::new(ix)
297                .inset(true)
298                .spacing(ListItemSpacing::Sparse)
299                .toggle_state(selected)
300                .child(
301                    v_flex()
302                        .child(
303                            LabelLike::new().child(
304                                StyledText::new(&label)
305                                    .with_default_highlights(&text_style, highlights),
306                            ),
307                        )
308                        .child(
309                            h_flex()
310                                .child(Label::new(path).size(LabelSize::Small).color(Color::Muted))
311                                .child(
312                                    Label::new(format!(":{}", line_number))
313                                        .size(LabelSize::Small)
314                                        .color(Color::Placeholder),
315                                ),
316                        ),
317                ),
318        )
319    }
320}
321
322#[cfg(test)]
323mod tests {
324    use super::*;
325    use futures::StreamExt;
326    use gpui::{TestAppContext, VisualContext};
327    use language::{FakeLspAdapter, Language, LanguageConfig, LanguageMatcher};
328    use lsp::OneOf;
329    use project::FakeFs;
330    use serde_json::json;
331    use settings::SettingsStore;
332    use std::{path::Path, sync::Arc};
333    use util::path;
334    use workspace::MultiWorkspace;
335
336    #[gpui::test]
337    async fn test_project_symbols(cx: &mut TestAppContext) {
338        init_test(cx);
339
340        let fs = FakeFs::new(cx.executor());
341        fs.insert_tree(path!("/dir"), json!({ "test.rs": "" }))
342            .await;
343
344        let project = Project::test(fs.clone(), [path!("/dir").as_ref()], cx).await;
345
346        let language_registry = project.read_with(cx, |project, _| project.languages().clone());
347        language_registry.add(Arc::new(Language::new(
348            LanguageConfig {
349                name: "Rust".into(),
350                matcher: LanguageMatcher {
351                    path_suffixes: vec!["rs".to_string()],
352                    ..Default::default()
353                },
354                ..Default::default()
355            },
356            None,
357        )));
358        let mut fake_servers = language_registry.register_fake_lsp(
359            "Rust",
360            FakeLspAdapter {
361                capabilities: lsp::ServerCapabilities {
362                    workspace_symbol_provider: Some(OneOf::Left(true)),
363                    ..Default::default()
364                },
365                ..Default::default()
366            },
367        );
368
369        let _buffer = project
370            .update(cx, |project, cx| {
371                project.open_local_buffer_with_lsp(path!("/dir/test.rs"), cx)
372            })
373            .await
374            .unwrap();
375
376        // Set up fake language server to return fuzzy matches against
377        // a fixed set of symbol names.
378        let fake_symbols = [
379            symbol("one", path!("/external")),
380            symbol("ton", path!("/dir/test.rs")),
381            symbol("uno", path!("/dir/test.rs")),
382        ];
383        let fake_server = fake_servers.next().await.unwrap();
384        fake_server.set_request_handler::<lsp::WorkspaceSymbolRequest, _, _>(
385            move |params: lsp::WorkspaceSymbolParams, cx| {
386                let executor = cx.background_executor().clone();
387                let fake_symbols = fake_symbols.clone();
388                async move {
389                    let (query, prefixed) = match params.query.strip_prefix("dir::") {
390                        Some(query) => (query, true),
391                        None => (&*params.query, false),
392                    };
393                    let candidates = fake_symbols
394                        .iter()
395                        .enumerate()
396                        .filter(|(_, symbol)| {
397                            !prefixed || symbol.location.uri.path().contains("dir")
398                        })
399                        .map(|(id, symbol)| StringMatchCandidate::new(id, &symbol.name))
400                        .collect::<Vec<_>>();
401                    let matches = if query.is_empty() {
402                        Vec::new()
403                    } else {
404                        fuzzy::match_strings(
405                            &candidates,
406                            &query,
407                            true,
408                            true,
409                            100,
410                            &Default::default(),
411                            executor.clone(),
412                        )
413                        .await
414                    };
415
416                    Ok(Some(lsp::WorkspaceSymbolResponse::Flat(
417                        matches
418                            .into_iter()
419                            .map(|mat| fake_symbols[mat.candidate_id].clone())
420                            .collect(),
421                    )))
422                }
423            },
424        );
425
426        let (multi_workspace, cx) =
427            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
428        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
429
430        // Create the project symbols view.
431        let symbols = cx.new_window_entity(|window, cx| {
432            Picker::uniform_list(
433                ProjectSymbolsDelegate::new(workspace.downgrade(), project.clone()),
434                window,
435                cx,
436            )
437        });
438
439        // Spawn multiples updates before the first update completes,
440        // such that in the end, there are no matches. Testing for regression:
441        // https://github.com/zed-industries/zed/issues/861
442        symbols.update_in(cx, |p, window, cx| {
443            p.update_matches("o".to_string(), window, cx);
444            p.update_matches("on".to_string(), window, cx);
445            p.update_matches("onex".to_string(), window, cx);
446        });
447
448        cx.run_until_parked();
449        symbols.read_with(cx, |symbols, _| {
450            assert_eq!(symbols.delegate.matches.len(), 0);
451        });
452
453        // Spawn more updates such that in the end, there are matches.
454        symbols.update_in(cx, |p, window, cx| {
455            p.update_matches("one".to_string(), window, cx);
456            p.update_matches("on".to_string(), window, cx);
457        });
458
459        cx.run_until_parked();
460        symbols.read_with(cx, |symbols, _| {
461            let delegate = &symbols.delegate;
462            assert_eq!(delegate.matches.len(), 2);
463            assert_eq!(delegate.matches[0].string, "ton");
464            assert_eq!(delegate.matches[1].string, "one");
465        });
466
467        // Spawn more updates such that in the end, there are again no matches.
468        symbols.update_in(cx, |p, window, cx| {
469            p.update_matches("o".to_string(), window, cx);
470            p.update_matches("".to_string(), window, cx);
471        });
472
473        cx.run_until_parked();
474        symbols.read_with(cx, |symbols, _| {
475            assert_eq!(symbols.delegate.matches.len(), 0);
476        });
477
478        // Check that rust-analyzer path style symbols work
479        symbols.update_in(cx, |p, window, cx| {
480            p.update_matches("dir::to".to_string(), window, cx);
481        });
482
483        cx.run_until_parked();
484        symbols.read_with(cx, |symbols, _| {
485            assert_eq!(symbols.delegate.matches.len(), 1);
486        });
487    }
488
489    #[gpui::test]
490    async fn test_project_symbols_renders_utf8_match(cx: &mut TestAppContext) {
491        init_test(cx);
492
493        let fs = FakeFs::new(cx.executor());
494        fs.insert_tree(path!("/dir"), json!({ "test.rs": "" }))
495            .await;
496
497        let project = Project::test(fs.clone(), [path!("/dir").as_ref()], cx).await;
498
499        let language_registry = project.read_with(cx, |project, _| project.languages().clone());
500        language_registry.add(Arc::new(Language::new(
501            LanguageConfig {
502                name: "Rust".into(),
503                matcher: LanguageMatcher {
504                    path_suffixes: vec!["rs".to_string()],
505                    ..Default::default()
506                },
507                ..Default::default()
508            },
509            None,
510        )));
511        let mut fake_servers = language_registry.register_fake_lsp(
512            "Rust",
513            FakeLspAdapter {
514                capabilities: lsp::ServerCapabilities {
515                    workspace_symbol_provider: Some(OneOf::Left(true)),
516                    ..Default::default()
517                },
518                ..Default::default()
519            },
520        );
521
522        let _buffer = project
523            .update(cx, |project, cx| {
524                project.open_local_buffer_with_lsp(path!("/dir/test.rs"), cx)
525            })
526            .await
527            .unwrap();
528
529        let fake_symbols = [symbol("안녕", path!("/dir/test.rs"))];
530        let fake_server = fake_servers.next().await.unwrap();
531        fake_server.set_request_handler::<lsp::WorkspaceSymbolRequest, _, _>(
532            move |params: lsp::WorkspaceSymbolParams, cx| {
533                let executor = cx.background_executor().clone();
534                let fake_symbols = fake_symbols.clone();
535                async move {
536                    let candidates = fake_symbols
537                        .iter()
538                        .enumerate()
539                        .map(|(id, symbol)| StringMatchCandidate::new(id, &symbol.name))
540                        .collect::<Vec<_>>();
541                    let matches = fuzzy::match_strings(
542                        &candidates,
543                        &params.query,
544                        true,
545                        true,
546                        100,
547                        &Default::default(),
548                        executor,
549                    )
550                    .await;
551
552                    Ok(Some(lsp::WorkspaceSymbolResponse::Flat(
553                        matches
554                            .into_iter()
555                            .map(|mat| fake_symbols[mat.candidate_id].clone())
556                            .collect(),
557                    )))
558                }
559            },
560        );
561
562        let (multi_workspace, cx) =
563            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
564        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
565
566        let symbols = cx.new_window_entity(|window, cx| {
567            Picker::uniform_list(
568                ProjectSymbolsDelegate::new(workspace.downgrade(), project.clone()),
569                window,
570                cx,
571            )
572        });
573
574        symbols.update_in(cx, |p, window, cx| {
575            p.update_matches("".to_string(), window, cx);
576        });
577
578        cx.run_until_parked();
579        symbols.read_with(cx, |symbols, _| {
580            assert_eq!(symbols.delegate.matches.len(), 1);
581            assert_eq!(symbols.delegate.matches[0].string, "안녕");
582        });
583
584        symbols.update_in(cx, |p, window, cx| {
585            assert!(p.delegate.render_match(0, false, window, cx).is_some());
586        });
587    }
588
589    fn init_test(cx: &mut TestAppContext) {
590        cx.update(|cx| {
591            let store = SettingsStore::test(cx);
592            cx.set_global(store);
593            theme_settings::init(theme::LoadThemes::JustBase, cx);
594            release_channel::init(semver::Version::new(0, 0, 0), cx);
595            editor::init(cx);
596        });
597    }
598
599    fn symbol(name: &str, path: impl AsRef<Path>) -> lsp::SymbolInformation {
600        #[allow(deprecated)]
601        lsp::SymbolInformation {
602            name: name.to_string(),
603            kind: lsp::SymbolKind::FUNCTION,
604            tags: None,
605            deprecated: None,
606            container_name: None,
607            location: lsp::Location::new(
608                lsp::Uri::from_file_path(path.as_ref()).unwrap(),
609                lsp::Range::new(lsp::Position::new(0, 0), lsp::Position::new(0, 0)),
610            ),
611        }
612    }
613}