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