outline.rs

  1use fuzzy::{StringMatch, StringMatchCandidate};
  2use gpui::{relative, AppContext, BackgroundExecutor, HighlightStyle, StyledText, TextStyle};
  3use settings::Settings;
  4use std::ops::Range;
  5use theme::{color_alpha, ActiveTheme, ThemeSettings};
  6
  7/// An outline of all the symbols contained in a buffer.
  8#[derive(Debug)]
  9pub struct Outline<T> {
 10    pub items: Vec<OutlineItem<T>>,
 11    candidates: Vec<StringMatchCandidate>,
 12    pub path_candidates: Vec<StringMatchCandidate>,
 13    path_candidate_prefixes: Vec<usize>,
 14}
 15
 16#[derive(Clone, Debug, PartialEq, Eq, Hash)]
 17pub struct OutlineItem<T> {
 18    pub depth: usize,
 19    pub range: Range<T>,
 20    pub text: String,
 21    pub highlight_ranges: Vec<(Range<usize>, HighlightStyle)>,
 22    pub name_ranges: Vec<Range<usize>>,
 23    pub body_range: Option<Range<T>>,
 24}
 25
 26impl<T> Outline<T> {
 27    pub fn new(items: Vec<OutlineItem<T>>) -> Self {
 28        let mut candidates = Vec::new();
 29        let mut path_candidates = Vec::new();
 30        let mut path_candidate_prefixes = Vec::new();
 31        let mut path_text = String::new();
 32        let mut path_stack = Vec::new();
 33
 34        for (id, item) in items.iter().enumerate() {
 35            if item.depth < path_stack.len() {
 36                path_stack.truncate(item.depth);
 37                path_text.truncate(path_stack.last().copied().unwrap_or(0));
 38            }
 39            if !path_text.is_empty() {
 40                path_text.push(' ');
 41            }
 42            path_candidate_prefixes.push(path_text.len());
 43            path_text.push_str(&item.text);
 44            path_stack.push(path_text.len());
 45
 46            let candidate_text = item
 47                .name_ranges
 48                .iter()
 49                .map(|range| &item.text[range.start..range.end])
 50                .collect::<String>();
 51
 52            path_candidates.push(StringMatchCandidate::new(id, path_text.clone()));
 53            candidates.push(StringMatchCandidate::new(id, candidate_text));
 54        }
 55
 56        Self {
 57            candidates,
 58            path_candidates,
 59            path_candidate_prefixes,
 60            items,
 61        }
 62    }
 63
 64    pub async fn search(&self, query: &str, executor: BackgroundExecutor) -> Vec<StringMatch> {
 65        let query = query.trim_start();
 66        let is_path_query = query.contains(' ');
 67        let smart_case = query.chars().any(|c| c.is_uppercase());
 68        let mut matches = fuzzy::match_strings(
 69            if is_path_query {
 70                &self.path_candidates
 71            } else {
 72                &self.candidates
 73            },
 74            query,
 75            smart_case,
 76            100,
 77            &Default::default(),
 78            executor.clone(),
 79        )
 80        .await;
 81        matches.sort_unstable_by_key(|m| m.candidate_id);
 82
 83        let mut tree_matches = Vec::new();
 84
 85        let mut prev_item_ix = 0;
 86        for mut string_match in matches {
 87            let outline_match = &self.items[string_match.candidate_id];
 88            string_match.string.clone_from(&outline_match.text);
 89
 90            if is_path_query {
 91                let prefix_len = self.path_candidate_prefixes[string_match.candidate_id];
 92                string_match
 93                    .positions
 94                    .retain(|position| *position >= prefix_len);
 95                for position in &mut string_match.positions {
 96                    *position -= prefix_len;
 97                }
 98            } else {
 99                let mut name_ranges = outline_match.name_ranges.iter();
100                let mut name_range = name_ranges.next().unwrap();
101                let mut preceding_ranges_len = 0;
102                for position in &mut string_match.positions {
103                    while *position >= preceding_ranges_len + name_range.len() {
104                        preceding_ranges_len += name_range.len();
105                        name_range = name_ranges.next().unwrap();
106                    }
107                    *position = name_range.start + (*position - preceding_ranges_len);
108                }
109            }
110
111            let insertion_ix = tree_matches.len();
112            let mut cur_depth = outline_match.depth;
113            for (ix, item) in self.items[prev_item_ix..string_match.candidate_id]
114                .iter()
115                .enumerate()
116                .rev()
117            {
118                if cur_depth == 0 {
119                    break;
120                }
121
122                let candidate_index = ix + prev_item_ix;
123                if item.depth == cur_depth - 1 {
124                    tree_matches.insert(
125                        insertion_ix,
126                        StringMatch {
127                            candidate_id: candidate_index,
128                            score: Default::default(),
129                            positions: Default::default(),
130                            string: Default::default(),
131                        },
132                    );
133                    cur_depth -= 1;
134                }
135            }
136
137            prev_item_ix = string_match.candidate_id + 1;
138            tree_matches.push(string_match);
139        }
140
141        tree_matches
142    }
143}
144
145pub fn render_item<T>(
146    outline_item: &OutlineItem<T>,
147    match_ranges: impl IntoIterator<Item = Range<usize>>,
148    cx: &AppContext,
149) -> StyledText {
150    let mut highlight_style = HighlightStyle::default();
151    highlight_style.background_color = Some(color_alpha(cx.theme().colors().text_accent, 0.3));
152    let custom_highlights = match_ranges
153        .into_iter()
154        .map(|range| (range, highlight_style));
155
156    let settings = ThemeSettings::get_global(cx);
157
158    // TODO: We probably shouldn't need to build a whole new text style here
159    // but I'm not sure how to get the current one and modify it.
160    // Before this change TextStyle::default() was used here, which was giving us the wrong font and text color.
161    let text_style = TextStyle {
162        color: cx.theme().colors().text,
163        font_family: settings.buffer_font.family.clone(),
164        font_features: settings.buffer_font.features.clone(),
165        font_size: settings.buffer_font_size(cx).into(),
166        font_weight: settings.buffer_font.weight,
167        line_height: relative(1.),
168        ..Default::default()
169    };
170    let highlights = gpui::combine_highlights(
171        custom_highlights,
172        outline_item.highlight_ranges.iter().cloned(),
173    );
174
175    StyledText::new(outline_item.text.clone()).with_highlights(&text_style, highlights)
176}