project_symbols.rs

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