project_symbols.rs

  1use editor::{scroll::Autoscroll, styled_runs_for_code_label, Bias, Editor};
  2use fuzzy::{StringMatch, StringMatchCandidate};
  3use gpui::{
  4    rems, AppContext, DismissEvent, FontWeight, Model, ParentElement, StyledText, Task, View,
  5    ViewContext, WeakView, WindowContext,
  6};
  7use ordered_float::OrderedFloat;
  8use picker::{Picker, PickerDelegate};
  9use project::{Project, Symbol};
 10use std::{borrow::Cow, cmp::Reverse, sync::Arc};
 11use theme::ActiveTheme;
 12use util::ResultExt;
 13use workspace::{
 14    ui::{v_flex, Color, Label, LabelCommon, LabelLike, ListItem, ListItemSpacing, Toggleable},
 15    Workspace,
 16};
 17
 18pub fn init(cx: &mut AppContext) {
 19    cx.observe_new_views(
 20        |workspace: &mut Workspace, _: &mut ViewContext<Workspace>| {
 21            workspace.register_action(|workspace, _: &workspace::ToggleProjectSymbols, cx| {
 22                let project = workspace.project().clone();
 23                let handle = cx.view().downgrade();
 24                workspace.toggle_modal(cx, move |cx| {
 25                    let delegate = ProjectSymbolsDelegate::new(handle, project);
 26                    Picker::uniform_list(delegate, cx).width(rems(34.))
 27                })
 28            });
 29        },
 30    )
 31    .detach();
 32}
 33
 34pub type ProjectSymbols = View<Picker<ProjectSymbolsDelegate>>;
 35
 36pub struct ProjectSymbolsDelegate {
 37    workspace: WeakView<Workspace>,
 38    project: Model<Project>,
 39    selected_match_index: usize,
 40    symbols: Vec<Symbol>,
 41    visible_match_candidates: Vec<StringMatchCandidate>,
 42    external_match_candidates: Vec<StringMatchCandidate>,
 43    show_worktree_root_name: bool,
 44    matches: Vec<StringMatch>,
 45}
 46
 47impl ProjectSymbolsDelegate {
 48    fn new(workspace: WeakView<Workspace>, project: Model<Project>) -> Self {
 49        Self {
 50            workspace,
 51            project,
 52            selected_match_index: 0,
 53            symbols: Default::default(),
 54            visible_match_candidates: Default::default(),
 55            external_match_candidates: Default::default(),
 56            matches: Default::default(),
 57            show_worktree_root_name: false,
 58        }
 59    }
 60
 61    fn filter(&mut self, query: &str, cx: &mut ViewContext<Picker<Self>>) {
 62        const MAX_MATCHES: usize = 100;
 63        let mut visible_matches = cx.background_executor().block(fuzzy::match_strings(
 64            &self.visible_match_candidates,
 65            query,
 66            false,
 67            MAX_MATCHES,
 68            &Default::default(),
 69            cx.background_executor().clone(),
 70        ));
 71        let mut external_matches = cx.background_executor().block(fuzzy::match_strings(
 72            &self.external_match_candidates,
 73            query,
 74            false,
 75            MAX_MATCHES - visible_matches.len().min(MAX_MATCHES),
 76            &Default::default(),
 77            cx.background_executor().clone(),
 78        ));
 79        let sort_key_for_match = |mat: &StringMatch| {
 80            let symbol = &self.symbols[mat.candidate_id];
 81            (Reverse(OrderedFloat(mat.score)), symbol.label.filter_text())
 82        };
 83
 84        visible_matches.sort_unstable_by_key(sort_key_for_match);
 85        external_matches.sort_unstable_by_key(sort_key_for_match);
 86        let mut matches = visible_matches;
 87        matches.append(&mut external_matches);
 88
 89        for mat in &mut matches {
 90            let symbol = &self.symbols[mat.candidate_id];
 91            let filter_start = symbol.label.filter_range.start;
 92            for position in &mut mat.positions {
 93                *position += filter_start;
 94            }
 95        }
 96
 97        self.matches = matches;
 98        self.set_selected_index(0, cx);
 99    }
100}
101
102impl PickerDelegate for ProjectSymbolsDelegate {
103    type ListItem = ListItem;
104    fn placeholder_text(&self, _cx: &mut WindowContext) -> Arc<str> {
105        "Search project symbols...".into()
106    }
107
108    fn confirm(&mut self, secondary: bool, cx: &mut ViewContext<Picker<Self>>) {
109        if let Some(symbol) = self
110            .matches
111            .get(self.selected_match_index)
112            .map(|mat| self.symbols[mat.candidate_id].clone())
113        {
114            let buffer = self.project.update(cx, |project, cx| {
115                project.open_buffer_for_symbol(&symbol, cx)
116            });
117            let symbol = symbol.clone();
118            let workspace = self.workspace.clone();
119            cx.spawn(|_, mut cx| async move {
120                let buffer = buffer.await?;
121                workspace.update(&mut cx, |workspace, cx| {
122                    let position = buffer
123                        .read(cx)
124                        .clip_point_utf16(symbol.range.start, Bias::Left);
125                    let pane = if secondary {
126                        workspace.adjacent_pane(cx)
127                    } else {
128                        workspace.active_pane().clone()
129                    };
130
131                    let editor =
132                        workspace.open_project_item::<Editor>(pane, buffer, true, true, cx);
133
134                    editor.update(cx, |editor, cx| {
135                        editor.change_selections(Some(Autoscroll::center()), cx, |s| {
136                            s.select_ranges([position..position])
137                        });
138                    });
139                })?;
140                Ok::<_, anyhow::Error>(())
141            })
142            .detach_and_log_err(cx);
143            cx.emit(DismissEvent);
144        }
145    }
146
147    fn dismissed(&mut self, _cx: &mut ViewContext<Picker<Self>>) {}
148
149    fn match_count(&self) -> usize {
150        self.matches.len()
151    }
152
153    fn selected_index(&self) -> usize {
154        self.selected_match_index
155    }
156
157    fn set_selected_index(&mut self, ix: usize, _cx: &mut ViewContext<Picker<Self>>) {
158        self.selected_match_index = ix;
159    }
160
161    fn update_matches(&mut self, query: String, cx: &mut ViewContext<Picker<Self>>) -> Task<()> {
162        self.filter(&query, cx);
163        self.show_worktree_root_name = self.project.read(cx).visible_worktrees(cx).count() > 1;
164        let symbols = self
165            .project
166            .update(cx, |project, cx| project.symbols(&query, cx));
167        cx.spawn(|this, mut cx| async move {
168            let symbols = symbols.await.log_err();
169            if let Some(symbols) = symbols {
170                this.update(&mut cx, |this, cx| {
171                    let delegate = &mut this.delegate;
172                    let project = delegate.project.read(cx);
173                    let (visible_match_candidates, external_match_candidates) = symbols
174                        .iter()
175                        .enumerate()
176                        .map(|(id, symbol)| {
177                            StringMatchCandidate::new(id, &symbol.label.filter_text())
178                        })
179                        .partition(|candidate| {
180                            project
181                                .entry_for_path(&symbols[candidate.id].path, cx)
182                                .map_or(false, |e| !e.is_ignored)
183                        });
184
185                    delegate.visible_match_candidates = visible_match_candidates;
186                    delegate.external_match_candidates = external_match_candidates;
187                    delegate.symbols = symbols;
188                    delegate.filter(&query, cx);
189                })
190                .log_err();
191            }
192        })
193    }
194
195    fn render_match(
196        &self,
197        ix: usize,
198        selected: bool,
199        cx: &mut ViewContext<Picker<Self>>,
200    ) -> Option<Self::ListItem> {
201        let string_match = &self.matches[ix];
202        let symbol = &self.symbols[string_match.candidate_id];
203        let syntax_runs = styled_runs_for_code_label(&symbol.label, cx.theme().syntax());
204
205        let mut path = symbol.path.path.to_string_lossy();
206        if self.show_worktree_root_name {
207            let project = self.project.read(cx);
208            if let Some(worktree) = project.worktree_for_id(symbol.path.worktree_id, cx) {
209                path = Cow::Owned(format!(
210                    "{}{}{}",
211                    worktree.read(cx).root_name(),
212                    std::path::MAIN_SEPARATOR,
213                    path.as_ref()
214                ));
215            }
216        }
217        let label = symbol.label.text.clone();
218        let path = path.to_string().clone();
219
220        let highlights = gpui::combine_highlights(
221            string_match
222                .positions
223                .iter()
224                .map(|pos| (*pos..pos + 1, FontWeight::BOLD.into())),
225            syntax_runs.map(|(range, mut highlight)| {
226                // Ignore font weight for syntax highlighting, as we'll use it
227                // for fuzzy matches.
228                highlight.font_weight = None;
229                (range, highlight)
230            }),
231        );
232
233        Some(
234            ListItem::new(ix)
235                .inset(true)
236                .spacing(ListItemSpacing::Sparse)
237                .toggle_state(selected)
238                .child(
239                    v_flex()
240                        .child(
241                            LabelLike::new().child(
242                                StyledText::new(label)
243                                    .with_highlights(&cx.text_style().clone(), highlights),
244                            ),
245                        )
246                        .child(Label::new(path).color(Color::Muted)),
247                ),
248        )
249    }
250}
251
252#[cfg(test)]
253mod tests {
254    use super::*;
255    use futures::StreamExt;
256    use gpui::{SemanticVersion, TestAppContext, VisualContext};
257    use language::{FakeLspAdapter, Language, LanguageConfig, LanguageMatcher};
258    use project::FakeFs;
259    use serde_json::json;
260    use settings::SettingsStore;
261    use std::{path::Path, sync::Arc};
262
263    #[gpui::test]
264    async fn test_project_symbols(cx: &mut TestAppContext) {
265        init_test(cx);
266
267        let fs = FakeFs::new(cx.executor());
268        fs.insert_tree("/dir", json!({ "test.rs": "" })).await;
269
270        let project = Project::test(fs.clone(), ["/dir".as_ref()], cx).await;
271
272        let language_registry = project.read_with(cx, |project, _| project.languages().clone());
273        language_registry.add(Arc::new(Language::new(
274            LanguageConfig {
275                name: "Rust".into(),
276                matcher: LanguageMatcher {
277                    path_suffixes: vec!["rs".to_string()],
278                    ..Default::default()
279                },
280                ..Default::default()
281            },
282            None,
283        )));
284        let mut fake_servers =
285            language_registry.register_fake_lsp("Rust", FakeLspAdapter::default());
286
287        let _buffer = project
288            .update(cx, |project, cx| {
289                project.open_local_buffer_with_lsp("/dir/test.rs", cx)
290            })
291            .await
292            .unwrap();
293
294        // Set up fake language server to return fuzzy matches against
295        // a fixed set of symbol names.
296        let fake_symbols = [
297            symbol("one", "/external"),
298            symbol("ton", "/dir/test.rs"),
299            symbol("uno", "/dir/test.rs"),
300        ];
301        let fake_server = fake_servers.next().await.unwrap();
302        fake_server.handle_request::<lsp::WorkspaceSymbolRequest, _, _>(
303            move |params: lsp::WorkspaceSymbolParams, cx| {
304                let executor = cx.background_executor().clone();
305                let fake_symbols = fake_symbols.clone();
306                async move {
307                    let candidates = fake_symbols
308                        .iter()
309                        .enumerate()
310                        .map(|(id, symbol)| StringMatchCandidate::new(id, &symbol.name))
311                        .collect::<Vec<_>>();
312                    let matches = if params.query.is_empty() {
313                        Vec::new()
314                    } else {
315                        fuzzy::match_strings(
316                            &candidates,
317                            &params.query,
318                            true,
319                            100,
320                            &Default::default(),
321                            executor.clone(),
322                        )
323                        .await
324                    };
325
326                    Ok(Some(lsp::WorkspaceSymbolResponse::Flat(
327                        matches
328                            .into_iter()
329                            .map(|mat| fake_symbols[mat.candidate_id].clone())
330                            .collect(),
331                    )))
332                }
333            },
334        );
335
336        let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project.clone(), cx));
337
338        // Create the project symbols view.
339        let symbols = cx.new_view(|cx| {
340            Picker::uniform_list(
341                ProjectSymbolsDelegate::new(workspace.downgrade(), project.clone()),
342                cx,
343            )
344        });
345
346        // Spawn multiples updates before the first update completes,
347        // such that in the end, there are no matches. Testing for regression:
348        // https://github.com/zed-industries/zed/issues/861
349        symbols.update(cx, |p, cx| {
350            p.update_matches("o".to_string(), cx);
351            p.update_matches("on".to_string(), cx);
352            p.update_matches("onex".to_string(), cx);
353        });
354
355        cx.run_until_parked();
356        symbols.update(cx, |symbols, _| {
357            assert_eq!(symbols.delegate.matches.len(), 0);
358        });
359
360        // Spawn more updates such that in the end, there are matches.
361        symbols.update(cx, |p, cx| {
362            p.update_matches("one".to_string(), cx);
363            p.update_matches("on".to_string(), cx);
364        });
365
366        cx.run_until_parked();
367        symbols.update(cx, |symbols, _| {
368            let delegate = &symbols.delegate;
369            assert_eq!(delegate.matches.len(), 2);
370            assert_eq!(delegate.matches[0].string, "ton");
371            assert_eq!(delegate.matches[1].string, "one");
372        });
373
374        // Spawn more updates such that in the end, there are again no matches.
375        symbols.update(cx, |p, cx| {
376            p.update_matches("o".to_string(), cx);
377            p.update_matches("".to_string(), cx);
378        });
379
380        cx.run_until_parked();
381        symbols.update(cx, |symbols, _| {
382            assert_eq!(symbols.delegate.matches.len(), 0);
383        });
384    }
385
386    fn init_test(cx: &mut TestAppContext) {
387        cx.update(|cx| {
388            let store = SettingsStore::test(cx);
389            cx.set_global(store);
390            theme::init(theme::LoadThemes::JustBase, cx);
391            release_channel::init(SemanticVersion::default(), cx);
392            language::init(cx);
393            Project::init_settings(cx);
394            workspace::init_settings(cx);
395            editor::init(cx);
396        });
397    }
398
399    fn symbol(name: &str, path: impl AsRef<Path>) -> lsp::SymbolInformation {
400        #[allow(deprecated)]
401        lsp::SymbolInformation {
402            name: name.to_string(),
403            kind: lsp::SymbolKind::FUNCTION,
404            tags: None,
405            deprecated: None,
406            container_name: None,
407            location: lsp::Location::new(
408                lsp::Url::from_file_path(path.as_ref()).unwrap(),
409                lsp::Range::new(lsp::Position::new(0, 0), lsp::Position::new(0, 0)),
410            ),
411        }
412    }
413}