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};
 10use settings::Settings;
 11use std::{borrow::Cow, 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                            project
199                                .entry_for_path(&symbols[candidate.id].path, cx)
200                                .is_some_and(|e| !e.is_ignored)
201                        });
202
203                    delegate.visible_match_candidates = visible_match_candidates;
204                    delegate.external_match_candidates = external_match_candidates;
205                    delegate.symbols = symbols;
206                    delegate.filter(&query, window, cx);
207                })
208                .log_err();
209            }
210        })
211    }
212
213    fn render_match(
214        &self,
215        ix: usize,
216        selected: bool,
217        _window: &mut Window,
218        cx: &mut Context<Picker<Self>>,
219    ) -> Option<Self::ListItem> {
220        let string_match = &self.matches[ix];
221        let symbol = &self.symbols[string_match.candidate_id];
222        let syntax_runs = styled_runs_for_code_label(&symbol.label, cx.theme().syntax());
223
224        let mut path = symbol.path.path.to_string_lossy();
225        if self.show_worktree_root_name {
226            let project = self.project.read(cx);
227            if let Some(worktree) = project.worktree_for_id(symbol.path.worktree_id, cx) {
228                path = Cow::Owned(format!(
229                    "{}{}{}",
230                    worktree.read(cx).root_name(),
231                    std::path::MAIN_SEPARATOR,
232                    path.as_ref()
233                ));
234            }
235        }
236        let label = symbol.label.text.clone();
237        let path = path.to_string();
238
239        let settings = ThemeSettings::get_global(cx);
240
241        let text_style = TextStyle {
242            color: cx.theme().colors().text,
243            font_family: settings.buffer_font.family.clone(),
244            font_features: settings.buffer_font.features.clone(),
245            font_fallbacks: settings.buffer_font.fallbacks.clone(),
246            font_size: settings.buffer_font_size(cx).into(),
247            font_weight: settings.buffer_font.weight,
248            line_height: relative(1.),
249            ..Default::default()
250        };
251
252        let highlight_style = HighlightStyle {
253            background_color: Some(cx.theme().colors().text_accent.alpha(0.3)),
254            ..Default::default()
255        };
256        let custom_highlights = string_match
257            .positions
258            .iter()
259            .map(|pos| (*pos..pos + 1, highlight_style));
260
261        let highlights = gpui::combine_highlights(custom_highlights, syntax_runs);
262
263        Some(
264            ListItem::new(ix)
265                .inset(true)
266                .spacing(ListItemSpacing::Sparse)
267                .toggle_state(selected)
268                .child(
269                    v_flex()
270                        .child(LabelLike::new().child(
271                            StyledText::new(label).with_default_highlights(&text_style, highlights),
272                        ))
273                        .child(Label::new(path).size(LabelSize::Small).color(Color::Muted)),
274                ),
275        )
276    }
277}
278
279#[cfg(test)]
280mod tests {
281    use super::*;
282    use futures::StreamExt;
283    use gpui::{SemanticVersion, TestAppContext, VisualContext};
284    use language::{FakeLspAdapter, Language, LanguageConfig, LanguageMatcher};
285    use lsp::OneOf;
286    use project::FakeFs;
287    use serde_json::json;
288    use settings::SettingsStore;
289    use std::{path::Path, sync::Arc};
290    use util::path;
291
292    #[gpui::test]
293    async fn test_project_symbols(cx: &mut TestAppContext) {
294        init_test(cx);
295
296        let fs = FakeFs::new(cx.executor());
297        fs.insert_tree(path!("/dir"), json!({ "test.rs": "" }))
298            .await;
299
300        let project = Project::test(fs.clone(), [path!("/dir").as_ref()], cx).await;
301
302        let language_registry = project.read_with(cx, |project, _| project.languages().clone());
303        language_registry.add(Arc::new(Language::new(
304            LanguageConfig {
305                name: "Rust".into(),
306                matcher: LanguageMatcher {
307                    path_suffixes: vec!["rs".to_string()],
308                    ..Default::default()
309                },
310                ..Default::default()
311            },
312            None,
313        )));
314        let mut fake_servers = language_registry.register_fake_lsp(
315            "Rust",
316            FakeLspAdapter {
317                capabilities: lsp::ServerCapabilities {
318                    workspace_symbol_provider: Some(OneOf::Left(true)),
319                    ..Default::default()
320                },
321                ..Default::default()
322            },
323        );
324
325        let _buffer = project
326            .update(cx, |project, cx| {
327                project.open_local_buffer_with_lsp(path!("/dir/test.rs"), cx)
328            })
329            .await
330            .unwrap();
331
332        // Set up fake language server to return fuzzy matches against
333        // a fixed set of symbol names.
334        let fake_symbols = [
335            symbol("one", path!("/external")),
336            symbol("ton", path!("/dir/test.rs")),
337            symbol("uno", path!("/dir/test.rs")),
338        ];
339        let fake_server = fake_servers.next().await.unwrap();
340        fake_server.set_request_handler::<lsp::WorkspaceSymbolRequest, _, _>(
341            move |params: lsp::WorkspaceSymbolParams, cx| {
342                let executor = cx.background_executor().clone();
343                let fake_symbols = fake_symbols.clone();
344                async move {
345                    let candidates = fake_symbols
346                        .iter()
347                        .enumerate()
348                        .map(|(id, symbol)| StringMatchCandidate::new(id, &symbol.name))
349                        .collect::<Vec<_>>();
350                    let matches = if params.query.is_empty() {
351                        Vec::new()
352                    } else {
353                        fuzzy::match_strings(
354                            &candidates,
355                            &params.query,
356                            true,
357                            true,
358                            100,
359                            &Default::default(),
360                            executor.clone(),
361                        )
362                        .await
363                    };
364
365                    Ok(Some(lsp::WorkspaceSymbolResponse::Flat(
366                        matches
367                            .into_iter()
368                            .map(|mat| fake_symbols[mat.candidate_id].clone())
369                            .collect(),
370                    )))
371                }
372            },
373        );
374
375        let (workspace, cx) =
376            cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
377
378        // Create the project symbols view.
379        let symbols = cx.new_window_entity(|window, cx| {
380            Picker::uniform_list(
381                ProjectSymbolsDelegate::new(workspace.downgrade(), project.clone()),
382                window,
383                cx,
384            )
385        });
386
387        // Spawn multiples updates before the first update completes,
388        // such that in the end, there are no matches. Testing for regression:
389        // https://github.com/zed-industries/zed/issues/861
390        symbols.update_in(cx, |p, window, cx| {
391            p.update_matches("o".to_string(), window, cx);
392            p.update_matches("on".to_string(), window, cx);
393            p.update_matches("onex".to_string(), window, cx);
394        });
395
396        cx.run_until_parked();
397        symbols.read_with(cx, |symbols, _| {
398            assert_eq!(symbols.delegate.matches.len(), 0);
399        });
400
401        // Spawn more updates such that in the end, there are matches.
402        symbols.update_in(cx, |p, window, cx| {
403            p.update_matches("one".to_string(), window, cx);
404            p.update_matches("on".to_string(), window, cx);
405        });
406
407        cx.run_until_parked();
408        symbols.read_with(cx, |symbols, _| {
409            let delegate = &symbols.delegate;
410            assert_eq!(delegate.matches.len(), 2);
411            assert_eq!(delegate.matches[0].string, "ton");
412            assert_eq!(delegate.matches[1].string, "one");
413        });
414
415        // Spawn more updates such that in the end, there are again no matches.
416        symbols.update_in(cx, |p, window, cx| {
417            p.update_matches("o".to_string(), window, cx);
418            p.update_matches("".to_string(), window, cx);
419        });
420
421        cx.run_until_parked();
422        symbols.read_with(cx, |symbols, _| {
423            assert_eq!(symbols.delegate.matches.len(), 0);
424        });
425    }
426
427    fn init_test(cx: &mut TestAppContext) {
428        cx.update(|cx| {
429            let store = SettingsStore::test(cx);
430            cx.set_global(store);
431            theme::init(theme::LoadThemes::JustBase, cx);
432            release_channel::init(SemanticVersion::default(), cx);
433            language::init(cx);
434            Project::init_settings(cx);
435            workspace::init_settings(cx);
436            editor::init(cx);
437        });
438    }
439
440    fn symbol(name: &str, path: impl AsRef<Path>) -> lsp::SymbolInformation {
441        #[allow(deprecated)]
442        lsp::SymbolInformation {
443            name: name.to_string(),
444            kind: lsp::SymbolKind::FUNCTION,
445            tags: None,
446            deprecated: None,
447            container_name: None,
448            location: lsp::Location::new(
449                lsp::Uri::from_file_path(path.as_ref()).unwrap(),
450                lsp::Range::new(lsp::Position::new(0, 0), lsp::Position::new(0, 0)),
451            ),
452        }
453    }
454}