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