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