bracket_colorization.rs

  1use crate::Editor;
  2use collections::HashMap;
  3use gpui::{Context, HighlightStyle};
  4use language::language_settings;
  5use ui::{ActiveTheme, utils::ensure_minimum_contrast};
  6
  7struct RainbowBracketHighlight;
  8
  9impl Editor {
 10    pub(crate) fn colorize_brackets(&mut self, invalidate: bool, cx: &mut Context<Editor>) {
 11        if !self.mode.is_full() {
 12            return;
 13        }
 14
 15        if invalidate {
 16            self.fetched_tree_sitter_chunks.clear();
 17        }
 18
 19        let accents_count = cx.theme().accents().0.len();
 20        let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
 21        let bracket_matches_by_accent = self.visible_excerpts(cx).into_iter().fold(
 22            HashMap::default(),
 23            |mut acc, (excerpt_id, (buffer, buffer_version, buffer_range))| {
 24                let buffer_snapshot = buffer.read(cx).snapshot();
 25                if language_settings::language_settings(
 26                    buffer_snapshot.language().map(|language| language.name()),
 27                    buffer_snapshot.file(),
 28                    cx,
 29                )
 30                .colorize_brackets
 31                {
 32                    let fetched_chunks = self
 33                        .fetched_tree_sitter_chunks
 34                        .entry(excerpt_id)
 35                        .or_default();
 36
 37                    let brackets_by_accent = buffer_snapshot
 38                        .fetch_bracket_ranges(
 39                            buffer_range.start..buffer_range.end,
 40                            Some((&buffer_version, fetched_chunks)),
 41                        )
 42                        .into_iter()
 43                        .flat_map(|(chunk_range, pairs)| {
 44                            if fetched_chunks.insert(chunk_range) {
 45                                pairs
 46                            } else {
 47                                Vec::new()
 48                            }
 49                        })
 50                        .filter_map(|pair| {
 51                            let buffer_open_range = buffer_snapshot
 52                                .anchor_before(pair.open_range.start)
 53                                ..buffer_snapshot.anchor_after(pair.open_range.end);
 54                            let multi_buffer_open_range = multi_buffer_snapshot
 55                                .anchor_in_excerpt(excerpt_id, buffer_open_range.start)?
 56                                ..multi_buffer_snapshot
 57                                    .anchor_in_excerpt(excerpt_id, buffer_open_range.end)?;
 58                            let buffer_close_range = buffer_snapshot
 59                                .anchor_before(pair.close_range.start)
 60                                ..buffer_snapshot.anchor_after(pair.close_range.end);
 61                            let multi_buffer_close_range = multi_buffer_snapshot
 62                                .anchor_in_excerpt(excerpt_id, buffer_close_range.start)?
 63                                ..multi_buffer_snapshot
 64                                    .anchor_in_excerpt(excerpt_id, buffer_close_range.end)?;
 65
 66                            pair.id.map(|id| {
 67                                let accent_number = id % accents_count;
 68
 69                                (
 70                                    accent_number,
 71                                    multi_buffer_open_range,
 72                                    multi_buffer_close_range,
 73                                )
 74                            })
 75                        });
 76
 77                    for (accent_number, open_range, close_range) in brackets_by_accent {
 78                        let ranges = acc.entry(accent_number).or_insert_with(Vec::new);
 79                        ranges.push(open_range);
 80                        ranges.push(close_range);
 81                    }
 82                }
 83
 84                acc
 85            },
 86        );
 87
 88        if invalidate {
 89            self.clear_highlights::<RainbowBracketHighlight>(cx);
 90        }
 91
 92        let editor_background = cx.theme().colors().editor_background;
 93        for (accent_number, bracket_highlights) in bracket_matches_by_accent {
 94            let bracket_color = cx.theme().accents().color_for_index(accent_number as u32);
 95            let adjusted_color = ensure_minimum_contrast(bracket_color, editor_background, 55.0);
 96            let style = HighlightStyle {
 97                color: Some(adjusted_color),
 98                ..HighlightStyle::default()
 99            };
100
101            self.highlight_text_key::<RainbowBracketHighlight>(
102                accent_number,
103                bracket_highlights,
104                style,
105                true,
106                cx,
107            );
108        }
109    }
110}
111
112#[cfg(test)]
113mod tests {
114    use std::{ops::Range, time::Duration};
115
116    use super::*;
117    use crate::{
118        editor_tests::init_test,
119        test::{
120            editor_lsp_test_context::EditorLspTestContext, editor_test_context::EditorTestContext,
121        },
122    };
123    use gpui::Hsla;
124    use indoc::indoc;
125    use language::{BracketPair, BracketPairConfig, Language, LanguageConfig, LanguageMatcher};
126    use multi_buffer::AnchorRangeExt as _;
127    use rope::Point;
128
129    #[gpui::test]
130    async fn test_rainbow_bracket_highlights(cx: &mut gpui::TestAppContext) {
131        fn collect_colored_brackets(
132            cx: &mut EditorTestContext,
133        ) -> Vec<(Option<Hsla>, Range<Point>)> {
134            cx.update_editor(|editor, window, cx| {
135                let snapshot = editor.snapshot(window, cx);
136                snapshot
137                    .all_text_highlight_ranges::<RainbowBracketHighlight>()
138                    .iter()
139                    .flat_map(|ranges| {
140                        ranges.1.iter().map(|range| {
141                            (ranges.0.color, range.to_point(&snapshot.buffer_snapshot()))
142                        })
143                    })
144                    .collect::<Vec<_>>()
145            })
146        }
147
148        init_test(cx, |language_settings| {
149            language_settings.defaults.colorize_brackets = Some(true);
150        });
151
152        let mut cx = EditorLspTestContext::new(
153            Language::new(
154                LanguageConfig {
155                    name: "Rust".into(),
156                    matcher: LanguageMatcher {
157                        path_suffixes: vec!["rs".to_string()],
158                        ..LanguageMatcher::default()
159                    },
160                    brackets: BracketPairConfig {
161                        pairs: vec![
162                            BracketPair {
163                                start: "{".to_string(),
164                                end: "}".to_string(),
165                                close: false,
166                                surround: false,
167                                newline: true,
168                            },
169                            BracketPair {
170                                start: "(".to_string(),
171                                end: ")".to_string(),
172                                close: false,
173                                surround: false,
174                                newline: true,
175                            },
176                        ],
177                        ..BracketPairConfig::default()
178                    },
179                    ..LanguageConfig::default()
180                },
181                Some(tree_sitter_rust::LANGUAGE.into()),
182            )
183            .with_brackets_query(indoc! {r#"
184                ("{" @open "}" @close)
185                ("(" @open ")" @close)
186                "#})
187            .unwrap(),
188            lsp::ServerCapabilities::default(),
189            cx,
190        )
191        .await;
192
193        let mut highlighted_brackets = HashMap::default();
194
195        // taken from r-a https://github.com/rust-lang/rust-analyzer/blob/d733c07552a2dc0ec0cc8f4df3f0ca969a93fd90/crates/ide/src/inlay_hints.rs#L81-L297
196        cx.set_state(indoc! {r#197            pub(crate) fn inlay_hints(
198                db: &RootDatabase,
199                file_id: FileId,
200                range_limit: Option<TextRange>,
201                config: &InlayHintsConfig,
202            ) -> Vec<InlayHint> {
203                let _p = tracing::info_span!("inlay_hints").entered();
204                let sema = Semantics::new(db);
205                let file_id = sema
206                    .attach_first_edition(file_id)
207                    .unwrap_or_else(|| EditionedFileId::current_edition(db, file_id));
208                let file = sema.parse(file_id);
209                let file = file.syntax();
210
211                let mut acc = Vec::new();
212
213                let Some(scope) = sema.scope(file) else {
214                    return acc;
215                };
216                let famous_defs = FamousDefs(&sema, scope.krate());
217                let display_target = famous_defs.1.to_display_target(sema.db);
218
219                let ctx = &mut InlayHintCtx::default();
220                let mut hints = |event| {
221                    if let Some(node) = handle_event(ctx, event) {
222                        hints(&mut acc, ctx, &famous_defs, config, file_id, display_target, node);
223                    }
224                };
225                let mut preorder = file.preorder();
226                salsa::attach(sema.db, || {
227                    while let Some(event) = preorder.next() {
228                        if matches!((&event, range_limit), (WalkEvent::Enter(node), Some(range)) if range.intersect(node.text_range()).is_none())
229                        {
230                            preorder.skip_subtree();
231                            continue;
232                        }
233                        hints(event);
234                    }
235                });
236                if let Some(range_limit) = range_limit {
237                    acc.retain(|hint| range_limit.contains_range(hint.range));
238                }
239                acc
240            }
241
242            #[derive(Default)]
243            struct InlayHintCtx {
244                lifetime_stacks: Vec<Vec<SmolStr>>,
245                extern_block_parent: Option<ast::ExternBlock>,
246            }
247
248            pub(crate) fn inlay_hints_resolve(
249                db: &RootDatabase,
250                file_id: FileId,
251                resolve_range: TextRange,
252                hash: u64,
253                config: &InlayHintsConfig,
254                hasher: impl Fn(&InlayHint) -> u64,
255            ) -> Option<InlayHint> {
256                let _p = tracing::info_span!("inlay_hints_resolve").entered();
257                let sema = Semantics::new(db);
258                let file_id = sema
259                    .attach_first_edition(file_id)
260                    .unwrap_or_else(|| EditionedFileId::current_edition(db, file_id));
261                let file = sema.parse(file_id);
262                let file = file.syntax();
263
264                let scope = sema.scope(file)?;
265                let famous_defs = FamousDefs(&sema, scope.krate());
266                let mut acc = Vec::new();
267
268                let display_target = famous_defs.1.to_display_target(sema.db);
269
270                let ctx = &mut InlayHintCtx::default();
271                let mut hints = |event| {
272                    if let Some(node) = handle_event(ctx, event) {
273                        hints(&mut acc, ctx, &famous_defs, config, file_id, display_target, node);
274                    }
275                };
276
277                let mut preorder = file.preorder();
278                while let Some(event) = preorder.next() {
279                    // FIXME: This can miss some hints that require the parent of the range to calculate
280                    if matches!(&event, WalkEvent::Enter(node) if resolve_range.intersect(node.text_range()).is_none())
281                    {
282                        preorder.skip_subtree();
283                        continue;
284                    }
285                    hints(event);
286                }
287                acc.into_iter().find(|hint| hasher(hint) == hash)
288            }
289
290            fn handle_event(ctx: &mut InlayHintCtx, node: WalkEvent<SyntaxNode>) -> Option<SyntaxNode> {
291                match node {
292                    WalkEvent::Enter(node) => {
293                        if let Some(node) = ast::AnyHasGenericParams::cast(node.clone()) {
294                            let params = node
295                                .generic_param_list()
296                                .map(|it| {
297                                    it.lifetime_params()
298                                        .filter_map(|it| {
299                                            it.lifetime().map(|it| format_smolstr!("{}", &it.text()[1..]))
300                                        })
301                                        .collect()
302                                })
303                                .unwrap_or_default();
304                            ctx.lifetime_stacks.push(params);
305                        }
306                        if let Some(node) = ast::ExternBlock::cast(node.clone()) {
307                            ctx.extern_block_parent = Some(node);
308                        }
309                        Some(node)
310                    }
311                    WalkEvent::Leave(n) => {
312                        if ast::AnyHasGenericParams::can_cast(n.kind()) {
313                            ctx.lifetime_stacks.pop();
314                        }
315                        if ast::ExternBlock::can_cast(n.kind()) {
316                            ctx.extern_block_parent = None;
317                        }
318                        None
319                    }
320                }
321            }
322
323            // FIXME: At some point when our hir infra is fleshed out enough we should flip this and traverse the
324            // HIR instead of the syntax tree.
325            fn hints(
326                hints: &mut Vec<InlayHint>,
327                ctx: &mut InlayHintCtx,
328                famous_defs @ FamousDefs(sema, _krate): &FamousDefs<'_, '_>,
329                config: &InlayHintsConfig,
330                file_id: EditionedFileId,
331                display_target: DisplayTarget,
332                node: SyntaxNode,
333            ) {
334                closing_brace::hints(
335                    hints,
336                    sema,
337                    config,
338                    display_target,
339                    InRealFile { file_id, value: node.clone() },
340                );
341                if let Some(any_has_generic_args) = ast::AnyHasGenericArgs::cast(node.clone()) {
342                    generic_param::hints(hints, famous_defs, config, any_has_generic_args);
343                }
344
345                match_ast! {
346                    match node {
347                        ast::Expr(expr) => {
348                            chaining::hints(hints, famous_defs, config, display_target, &expr);
349                            adjustment::hints(hints, famous_defs, config, display_target, &expr);
350                            match expr {
351                                ast::Expr::CallExpr(it) => param_name::hints(hints, famous_defs, config, file_id, ast::Expr::from(it)),
352                                ast::Expr::MethodCallExpr(it) => {
353                                    param_name::hints(hints, famous_defs, config, file_id, ast::Expr::from(it))
354                                }
355                                ast::Expr::ClosureExpr(it) => {
356                                    closure_captures::hints(hints, famous_defs, config, it.clone());
357                                    closure_ret::hints(hints, famous_defs, config, display_target, it)
358                                },
359                                ast::Expr::RangeExpr(it) => range_exclusive::hints(hints, famous_defs, config, it),
360                                _ => Some(()),
361                            }
362                        },
363                        ast::Pat(it) => {
364                            binding_mode::hints(hints, famous_defs, config, &it);
365                            match it {
366                                ast::Pat::IdentPat(it) => {
367                                    bind_pat::hints(hints, famous_defs, config, display_target, &it);
368                                }
369                                ast::Pat::RangePat(it) => {
370                                    range_exclusive::hints(hints, famous_defs, config, it);
371                                }
372                                _ => {}
373                            }
374                            Some(())
375                        },
376                        ast::Item(it) => match it {
377                            ast::Item::Fn(it) => {
378                                implicit_drop::hints(hints, famous_defs, config, display_target, &it);
379                                if let Some(extern_block) = &ctx.extern_block_parent {
380                                    extern_block::fn_hints(hints, famous_defs, config, &it, extern_block);
381                                }
382                                lifetime::fn_hints(hints, ctx, famous_defs, config,  it)
383                            },
384                            ast::Item::Static(it) => {
385                                if let Some(extern_block) = &ctx.extern_block_parent {
386                                    extern_block::static_hints(hints, famous_defs, config, &it, extern_block);
387                                }
388                                implicit_static::hints(hints, famous_defs, config,  Either::Left(it))
389                            },
390                            ast::Item::Const(it) => implicit_static::hints(hints, famous_defs, config, Either::Right(it)),
391                            ast::Item::Enum(it) => discriminant::enum_hints(hints, famous_defs, config, it),
392                            ast::Item::ExternBlock(it) => extern_block::extern_block_hints(hints, famous_defs, config, it),
393                            _ => None,
394                        },
395                        // FIXME: trait object type elisions
396                        ast::Type(ty) => match ty {
397                            ast::Type::FnPtrType(ptr) => lifetime::fn_ptr_hints(hints, ctx, famous_defs, config,  ptr),
398                            ast::Type::PathType(path) => {
399                                lifetime::fn_path_hints(hints, ctx, famous_defs, config, &path);
400                                implied_dyn_trait::hints(hints, famous_defs, config, Either::Left(path));
401                                Some(())
402                            },
403                            ast::Type::DynTraitType(dyn_) => {
404                                implied_dyn_trait::hints(hints, famous_defs, config, Either::Right(dyn_));
405                                Some(())
406                            },
407                            _ => Some(()),
408                        },
409                        ast::GenericParamList(it) => bounds::hints(hints, famous_defs, config,  it),
410                        _ => Some(()),
411                    }
412                };
413            }
414        "#});
415        cx.executor().advance_clock(Duration::from_millis(100));
416        cx.executor().run_until_parked();
417
418        let actual_ranges = collect_colored_brackets(&mut cx);
419
420        for (color, range) in actual_ranges.iter().cloned() {
421            highlighted_brackets.insert(range, color);
422        }
423
424        let last_bracket = actual_ranges
425            .iter()
426            .max_by_key(|(_, p)| p.end.row)
427            .unwrap()
428            .clone();
429
430        cx.update_editor(|editor, window, cx| {
431            let was_scrolled = editor.set_scroll_position(
432                gpui::Point::new(0.0, last_bracket.1.end.row as f64 * 2.0),
433                window,
434                cx,
435            );
436            assert!(was_scrolled.0);
437        });
438        cx.executor().advance_clock(Duration::from_millis(100));
439        cx.executor().run_until_parked();
440
441        let ranges_after_scrolling = collect_colored_brackets(&mut cx);
442        let new_last_bracket = ranges_after_scrolling
443            .iter()
444            .max_by_key(|(_, p)| p.end.row)
445            .unwrap()
446            .clone();
447
448        assert_ne!(
449            last_bracket, new_last_bracket,
450            "After scrolling down, we should have highlighted more brackets"
451        );
452
453        cx.update_editor(|editor, window, cx| {
454            let was_scrolled = editor.set_scroll_position(gpui::Point::default(), window, cx);
455            assert!(was_scrolled.0);
456        });
457
458        for _ in 0..200 {
459            cx.update_editor(|editor, window, cx| {
460                editor.apply_scroll_delta(gpui::Point::new(0.0, 0.25), window, cx);
461            });
462            cx.executor().run_until_parked();
463
464            for (color, range) in collect_colored_brackets(&mut cx) {
465                assert!(
466                    highlighted_brackets
467                        .entry(range.clone())
468                        .or_insert(color.clone())
469                        == &color,
470                    "Colors should stay consistent while scrolling!"
471                );
472            }
473        }
474
475        // todo! more tests, check no brackets missing in range, settings toggle
476    }
477}