project_symbols.rs

  1use editor::{scroll::autoscroll::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,
  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_stack, 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::new(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) -> 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
131                    let editor = if secondary {
132                        workspace.split_project_item::<Editor>(buffer, cx)
133                    } else {
134                        workspace.open_project_item::<Editor>(buffer, cx)
135                    };
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                    // todo!() combine_syntax_and_fuzzy_match_highlights()
246                    v_stack()
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};
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 mut language = Language::new(
275            LanguageConfig {
276                name: "Rust".into(),
277                path_suffixes: vec!["rs".to_string()],
278                ..Default::default()
279            },
280            None,
281        );
282        let mut fake_servers = language
283            .set_fake_lsp_adapter(Arc::<FakeLspAdapter>::default())
284            .await;
285
286        let fs = FakeFs::new(cx.executor());
287        fs.insert_tree("/dir", json!({ "test.rs": "" })).await;
288
289        let project = Project::test(fs.clone(), ["/dir".as_ref()], cx).await;
290        project.update(cx, |project, _| project.languages().add(Arc::new(language)));
291
292        let _buffer = project
293            .update(cx, |project, cx| {
294                project.open_local_buffer("/dir/test.rs", cx)
295            })
296            .await
297            .unwrap();
298
299        // Set up fake language server to return fuzzy matches against
300        // a fixed set of symbol names.
301        let fake_symbols = [
302            symbol("one", "/external"),
303            symbol("ton", "/dir/test.rs"),
304            symbol("uno", "/dir/test.rs"),
305        ];
306        let fake_server = fake_servers.next().await.unwrap();
307        fake_server.handle_request::<lsp::WorkspaceSymbolRequest, _, _>(
308            move |params: lsp::WorkspaceSymbolParams, cx| {
309                let executor = cx.background_executor().clone();
310                let fake_symbols = fake_symbols.clone();
311                async move {
312                    let candidates = fake_symbols
313                        .iter()
314                        .enumerate()
315                        .map(|(id, symbol)| StringMatchCandidate::new(id, symbol.name.clone()))
316                        .collect::<Vec<_>>();
317                    let matches = if params.query.is_empty() {
318                        Vec::new()
319                    } else {
320                        fuzzy::match_strings(
321                            &candidates,
322                            &params.query,
323                            true,
324                            100,
325                            &Default::default(),
326                            executor.clone(),
327                        )
328                        .await
329                    };
330
331                    Ok(Some(lsp::WorkspaceSymbolResponse::Flat(
332                        matches
333                            .into_iter()
334                            .map(|mat| fake_symbols[mat.candidate_id].clone())
335                            .collect(),
336                    )))
337                }
338            },
339        );
340
341        let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project.clone(), cx));
342
343        // Create the project symbols view.
344        let symbols = cx.new_view(|cx| {
345            Picker::new(
346                ProjectSymbolsDelegate::new(workspace.downgrade(), project.clone()),
347                cx,
348            )
349        });
350
351        // Spawn multiples updates before the first update completes,
352        // such that in the end, there are no matches. Testing for regression:
353        // https://github.com/zed-industries/zed/issues/861
354        symbols.update(cx, |p, cx| {
355            p.update_matches("o".to_string(), cx);
356            p.update_matches("on".to_string(), cx);
357            p.update_matches("onex".to_string(), cx);
358        });
359
360        cx.run_until_parked();
361        symbols.update(cx, |symbols, _| {
362            assert_eq!(symbols.delegate.matches.len(), 0);
363        });
364
365        // Spawn more updates such that in the end, there are matches.
366        symbols.update(cx, |p, cx| {
367            p.update_matches("one".to_string(), cx);
368            p.update_matches("on".to_string(), cx);
369        });
370
371        cx.run_until_parked();
372        symbols.update(cx, |symbols, _| {
373            let delegate = &symbols.delegate;
374            assert_eq!(delegate.matches.len(), 2);
375            assert_eq!(delegate.matches[0].string, "ton");
376            assert_eq!(delegate.matches[1].string, "one");
377        });
378
379        // Spawn more updates such that in the end, there are again no matches.
380        symbols.update(cx, |p, cx| {
381            p.update_matches("o".to_string(), cx);
382            p.update_matches("".to_string(), cx);
383        });
384
385        cx.run_until_parked();
386        symbols.update(cx, |symbols, _| {
387            assert_eq!(symbols.delegate.matches.len(), 0);
388        });
389    }
390
391    fn init_test(cx: &mut TestAppContext) {
392        cx.update(|cx| {
393            let store = SettingsStore::test(cx);
394            cx.set_global(store);
395            theme::init(theme::LoadThemes::JustBase, cx);
396            language::init(cx);
397            Project::init_settings(cx);
398            workspace::init_settings(cx);
399            editor::init(cx);
400        });
401    }
402
403    fn symbol(name: &str, path: impl AsRef<Path>) -> lsp::SymbolInformation {
404        #[allow(deprecated)]
405        lsp::SymbolInformation {
406            name: name.to_string(),
407            kind: lsp::SymbolKind::FUNCTION,
408            tags: None,
409            deprecated: None,
410            container_name: None,
411            location: lsp::Location::new(
412                lsp::Url::from_file_path(path.as_ref()).unwrap(),
413                lsp::Range::new(lsp::Position::new(0, 0), lsp::Position::new(0, 0)),
414            ),
415        }
416    }
417}