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