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