outline.rs

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