1use editor::{scroll::Autoscroll, Anchor, AnchorRangeExt, Editor, EditorMode};
2use fuzzy::StringMatch;
3use gpui::{
4 actions, div, rems, AppContext, DismissEvent, EventEmitter, FocusHandle, FocusableView,
5 FontStyle, FontWeight, HighlightStyle, ParentElement, Point, Render, Styled, StyledText, Task,
6 TextStyle, View, ViewContext, VisualContext, WeakView, WhiteSpace, WindowContext,
7};
8use language::Outline;
9use ordered_float::OrderedFloat;
10use picker::{Picker, PickerDelegate};
11use settings::Settings;
12use std::{
13 cmp::{self, Reverse},
14 sync::Arc,
15};
16
17use theme::{color_alpha, ActiveTheme, ThemeSettings};
18use ui::{prelude::*, ListItem, ListItemSpacing};
19use util::ResultExt;
20use workspace::{DismissDecision, ModalView};
21
22actions!(outline, [Toggle]);
23
24pub fn init(cx: &mut AppContext) {
25 cx.observe_new_views(OutlineView::register).detach();
26}
27
28pub fn toggle(editor: View<Editor>, _: &Toggle, cx: &mut WindowContext) {
29 let outline = editor
30 .read(cx)
31 .buffer()
32 .read(cx)
33 .snapshot(cx)
34 .outline(Some(&cx.theme().syntax()));
35
36 if let Some((workspace, outline)) = editor.read(cx).workspace().zip(outline) {
37 workspace.update(cx, |workspace, cx| {
38 workspace.toggle_modal(cx, |cx| OutlineView::new(outline, editor, cx));
39 })
40 }
41}
42
43pub struct OutlineView {
44 picker: View<Picker<OutlineViewDelegate>>,
45}
46
47impl FocusableView for OutlineView {
48 fn focus_handle(&self, cx: &AppContext) -> FocusHandle {
49 self.picker.focus_handle(cx)
50 }
51}
52
53impl EventEmitter<DismissEvent> for OutlineView {}
54impl ModalView for OutlineView {
55 fn on_before_dismiss(&mut self, cx: &mut ViewContext<Self>) -> DismissDecision {
56 self.picker
57 .update(cx, |picker, cx| picker.delegate.restore_active_editor(cx));
58 DismissDecision::Dismiss(true)
59 }
60}
61
62impl Render for OutlineView {
63 fn render(&mut self, _cx: &mut ViewContext<Self>) -> impl IntoElement {
64 v_flex().w(rems(34.)).child(self.picker.clone())
65 }
66}
67
68impl OutlineView {
69 fn register(editor: &mut Editor, cx: &mut ViewContext<Editor>) {
70 if editor.mode() == EditorMode::Full {
71 let handle = cx.view().downgrade();
72 editor.register_action(move |action, cx| {
73 if let Some(editor) = handle.upgrade() {
74 toggle(editor, action, cx);
75 }
76 });
77 }
78 }
79
80 fn new(
81 outline: Outline<Anchor>,
82 editor: View<Editor>,
83 cx: &mut ViewContext<Self>,
84 ) -> OutlineView {
85 let delegate = OutlineViewDelegate::new(cx.view().downgrade(), outline, editor, cx);
86 let picker = cx.new_view(|cx| Picker::uniform_list(delegate, cx).max_height(vh(0.75, cx)));
87 OutlineView { picker }
88 }
89}
90
91struct OutlineViewDelegate {
92 outline_view: WeakView<OutlineView>,
93 active_editor: View<Editor>,
94 outline: Outline<Anchor>,
95 selected_match_index: usize,
96 prev_scroll_position: Option<Point<f32>>,
97 matches: Vec<StringMatch>,
98 last_query: String,
99}
100
101impl OutlineViewDelegate {
102 fn new(
103 outline_view: WeakView<OutlineView>,
104 outline: Outline<Anchor>,
105 editor: View<Editor>,
106 cx: &mut ViewContext<OutlineView>,
107 ) -> Self {
108 Self {
109 outline_view,
110 last_query: Default::default(),
111 matches: Default::default(),
112 selected_match_index: 0,
113 prev_scroll_position: Some(editor.update(cx, |editor, cx| editor.scroll_position(cx))),
114 active_editor: editor,
115 outline,
116 }
117 }
118
119 fn restore_active_editor(&mut self, cx: &mut WindowContext) {
120 self.active_editor.update(cx, |editor, cx| {
121 editor.clear_row_highlights::<OutlineRowHighlights>();
122 if let Some(scroll_position) = self.prev_scroll_position {
123 editor.set_scroll_position(scroll_position, cx);
124 }
125 })
126 }
127
128 fn set_selected_index(
129 &mut self,
130 ix: usize,
131 navigate: bool,
132 cx: &mut ViewContext<Picker<OutlineViewDelegate>>,
133 ) {
134 self.selected_match_index = ix;
135
136 if navigate && !self.matches.is_empty() {
137 let selected_match = &self.matches[self.selected_match_index];
138 let outline_item = &self.outline.items[selected_match.candidate_id];
139
140 self.active_editor.update(cx, |active_editor, cx| {
141 active_editor.clear_row_highlights::<OutlineRowHighlights>();
142 active_editor.highlight_rows::<OutlineRowHighlights>(
143 outline_item.range.clone(),
144 Some(cx.theme().colors().editor_highlighted_line_background),
145 cx,
146 );
147 active_editor.request_autoscroll(Autoscroll::center(), cx);
148 });
149 }
150 }
151}
152
153enum OutlineRowHighlights {}
154
155impl PickerDelegate for OutlineViewDelegate {
156 type ListItem = ListItem;
157
158 fn placeholder_text(&self, _cx: &mut WindowContext) -> Arc<str> {
159 "Search buffer symbols...".into()
160 }
161
162 fn match_count(&self) -> usize {
163 self.matches.len()
164 }
165
166 fn selected_index(&self) -> usize {
167 self.selected_match_index
168 }
169
170 fn set_selected_index(&mut self, ix: usize, cx: &mut ViewContext<Picker<OutlineViewDelegate>>) {
171 self.set_selected_index(ix, true, cx);
172 }
173
174 fn update_matches(
175 &mut self,
176 query: String,
177 cx: &mut ViewContext<Picker<OutlineViewDelegate>>,
178 ) -> Task<()> {
179 let selected_index;
180 if query.is_empty() {
181 self.restore_active_editor(cx);
182 self.matches = self
183 .outline
184 .items
185 .iter()
186 .enumerate()
187 .map(|(index, _)| StringMatch {
188 candidate_id: index,
189 score: Default::default(),
190 positions: Default::default(),
191 string: Default::default(),
192 })
193 .collect();
194
195 let editor = self.active_editor.read(cx);
196 let cursor_offset = editor.selections.newest::<usize>(cx).head();
197 let buffer = editor.buffer().read(cx).snapshot(cx);
198 selected_index = self
199 .outline
200 .items
201 .iter()
202 .enumerate()
203 .map(|(ix, item)| {
204 let range = item.range.to_offset(&buffer);
205 let distance_to_closest_endpoint = cmp::min(
206 (range.start as isize - cursor_offset as isize).abs(),
207 (range.end as isize - cursor_offset as isize).abs(),
208 );
209 let depth = if range.contains(&cursor_offset) {
210 Some(item.depth)
211 } else {
212 None
213 };
214 (ix, depth, distance_to_closest_endpoint)
215 })
216 .max_by_key(|(_, depth, distance)| (*depth, Reverse(*distance)))
217 .map(|(ix, _, _)| ix)
218 .unwrap_or(0);
219 } else {
220 self.matches = smol::block_on(
221 self.outline
222 .search(&query, cx.background_executor().clone()),
223 );
224 selected_index = self
225 .matches
226 .iter()
227 .enumerate()
228 .max_by_key(|(_, m)| OrderedFloat(m.score))
229 .map(|(ix, _)| ix)
230 .unwrap_or(0);
231 }
232 self.last_query = query;
233 self.set_selected_index(selected_index, !self.last_query.is_empty(), cx);
234 Task::ready(())
235 }
236
237 fn confirm(&mut self, _: bool, cx: &mut ViewContext<Picker<OutlineViewDelegate>>) {
238 self.prev_scroll_position.take();
239
240 self.active_editor.update(cx, |active_editor, cx| {
241 if let Some(rows) = active_editor
242 .highlighted_rows::<OutlineRowHighlights>()
243 .and_then(|highlights| highlights.into_iter().next().map(|(rows, _)| rows.clone()))
244 {
245 active_editor.change_selections(Some(Autoscroll::center()), cx, |s| {
246 s.select_ranges([rows.start..rows.start])
247 });
248 active_editor.clear_row_highlights::<OutlineRowHighlights>();
249 active_editor.focus(cx);
250 }
251 });
252
253 self.dismissed(cx);
254 }
255
256 fn dismissed(&mut self, cx: &mut ViewContext<Picker<OutlineViewDelegate>>) {
257 self.outline_view
258 .update(cx, |_, cx| cx.emit(DismissEvent))
259 .log_err();
260 self.restore_active_editor(cx);
261 }
262
263 fn render_match(
264 &self,
265 ix: usize,
266 selected: bool,
267 cx: &mut ViewContext<Picker<Self>>,
268 ) -> Option<Self::ListItem> {
269 let settings = ThemeSettings::get_global(cx);
270
271 // TODO: We probably shouldn't need to build a whole new text style here
272 // but I'm not sure how to get the current one and modify it.
273 // Before this change TextStyle::default() was used here, which was giving us the wrong font and text color.
274 let text_style = TextStyle {
275 color: cx.theme().colors().text,
276 font_family: settings.buffer_font.family.clone(),
277 font_features: settings.buffer_font.features,
278 font_size: settings.buffer_font_size(cx).into(),
279 font_weight: FontWeight::NORMAL,
280 font_style: FontStyle::Normal,
281 line_height: relative(1.),
282 background_color: None,
283 underline: None,
284 strikethrough: None,
285 white_space: WhiteSpace::Normal,
286 };
287
288 let mut highlight_style = HighlightStyle::default();
289 highlight_style.background_color = Some(color_alpha(cx.theme().colors().text_accent, 0.3));
290
291 let mat = &self.matches[ix];
292 let outline_item = &self.outline.items[mat.candidate_id];
293
294 let highlights = gpui::combine_highlights(
295 mat.ranges().map(|range| (range, highlight_style)),
296 outline_item.highlight_ranges.iter().cloned(),
297 );
298
299 let styled_text =
300 StyledText::new(outline_item.text.clone()).with_highlights(&text_style, highlights);
301
302 Some(
303 ListItem::new(ix)
304 .inset(true)
305 .spacing(ListItemSpacing::Sparse)
306 .selected(selected)
307 .child(
308 div()
309 .text_ui()
310 .pl(rems(outline_item.depth as f32))
311 .child(styled_text),
312 ),
313 )
314 }
315}
316
317#[cfg(test)]
318mod tests {
319 use gpui::{TestAppContext, VisualTestContext};
320 use indoc::indoc;
321 use language::{Language, LanguageConfig, LanguageMatcher};
322 use project::{FakeFs, Project};
323 use serde_json::json;
324 use workspace::{AppState, Workspace};
325
326 use super::*;
327
328 #[gpui::test]
329 async fn test_outline_view_row_highlights(cx: &mut TestAppContext) {
330 init_test(cx);
331 let fs = FakeFs::new(cx.executor());
332 fs.insert_tree(
333 "/dir",
334 json!({
335 "a.rs": indoc!{"
336 struct SingleLine; // display line 0
337 // display line 1
338 struct MultiLine { // display line 2
339 field_1: i32, // display line 3
340 field_2: i32, // display line 4
341 } // display line 5
342 "}
343 }),
344 )
345 .await;
346
347 let project = Project::test(fs, ["/dir".as_ref()], cx).await;
348 project.read_with(cx, |project, _| project.languages().add(rust_lang()));
349
350 let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project.clone(), cx));
351 let worktree_id = workspace.update(cx, |workspace, cx| {
352 workspace.project().update(cx, |project, cx| {
353 project.worktrees().next().unwrap().read(cx).id()
354 })
355 });
356 let _buffer = project
357 .update(cx, |project, cx| project.open_local_buffer("/dir/a.rs", cx))
358 .await
359 .unwrap();
360 let editor = workspace
361 .update(cx, |workspace, cx| {
362 workspace.open_path((worktree_id, "a.rs"), None, true, cx)
363 })
364 .await
365 .unwrap()
366 .downcast::<Editor>()
367 .unwrap();
368 let ensure_outline_view_contents =
369 |outline_view: &View<Picker<OutlineViewDelegate>>, cx: &mut VisualTestContext| {
370 assert_eq!(query(&outline_view, cx), "");
371 assert_eq!(
372 outline_names(&outline_view, cx),
373 vec![
374 "struct SingleLine",
375 "struct MultiLine",
376 "field_1",
377 "field_2"
378 ],
379 );
380 };
381
382 let outline_view = open_outline_view(&workspace, cx);
383 ensure_outline_view_contents(&outline_view, cx);
384 assert_eq!(
385 highlighted_display_rows(&editor, cx),
386 Vec::<u32>::new(),
387 "Initially opened outline view should have no highlights"
388 );
389 assert_single_caret_at_row(&editor, 0, cx);
390
391 cx.dispatch_action(menu::SelectNext);
392 ensure_outline_view_contents(&outline_view, cx);
393 assert_eq!(
394 highlighted_display_rows(&editor, cx),
395 vec![2, 3, 4, 5],
396 "Second struct's rows should be highlighted"
397 );
398 assert_single_caret_at_row(&editor, 0, cx);
399
400 cx.dispatch_action(menu::SelectPrev);
401 ensure_outline_view_contents(&outline_view, cx);
402 assert_eq!(
403 highlighted_display_rows(&editor, cx),
404 vec![0],
405 "First struct's row should be highlighted"
406 );
407 assert_single_caret_at_row(&editor, 0, cx);
408
409 cx.dispatch_action(menu::Cancel);
410 ensure_outline_view_contents(&outline_view, cx);
411 assert_eq!(
412 highlighted_display_rows(&editor, cx),
413 Vec::<u32>::new(),
414 "No rows should be highlighted after outline view is cancelled and closed"
415 );
416 assert_single_caret_at_row(&editor, 0, cx);
417
418 let outline_view = open_outline_view(&workspace, cx);
419 ensure_outline_view_contents(&outline_view, cx);
420 assert_eq!(
421 highlighted_display_rows(&editor, cx),
422 Vec::<u32>::new(),
423 "Reopened outline view should have no highlights"
424 );
425 assert_single_caret_at_row(&editor, 0, cx);
426
427 let expected_first_highlighted_row = 2;
428 cx.dispatch_action(menu::SelectNext);
429 ensure_outline_view_contents(&outline_view, cx);
430 assert_eq!(
431 highlighted_display_rows(&editor, cx),
432 vec![expected_first_highlighted_row, 3, 4, 5]
433 );
434 assert_single_caret_at_row(&editor, 0, cx);
435 cx.dispatch_action(menu::Confirm);
436 ensure_outline_view_contents(&outline_view, cx);
437 assert_eq!(
438 highlighted_display_rows(&editor, cx),
439 Vec::<u32>::new(),
440 "No rows should be highlighted after outline view is confirmed and closed"
441 );
442 // On confirm, should place the caret on the first row of the highlighted rows range.
443 assert_single_caret_at_row(&editor, expected_first_highlighted_row, cx);
444 }
445
446 fn open_outline_view(
447 workspace: &View<Workspace>,
448 cx: &mut VisualTestContext,
449 ) -> View<Picker<OutlineViewDelegate>> {
450 cx.dispatch_action(Toggle);
451 workspace.update(cx, |workspace, cx| {
452 workspace
453 .active_modal::<OutlineView>(cx)
454 .unwrap()
455 .read(cx)
456 .picker
457 .clone()
458 })
459 }
460
461 fn query(
462 outline_view: &View<Picker<OutlineViewDelegate>>,
463 cx: &mut VisualTestContext,
464 ) -> String {
465 outline_view.update(cx, |outline_view, cx| outline_view.query(cx))
466 }
467
468 fn outline_names(
469 outline_view: &View<Picker<OutlineViewDelegate>>,
470 cx: &mut VisualTestContext,
471 ) -> Vec<String> {
472 outline_view.update(cx, |outline_view, _| {
473 let items = &outline_view.delegate.outline.items;
474 outline_view
475 .delegate
476 .matches
477 .iter()
478 .map(|hit| items[hit.candidate_id].text.clone())
479 .collect::<Vec<_>>()
480 })
481 }
482
483 fn highlighted_display_rows(editor: &View<Editor>, cx: &mut VisualTestContext) -> Vec<u32> {
484 editor.update(cx, |editor, cx| {
485 editor.highlighted_display_rows(cx).into_keys().collect()
486 })
487 }
488
489 fn init_test(cx: &mut TestAppContext) -> Arc<AppState> {
490 cx.update(|cx| {
491 let state = AppState::test(cx);
492 language::init(cx);
493 crate::init(cx);
494 editor::init(cx);
495 workspace::init_settings(cx);
496 Project::init_settings(cx);
497 state
498 })
499 }
500
501 fn rust_lang() -> Arc<Language> {
502 Arc::new(
503 Language::new(
504 LanguageConfig {
505 name: "Rust".into(),
506 matcher: LanguageMatcher {
507 path_suffixes: vec!["rs".to_string()],
508 ..Default::default()
509 },
510 ..Default::default()
511 },
512 Some(tree_sitter_rust::language()),
513 )
514 .with_outline_query(
515 r#"(struct_item
516 (visibility_modifier)? @context
517 "struct" @context
518 name: (_) @name) @item
519
520 (enum_item
521 (visibility_modifier)? @context
522 "enum" @context
523 name: (_) @name) @item
524
525 (enum_variant
526 (visibility_modifier)? @context
527 name: (_) @name) @item
528
529 (impl_item
530 "impl" @context
531 trait: (_)? @name
532 "for"? @context
533 type: (_) @name) @item
534
535 (trait_item
536 (visibility_modifier)? @context
537 "trait" @context
538 name: (_) @name) @item
539
540 (function_item
541 (visibility_modifier)? @context
542 (function_modifiers)? @context
543 "fn" @context
544 name: (_) @name) @item
545
546 (function_signature_item
547 (visibility_modifier)? @context
548 (function_modifiers)? @context
549 "fn" @context
550 name: (_) @name) @item
551
552 (macro_definition
553 . "macro_rules!" @context
554 name: (_) @name) @item
555
556 (mod_item
557 (visibility_modifier)? @context
558 "mod" @context
559 name: (_) @name) @item
560
561 (type_item
562 (visibility_modifier)? @context
563 "type" @context
564 name: (_) @name) @item
565
566 (associated_type
567 "type" @context
568 name: (_) @name) @item
569
570 (const_item
571 (visibility_modifier)? @context
572 "const" @context
573 name: (_) @name) @item
574
575 (field_declaration
576 (visibility_modifier)? @context
577 name: (_) @name) @item
578"#,
579 )
580 .unwrap(),
581 )
582 }
583
584 #[track_caller]
585 fn assert_single_caret_at_row(
586 editor: &View<Editor>,
587 buffer_row: u32,
588 cx: &mut VisualTestContext,
589 ) {
590 let selections = editor.update(cx, |editor, cx| {
591 editor
592 .selections
593 .all::<rope::Point>(cx)
594 .into_iter()
595 .map(|s| s.start..s.end)
596 .collect::<Vec<_>>()
597 });
598 assert!(
599 selections.len() == 1,
600 "Expected one caret selection but got: {selections:?}"
601 );
602 let selection = &selections[0];
603 assert!(
604 selection.start == selection.end,
605 "Expected a single caret selection, but got: {selection:?}"
606 );
607 assert_eq!(selection.start.row, buffer_row);
608 }
609}