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..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(LabelLike::new().child(
303                            StyledText::new(label).with_default_highlights(&text_style, highlights),
304                        ))
305                        .child(
306                            h_flex()
307                                .child(Label::new(path).size(LabelSize::Small).color(Color::Muted))
308                                .child(
309                                    Label::new(format!(":{}", line_number))
310                                        .size(LabelSize::Small)
311                                        .color(Color::Placeholder),
312                                ),
313                        ),
314                ),
315        )
316    }
317}
318
319#[cfg(test)]
320mod tests {
321    use super::*;
322    use futures::StreamExt;
323    use gpui::{TestAppContext, VisualContext};
324    use language::{FakeLspAdapter, Language, LanguageConfig, LanguageMatcher};
325    use lsp::OneOf;
326    use project::FakeFs;
327    use serde_json::json;
328    use settings::SettingsStore;
329    use std::{path::Path, sync::Arc};
330    use util::path;
331    use workspace::MultiWorkspace;
332
333    #[gpui::test]
334    async fn test_project_symbols(cx: &mut TestAppContext) {
335        init_test(cx);
336
337        let fs = FakeFs::new(cx.executor());
338        fs.insert_tree(path!("/dir"), json!({ "test.rs": "" }))
339            .await;
340
341        let project = Project::test(fs.clone(), [path!("/dir").as_ref()], cx).await;
342
343        let language_registry = project.read_with(cx, |project, _| project.languages().clone());
344        language_registry.add(Arc::new(Language::new(
345            LanguageConfig {
346                name: "Rust".into(),
347                matcher: LanguageMatcher {
348                    path_suffixes: vec!["rs".to_string()],
349                    ..Default::default()
350                },
351                ..Default::default()
352            },
353            None,
354        )));
355        let mut fake_servers = language_registry.register_fake_lsp(
356            "Rust",
357            FakeLspAdapter {
358                capabilities: lsp::ServerCapabilities {
359                    workspace_symbol_provider: Some(OneOf::Left(true)),
360                    ..Default::default()
361                },
362                ..Default::default()
363            },
364        );
365
366        let _buffer = project
367            .update(cx, |project, cx| {
368                project.open_local_buffer_with_lsp(path!("/dir/test.rs"), cx)
369            })
370            .await
371            .unwrap();
372
373        // Set up fake language server to return fuzzy matches against
374        // a fixed set of symbol names.
375        let fake_symbols = [
376            symbol("one", path!("/external")),
377            symbol("ton", path!("/dir/test.rs")),
378            symbol("uno", path!("/dir/test.rs")),
379        ];
380        let fake_server = fake_servers.next().await.unwrap();
381        fake_server.set_request_handler::<lsp::WorkspaceSymbolRequest, _, _>(
382            move |params: lsp::WorkspaceSymbolParams, cx| {
383                let executor = cx.background_executor().clone();
384                let fake_symbols = fake_symbols.clone();
385                async move {
386                    let (query, prefixed) = match params.query.strip_prefix("dir::") {
387                        Some(query) => (query, true),
388                        None => (&*params.query, false),
389                    };
390                    let candidates = fake_symbols
391                        .iter()
392                        .enumerate()
393                        .filter(|(_, symbol)| {
394                            !prefixed || symbol.location.uri.path().contains("dir")
395                        })
396                        .map(|(id, symbol)| StringMatchCandidate::new(id, &symbol.name))
397                        .collect::<Vec<_>>();
398                    let matches = if query.is_empty() {
399                        Vec::new()
400                    } else {
401                        fuzzy::match_strings(
402                            &candidates,
403                            &query,
404                            true,
405                            true,
406                            100,
407                            &Default::default(),
408                            executor.clone(),
409                        )
410                        .await
411                    };
412
413                    Ok(Some(lsp::WorkspaceSymbolResponse::Flat(
414                        matches
415                            .into_iter()
416                            .map(|mat| fake_symbols[mat.candidate_id].clone())
417                            .collect(),
418                    )))
419                }
420            },
421        );
422
423        let (multi_workspace, cx) =
424            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
425        let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
426
427        // Create the project symbols view.
428        let symbols = cx.new_window_entity(|window, cx| {
429            Picker::uniform_list(
430                ProjectSymbolsDelegate::new(workspace.downgrade(), project.clone()),
431                window,
432                cx,
433            )
434        });
435
436        // Spawn multiples updates before the first update completes,
437        // such that in the end, there are no matches. Testing for regression:
438        // https://github.com/zed-industries/zed/issues/861
439        symbols.update_in(cx, |p, window, cx| {
440            p.update_matches("o".to_string(), window, cx);
441            p.update_matches("on".to_string(), window, cx);
442            p.update_matches("onex".to_string(), window, cx);
443        });
444
445        cx.run_until_parked();
446        symbols.read_with(cx, |symbols, _| {
447            assert_eq!(symbols.delegate.matches.len(), 0);
448        });
449
450        // Spawn more updates such that in the end, there are matches.
451        symbols.update_in(cx, |p, window, cx| {
452            p.update_matches("one".to_string(), window, cx);
453            p.update_matches("on".to_string(), window, cx);
454        });
455
456        cx.run_until_parked();
457        symbols.read_with(cx, |symbols, _| {
458            let delegate = &symbols.delegate;
459            assert_eq!(delegate.matches.len(), 2);
460            assert_eq!(delegate.matches[0].string, "ton");
461            assert_eq!(delegate.matches[1].string, "one");
462        });
463
464        // Spawn more updates such that in the end, there are again no matches.
465        symbols.update_in(cx, |p, window, cx| {
466            p.update_matches("o".to_string(), window, cx);
467            p.update_matches("".to_string(), window, cx);
468        });
469
470        cx.run_until_parked();
471        symbols.read_with(cx, |symbols, _| {
472            assert_eq!(symbols.delegate.matches.len(), 0);
473        });
474
475        // Check that rust-analyzer path style symbols work
476        symbols.update_in(cx, |p, window, cx| {
477            p.update_matches("dir::to".to_string(), window, cx);
478        });
479
480        cx.run_until_parked();
481        symbols.read_with(cx, |symbols, _| {
482            assert_eq!(symbols.delegate.matches.len(), 1);
483        });
484    }
485
486    fn init_test(cx: &mut TestAppContext) {
487        cx.update(|cx| {
488            let store = SettingsStore::test(cx);
489            cx.set_global(store);
490            theme_settings::init(theme::LoadThemes::JustBase, cx);
491            release_channel::init(semver::Version::new(0, 0, 0), cx);
492            editor::init(cx);
493        });
494    }
495
496    fn symbol(name: &str, path: impl AsRef<Path>) -> lsp::SymbolInformation {
497        #[allow(deprecated)]
498        lsp::SymbolInformation {
499            name: name.to_string(),
500            kind: lsp::SymbolKind::FUNCTION,
501            tags: None,
502            deprecated: None,
503            container_name: None,
504            location: lsp::Location::new(
505                lsp::Uri::from_file_path(path.as_ref()).unwrap(),
506                lsp::Range::new(lsp::Position::new(0, 0), lsp::Position::new(0, 0)),
507            ),
508        }
509    }
510}