outline.rs

  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::{MultiBufferOffset, 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};
 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 Some(workspace) = editor.read(cx).workspace() else {
 45        return;
 46    };
 47    if workspace.read(cx).active_modal::<OutlineView>(cx).is_some() {
 48        workspace.update(cx, |workspace, cx| {
 49            workspace.toggle_modal(window, cx, |window, cx| {
 50                OutlineView::new(Outline::new(Vec::new()), editor.clone(), window, cx)
 51            });
 52        });
 53        return;
 54    }
 55
 56    let Some(task) = outline_for_editor(&editor, cx) else {
 57        return;
 58    };
 59    let editor = editor.clone();
 60    window
 61        .spawn(cx, async move |cx| {
 62            let items = task.await;
 63            if items.is_empty() {
 64                return;
 65            }
 66            cx.update(|window, cx| {
 67                let outline = Outline::new(items);
 68                workspace.update(cx, |workspace, cx| {
 69                    workspace.toggle_modal(window, cx, |window, cx| {
 70                        OutlineView::new(outline, editor, window, cx)
 71                    });
 72                });
 73            })
 74            .ok();
 75        })
 76        .detach();
 77}
 78
 79fn outline_for_editor(
 80    editor: &Entity<Editor>,
 81    cx: &mut App,
 82) -> Option<Task<Vec<OutlineItem<Anchor>>>> {
 83    let multibuffer = editor.read(cx).buffer().read(cx).snapshot(cx);
 84    let (excerpt_id, _, buffer_snapshot) = multibuffer.as_singleton()?;
 85    let excerpt_id = *excerpt_id;
 86    let buffer_id = buffer_snapshot.remote_id();
 87    let task = editor.update(cx, |editor, cx| editor.buffer_outline_items(buffer_id, cx));
 88
 89    Some(cx.background_executor().spawn(async move {
 90        task.await
 91            .into_iter()
 92            .map(|item| OutlineItem {
 93                depth: item.depth,
 94                range: Anchor::range_in_buffer(excerpt_id, item.range),
 95                source_range_for_text: Anchor::range_in_buffer(
 96                    excerpt_id,
 97                    item.source_range_for_text,
 98                ),
 99                text: item.text,
100                highlight_ranges: item.highlight_ranges,
101                name_ranges: item.name_ranges,
102                body_range: item
103                    .body_range
104                    .map(|r| Anchor::range_in_buffer(excerpt_id, r)),
105                annotation_range: item
106                    .annotation_range
107                    .map(|r| Anchor::range_in_buffer(excerpt_id, r)),
108            })
109            .collect()
110    }))
111}
112
113pub struct OutlineView {
114    picker: Entity<Picker<OutlineViewDelegate>>,
115}
116
117impl Focusable for OutlineView {
118    fn focus_handle(&self, cx: &App) -> FocusHandle {
119        self.picker.focus_handle(cx)
120    }
121}
122
123impl EventEmitter<DismissEvent> for OutlineView {}
124impl ModalView for OutlineView {
125    fn on_before_dismiss(
126        &mut self,
127        window: &mut Window,
128        cx: &mut Context<Self>,
129    ) -> DismissDecision {
130        self.picker.update(cx, |picker, cx| {
131            picker.delegate.restore_active_editor(window, cx)
132        });
133        DismissDecision::Dismiss(true)
134    }
135}
136
137impl Render for OutlineView {
138    fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
139        v_flex()
140            .w(rems(34.))
141            .on_action(cx.listener(
142                |_this: &mut OutlineView,
143                 _: &zed_actions::outline::ToggleOutline,
144                 _window: &mut Window,
145                 cx: &mut Context<OutlineView>| {
146                    // When outline::Toggle is triggered while the outline is open, dismiss it
147                    cx.emit(DismissEvent);
148                },
149            ))
150            .child(self.picker.clone())
151    }
152}
153
154impl OutlineView {
155    fn register(editor: &mut Editor, _: Option<&mut Window>, cx: &mut Context<Editor>) {
156        if editor.mode().is_full() {
157            let handle = cx.entity().downgrade();
158            editor
159                .register_action(move |action, window, cx| {
160                    if let Some(editor) = handle.upgrade() {
161                        toggle(editor, action, window, cx);
162                    }
163                })
164                .detach();
165        }
166    }
167
168    fn new(
169        outline: Outline<Anchor>,
170        editor: Entity<Editor>,
171        window: &mut Window,
172        cx: &mut Context<Self>,
173    ) -> OutlineView {
174        let delegate = OutlineViewDelegate::new(cx.entity().downgrade(), outline, editor, cx);
175        let picker = cx.new(|cx| {
176            Picker::uniform_list(delegate, window, cx)
177                .max_height(Some(vh(0.75, window)))
178                .show_scrollbar(true)
179        });
180        OutlineView { picker }
181    }
182}
183
184struct OutlineViewDelegate {
185    outline_view: WeakEntity<OutlineView>,
186    active_editor: Entity<Editor>,
187    outline: Outline<Anchor>,
188    selected_match_index: usize,
189    prev_scroll_position: Option<Point<ScrollOffset>>,
190    matches: Vec<StringMatch>,
191    last_query: String,
192}
193
194enum OutlineRowHighlights {}
195
196impl OutlineViewDelegate {
197    fn new(
198        outline_view: WeakEntity<OutlineView>,
199        outline: Outline<Anchor>,
200        editor: Entity<Editor>,
201
202        cx: &mut Context<OutlineView>,
203    ) -> Self {
204        Self {
205            outline_view,
206            last_query: Default::default(),
207            matches: Default::default(),
208            selected_match_index: 0,
209            prev_scroll_position: Some(editor.update(cx, |editor, cx| editor.scroll_position(cx))),
210            active_editor: editor,
211            outline,
212        }
213    }
214
215    fn restore_active_editor(&mut self, window: &mut Window, cx: &mut App) {
216        self.active_editor.update(cx, |editor, cx| {
217            editor.clear_row_highlights::<OutlineRowHighlights>();
218            if let Some(scroll_position) = self.prev_scroll_position {
219                editor.set_scroll_position(scroll_position, window, cx);
220            }
221        })
222    }
223
224    fn set_selected_index(
225        &mut self,
226        ix: usize,
227        navigate: bool,
228
229        cx: &mut Context<Picker<OutlineViewDelegate>>,
230    ) {
231        self.selected_match_index = ix;
232
233        if navigate && !self.matches.is_empty() {
234            let selected_match = &self.matches[self.selected_match_index];
235            let outline_item = &self.outline.items[selected_match.candidate_id];
236
237            self.active_editor.update(cx, |active_editor, cx| {
238                active_editor.clear_row_highlights::<OutlineRowHighlights>();
239                active_editor.highlight_rows::<OutlineRowHighlights>(
240                    outline_item.range.start..outline_item.range.end,
241                    cx.theme().colors().editor_highlighted_line_background,
242                    RowHighlightOptions {
243                        autoscroll: true,
244                        ..Default::default()
245                    },
246                    cx,
247                );
248                active_editor.request_autoscroll(Autoscroll::center(), cx);
249            });
250        }
251    }
252}
253
254impl PickerDelegate for OutlineViewDelegate {
255    type ListItem = ListItem;
256
257    fn placeholder_text(&self, _window: &mut Window, _cx: &mut App) -> Arc<str> {
258        "Search buffer symbols...".into()
259    }
260
261    fn match_count(&self) -> usize {
262        self.matches.len()
263    }
264
265    fn selected_index(&self) -> usize {
266        self.selected_match_index
267    }
268
269    fn set_selected_index(
270        &mut self,
271        ix: usize,
272        _: &mut Window,
273        cx: &mut Context<Picker<OutlineViewDelegate>>,
274    ) {
275        self.set_selected_index(ix, true, cx);
276    }
277
278    fn update_matches(
279        &mut self,
280        query: String,
281        window: &mut Window,
282        cx: &mut Context<Picker<OutlineViewDelegate>>,
283    ) -> Task<()> {
284        let selected_index;
285        if query.is_empty() {
286            self.restore_active_editor(window, cx);
287            self.matches = self
288                .outline
289                .items
290                .iter()
291                .enumerate()
292                .map(|(index, _)| StringMatch {
293                    candidate_id: index,
294                    score: Default::default(),
295                    positions: Default::default(),
296                    string: Default::default(),
297                })
298                .collect();
299
300            let (buffer, cursor_offset) = self.active_editor.update(cx, |editor, cx| {
301                let buffer = editor.buffer().read(cx).snapshot(cx);
302                let cursor_offset = editor
303                    .selections
304                    .newest::<MultiBufferOffset>(&editor.display_snapshot(cx))
305                    .head();
306                (buffer, cursor_offset)
307            });
308            selected_index = self
309                .outline
310                .items
311                .iter()
312                .enumerate()
313                .map(|(ix, item)| {
314                    let range = item.range.to_offset(&buffer);
315                    let distance_to_closest_endpoint = cmp::min(
316                        (range.start.0 as isize - cursor_offset.0 as isize).abs(),
317                        (range.end.0 as isize - cursor_offset.0 as isize).abs(),
318                    );
319                    let depth = if range.contains(&cursor_offset) {
320                        Some(item.depth)
321                    } else {
322                        None
323                    };
324                    (ix, depth, distance_to_closest_endpoint)
325                })
326                .max_by_key(|(_, depth, distance)| (*depth, Reverse(*distance)))
327                .map(|(ix, _, _)| ix)
328                .unwrap_or(0);
329        } else {
330            self.matches = smol::block_on(
331                self.outline
332                    .search(&query, cx.background_executor().clone()),
333            );
334            selected_index = self
335                .matches
336                .iter()
337                .enumerate()
338                .max_by_key(|(_, m)| OrderedFloat(m.score))
339                .map(|(ix, _)| ix)
340                .unwrap_or(0);
341        }
342        self.last_query = query;
343        self.set_selected_index(selected_index, !self.last_query.is_empty(), cx);
344        Task::ready(())
345    }
346
347    fn confirm(
348        &mut self,
349        _: bool,
350        window: &mut Window,
351        cx: &mut Context<Picker<OutlineViewDelegate>>,
352    ) {
353        self.prev_scroll_position.take();
354        self.set_selected_index(self.selected_match_index, true, cx);
355
356        self.active_editor.update(cx, |active_editor, cx| {
357            let highlight = active_editor
358                .highlighted_rows::<OutlineRowHighlights>()
359                .next();
360            if let Some((rows, _)) = highlight {
361                active_editor.change_selections(
362                    SelectionEffects::scroll(Autoscroll::center()),
363                    window,
364                    cx,
365                    |s| s.select_ranges([rows.start..rows.start]),
366                );
367                active_editor.clear_row_highlights::<OutlineRowHighlights>();
368                window.focus(&active_editor.focus_handle(cx), cx);
369            }
370        });
371
372        self.dismissed(window, cx);
373    }
374
375    fn dismissed(&mut self, window: &mut Window, cx: &mut Context<Picker<OutlineViewDelegate>>) {
376        self.outline_view
377            .update(cx, |_, cx| cx.emit(DismissEvent))
378            .log_err();
379        self.restore_active_editor(window, cx);
380    }
381
382    fn render_match(
383        &self,
384        ix: usize,
385        selected: bool,
386        _: &mut Window,
387        cx: &mut Context<Picker<Self>>,
388    ) -> Option<Self::ListItem> {
389        let mat = self.matches.get(ix)?;
390        let outline_item = self.outline.items.get(mat.candidate_id)?;
391
392        Some(
393            ListItem::new(ix)
394                .inset(true)
395                .spacing(ListItemSpacing::Sparse)
396                .toggle_state(selected)
397                .child(
398                    div()
399                        .text_ui(cx)
400                        .pl(rems(outline_item.depth as f32))
401                        .child(render_item(outline_item, mat.ranges(), cx)),
402                ),
403        )
404    }
405}
406
407pub fn render_item<T>(
408    outline_item: &OutlineItem<T>,
409    match_ranges: impl IntoIterator<Item = Range<usize>>,
410    cx: &App,
411) -> StyledText {
412    let highlight_style = HighlightStyle {
413        background_color: Some(cx.theme().colors().text_accent.alpha(0.3)),
414        ..Default::default()
415    };
416    let custom_highlights = match_ranges
417        .into_iter()
418        .map(|range| (range, highlight_style));
419
420    let settings = ThemeSettings::get_global(cx);
421
422    // TODO: We probably shouldn't need to build a whole new text style here
423    // but I'm not sure how to get the current one and modify it.
424    // Before this change TextStyle::default() was used here, which was giving us the wrong font and text color.
425    let text_style = TextStyle {
426        color: cx.theme().colors().text,
427        font_family: settings.buffer_font.family.clone(),
428        font_features: settings.buffer_font.features.clone(),
429        font_fallbacks: settings.buffer_font.fallbacks.clone(),
430        font_size: settings.buffer_font_size(cx).into(),
431        font_weight: settings.buffer_font.weight,
432        line_height: relative(1.),
433        ..Default::default()
434    };
435    let highlights = gpui::combine_highlights(
436        custom_highlights,
437        outline_item.highlight_ranges.iter().cloned(),
438    );
439
440    StyledText::new(outline_item.text.clone()).with_default_highlights(&text_style, highlights)
441}
442
443#[cfg(test)]
444mod tests {
445    use std::time::Duration;
446
447    use super::*;
448    use gpui::{TestAppContext, UpdateGlobal, VisualTestContext};
449    use indoc::indoc;
450    use language::FakeLspAdapter;
451    use project::{FakeFs, Project};
452    use serde_json::json;
453    use settings::SettingsStore;
454    use smol::stream::StreamExt as _;
455    use util::{path, rel_path::rel_path};
456    use workspace::{AppState, MultiWorkspace, Workspace};
457
458    #[gpui::test]
459    async fn test_outline_view_row_highlights(cx: &mut TestAppContext) {
460        init_test(cx);
461        let fs = FakeFs::new(cx.executor());
462        fs.insert_tree(
463            path!("/dir"),
464            json!({
465                "a.rs": indoc!{"
466                                       // display line 0
467                    struct SingleLine; // display line 1
468                                       // display line 2
469                    struct MultiLine { // display line 3
470                        field_1: i32,  // display line 4
471                        field_2: i32,  // display line 5
472                    }                  // display line 6
473                "}
474            }),
475        )
476        .await;
477
478        let project = Project::test(fs, [path!("/dir").as_ref()], cx).await;
479        project.read_with(cx, |project, _| {
480            project.languages().add(language::rust_lang())
481        });
482
483        let (workspace, cx) =
484            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
485
486        let workspace = cx.read(|cx| workspace.read(cx).workspace().clone());
487        let worktree_id = workspace.update(cx, |workspace, cx| {
488            workspace.project().update(cx, |project, cx| {
489                project.worktrees(cx).next().unwrap().read(cx).id()
490            })
491        });
492        let _buffer = project
493            .update(cx, |project, cx| {
494                project.open_local_buffer(path!("/dir/a.rs"), cx)
495            })
496            .await
497            .unwrap();
498        let editor = workspace
499            .update_in(cx, |workspace, window, cx| {
500                workspace.open_path((worktree_id, rel_path("a.rs")), None, true, window, cx)
501            })
502            .await
503            .unwrap()
504            .downcast::<Editor>()
505            .unwrap();
506        let ensure_outline_view_contents =
507            |outline_view: &Entity<Picker<OutlineViewDelegate>>, cx: &mut VisualTestContext| {
508                assert_eq!(query(outline_view, cx), "");
509                assert_eq!(
510                    outline_names(outline_view, cx),
511                    vec![
512                        "struct SingleLine",
513                        "struct MultiLine",
514                        "field_1",
515                        "field_2"
516                    ],
517                );
518            };
519
520        let outline_view = open_outline_view(&workspace, cx);
521        ensure_outline_view_contents(&outline_view, cx);
522        assert_eq!(
523            highlighted_display_rows(&editor, cx),
524            Vec::<u32>::new(),
525            "Initially opened outline view should have no highlights"
526        );
527        assert_single_caret_at_row(&editor, 0, cx);
528
529        cx.dispatch_action(menu::Confirm);
530        // Ensures that outline still goes to entry even if no queries have been made
531        assert_single_caret_at_row(&editor, 1, cx);
532
533        let outline_view = open_outline_view(&workspace, cx);
534
535        cx.dispatch_action(menu::SelectNext);
536        ensure_outline_view_contents(&outline_view, cx);
537        assert_eq!(
538            highlighted_display_rows(&editor, cx),
539            vec![3, 4, 5, 6],
540            "Second struct's rows should be highlighted"
541        );
542        assert_single_caret_at_row(&editor, 1, cx);
543
544        cx.dispatch_action(menu::SelectPrevious);
545        ensure_outline_view_contents(&outline_view, cx);
546        assert_eq!(
547            highlighted_display_rows(&editor, cx),
548            vec![1],
549            "First struct's row should be highlighted"
550        );
551        assert_single_caret_at_row(&editor, 1, cx);
552
553        cx.dispatch_action(menu::Cancel);
554        ensure_outline_view_contents(&outline_view, cx);
555        assert_eq!(
556            highlighted_display_rows(&editor, cx),
557            Vec::<u32>::new(),
558            "No rows should be highlighted after outline view is cancelled and closed"
559        );
560        assert_single_caret_at_row(&editor, 1, cx);
561
562        let outline_view = open_outline_view(&workspace, cx);
563        ensure_outline_view_contents(&outline_view, cx);
564        assert_eq!(
565            highlighted_display_rows(&editor, cx),
566            Vec::<u32>::new(),
567            "Reopened outline view should have no highlights"
568        );
569        assert_single_caret_at_row(&editor, 1, cx);
570
571        let expected_first_highlighted_row = 3;
572        cx.dispatch_action(menu::SelectNext);
573        ensure_outline_view_contents(&outline_view, cx);
574        assert_eq!(
575            highlighted_display_rows(&editor, cx),
576            vec![expected_first_highlighted_row, 4, 5, 6]
577        );
578        assert_single_caret_at_row(&editor, 1, cx);
579        cx.dispatch_action(menu::Confirm);
580        ensure_outline_view_contents(&outline_view, cx);
581        assert_eq!(
582            highlighted_display_rows(&editor, cx),
583            Vec::<u32>::new(),
584            "No rows should be highlighted after outline view is confirmed and closed"
585        );
586        // On confirm, should place the caret on the first row of the highlighted rows range.
587        assert_single_caret_at_row(&editor, expected_first_highlighted_row, cx);
588    }
589
590    fn open_outline_view(
591        workspace: &Entity<Workspace>,
592        cx: &mut VisualTestContext,
593    ) -> Entity<Picker<OutlineViewDelegate>> {
594        cx.dispatch_action(zed_actions::outline::ToggleOutline);
595        cx.executor().advance_clock(Duration::from_millis(200));
596        workspace.update(cx, |workspace, cx| {
597            workspace
598                .active_modal::<OutlineView>(cx)
599                .unwrap()
600                .read(cx)
601                .picker
602                .clone()
603        })
604    }
605
606    fn query(
607        outline_view: &Entity<Picker<OutlineViewDelegate>>,
608        cx: &mut VisualTestContext,
609    ) -> String {
610        outline_view.update(cx, |outline_view, cx| outline_view.query(cx))
611    }
612
613    fn outline_names(
614        outline_view: &Entity<Picker<OutlineViewDelegate>>,
615        cx: &mut VisualTestContext,
616    ) -> Vec<String> {
617        outline_view.read_with(cx, |outline_view, _| {
618            let items = &outline_view.delegate.outline.items;
619            outline_view
620                .delegate
621                .matches
622                .iter()
623                .map(|hit| items[hit.candidate_id].text.clone())
624                .collect::<Vec<_>>()
625        })
626    }
627
628    fn highlighted_display_rows(editor: &Entity<Editor>, cx: &mut VisualTestContext) -> Vec<u32> {
629        editor.update_in(cx, |editor, window, cx| {
630            editor
631                .highlighted_display_rows(window, cx)
632                .into_keys()
633                .map(|r| r.0)
634                .collect()
635        })
636    }
637
638    fn init_test(cx: &mut TestAppContext) -> Arc<AppState> {
639        cx.update(|cx| {
640            let state = AppState::test(cx);
641            crate::init(cx);
642            editor::init(cx);
643            state
644        })
645    }
646
647    #[gpui::test]
648    async fn test_outline_modal_lsp_document_symbols(cx: &mut TestAppContext) {
649        init_test(cx);
650
651        let fs = FakeFs::new(cx.executor());
652        fs.insert_tree(
653            path!("/dir"),
654            json!({
655                "a.rs": indoc!{"
656                    struct Foo {
657                        bar: u32,
658                        baz: String,
659                    }
660                "}
661            }),
662        )
663        .await;
664
665        let project = Project::test(fs, [path!("/dir").as_ref()], cx).await;
666        let language_registry = project.read_with(cx, |project, _| {
667            project.languages().add(language::rust_lang());
668            project.languages().clone()
669        });
670
671        let mut fake_language_servers = language_registry.register_fake_lsp(
672            "Rust",
673            FakeLspAdapter {
674                capabilities: lsp::ServerCapabilities {
675                    document_symbol_provider: Some(lsp::OneOf::Left(true)),
676                    ..lsp::ServerCapabilities::default()
677                },
678                initializer: Some(Box::new(|fake_language_server| {
679                    #[allow(deprecated)]
680                    fake_language_server
681                        .set_request_handler::<lsp::request::DocumentSymbolRequest, _, _>(
682                            move |_, _| async move {
683                                Ok(Some(lsp::DocumentSymbolResponse::Nested(vec![
684                                    lsp::DocumentSymbol {
685                                        name: "Foo".to_string(),
686                                        detail: None,
687                                        kind: lsp::SymbolKind::STRUCT,
688                                        tags: None,
689                                        deprecated: None,
690                                        range: lsp::Range::new(
691                                            lsp::Position::new(0, 0),
692                                            lsp::Position::new(3, 1),
693                                        ),
694                                        selection_range: lsp::Range::new(
695                                            lsp::Position::new(0, 7),
696                                            lsp::Position::new(0, 10),
697                                        ),
698                                        children: Some(vec![
699                                            lsp::DocumentSymbol {
700                                                name: "bar".to_string(),
701                                                detail: None,
702                                                kind: lsp::SymbolKind::FIELD,
703                                                tags: None,
704                                                deprecated: None,
705                                                range: lsp::Range::new(
706                                                    lsp::Position::new(1, 4),
707                                                    lsp::Position::new(1, 13),
708                                                ),
709                                                selection_range: lsp::Range::new(
710                                                    lsp::Position::new(1, 4),
711                                                    lsp::Position::new(1, 7),
712                                                ),
713                                                children: None,
714                                            },
715                                            lsp::DocumentSymbol {
716                                                name: "lsp_only_field".to_string(),
717                                                detail: None,
718                                                kind: lsp::SymbolKind::FIELD,
719                                                tags: None,
720                                                deprecated: None,
721                                                range: lsp::Range::new(
722                                                    lsp::Position::new(2, 4),
723                                                    lsp::Position::new(2, 15),
724                                                ),
725                                                selection_range: lsp::Range::new(
726                                                    lsp::Position::new(2, 4),
727                                                    lsp::Position::new(2, 7),
728                                                ),
729                                                children: None,
730                                            },
731                                        ]),
732                                    },
733                                ])))
734                            },
735                        );
736                })),
737                ..FakeLspAdapter::default()
738            },
739        );
740
741        let (multi_workspace, cx) =
742            cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
743        let workspace = cx.read(|cx| multi_workspace.read(cx).workspace().clone());
744        let worktree_id = workspace.update(cx, |workspace, cx| {
745            workspace.project().update(cx, |project, cx| {
746                project.worktrees(cx).next().unwrap().read(cx).id()
747            })
748        });
749        let _buffer = project
750            .update(cx, |project, cx| {
751                project.open_local_buffer(path!("/dir/a.rs"), cx)
752            })
753            .await
754            .unwrap();
755        let editor = workspace
756            .update_in(cx, |workspace, window, cx| {
757                workspace.open_path((worktree_id, rel_path("a.rs")), None, true, window, cx)
758            })
759            .await
760            .unwrap()
761            .downcast::<Editor>()
762            .unwrap();
763
764        let _fake_language_server = fake_language_servers.next().await.unwrap();
765        cx.run_until_parked();
766
767        // Step 1: tree-sitter outlines by default
768        let outline_view = open_outline_view(&workspace, cx);
769        let tree_sitter_names = outline_names(&outline_view, cx);
770        assert_eq!(
771            tree_sitter_names,
772            vec!["struct Foo", "bar", "baz"],
773            "Step 1: tree-sitter outlines should be displayed by default"
774        );
775        cx.dispatch_action(menu::Cancel);
776        cx.run_until_parked();
777
778        // Step 2: Switch to LSP document symbols
779        cx.update(|_, cx| {
780            SettingsStore::update_global(cx, |store: &mut SettingsStore, cx| {
781                store.update_user_settings(cx, |settings| {
782                    settings.project.all_languages.defaults.document_symbols =
783                        Some(settings::DocumentSymbols::On);
784                });
785            });
786        });
787        let outline_view = open_outline_view(&workspace, cx);
788        let lsp_names = outline_names(&outline_view, cx);
789        assert_eq!(
790            lsp_names,
791            vec!["struct Foo", "bar", "lsp_only_field"],
792            "Step 2: LSP-provided symbols should be displayed"
793        );
794        assert_eq!(
795            highlighted_display_rows(&editor, cx),
796            Vec::<u32>::new(),
797            "Step 2: initially opened outline view should have no highlights"
798        );
799        assert_single_caret_at_row(&editor, 0, cx);
800
801        cx.dispatch_action(menu::SelectNext);
802        assert_eq!(
803            highlighted_display_rows(&editor, cx),
804            vec![1],
805            "Step 2: bar's row should be highlighted after SelectNext"
806        );
807        assert_single_caret_at_row(&editor, 0, cx);
808
809        cx.dispatch_action(menu::Confirm);
810        cx.run_until_parked();
811        assert_single_caret_at_row(&editor, 1, cx);
812
813        // Step 3: Switch back to tree-sitter
814        cx.update(|_, cx| {
815            SettingsStore::update_global(cx, |store: &mut SettingsStore, cx| {
816                store.update_user_settings(cx, |settings| {
817                    settings.project.all_languages.defaults.document_symbols =
818                        Some(settings::DocumentSymbols::Off);
819                });
820            });
821        });
822
823        let outline_view = open_outline_view(&workspace, cx);
824        let restored_names = outline_names(&outline_view, cx);
825        assert_eq!(
826            restored_names,
827            vec!["struct Foo", "bar", "baz"],
828            "Step 3: tree-sitter outlines should be restored after switching back"
829        );
830    }
831
832    #[track_caller]
833    fn assert_single_caret_at_row(
834        editor: &Entity<Editor>,
835        buffer_row: u32,
836        cx: &mut VisualTestContext,
837    ) {
838        let selections = editor.update(cx, |editor, cx| {
839            editor
840                .selections
841                .all::<rope::Point>(&editor.display_snapshot(cx))
842                .into_iter()
843                .map(|s| s.start..s.end)
844                .collect::<Vec<_>>()
845        });
846        assert!(
847            selections.len() == 1,
848            "Expected one caret selection but got: {selections:?}"
849        );
850        let selection = &selections[0];
851        assert!(
852            selection.start == selection.end,
853            "Expected a single caret selection, but got: {selection:?}"
854        );
855        assert_eq!(selection.start.row, buffer_row);
856    }
857}