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