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