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