Skip to main content

gpui_component/text/
mod.rs

1//! Compatibility facade for rich text now owned by `gpui-base`.
2
3mod compat;
4mod frontmatter;
5mod style;
6
7pub use compat::{
8    Text, TextView, TextViewLayoutState, TextViewPlugin, TextViewPrepaintState, html, markdown,
9};
10pub use frontmatter::FrontmatterPlugin;
11pub use gpui_base::text::{
12    InlineElement, InlineRenderContext, MarkdownBlockParserFn, MarkdownBlockRenderFn,
13    MarkdownExtensions, MarkdownNode, MarkdownParseContext, MarkdownPlugin, RangeHighlight,
14    RangeHighlightError, RenderedText, SelectionFormat, TableData, TextViewMotion, TextViewState,
15    markdown_ast,
16};
17pub use style::TextViewStyle;
18
19#[cfg(feature = "tree-sitter")]
20use std::{cell::RefCell, collections::HashMap};
21
22use gpui::Styled as _;
23#[cfg(feature = "tree-sitter")]
24use gpui_base::input::{InputEdit, Point, RopeExt as _};
25#[cfg(feature = "tree-sitter")]
26use ropey::Rope;
27
28#[cfg(feature = "tree-sitter")]
29use crate::highlighter::{LanguageRegistry, SyntaxHighlighter};
30
31#[cfg(test)]
32mod window_selection;
33
34/// Derives the Base rich-text style installed by the component theme adapter.
35pub(crate) fn base_text_view_style(theme: &crate::Theme) -> gpui_base::TextViewStyle {
36    let radius = theme.semantic_tokens().radius.md;
37    let mut table = gpui::StyleRefinement::default();
38    table.corner_radii.top_left = Some(radius.into());
39    table.corner_radii.top_right = Some(radius.into());
40    table.corner_radii.bottom_left = Some(radius.into());
41    table.corner_radii.bottom_right = Some(radius.into());
42    let mut code_block = gpui::StyleRefinement::default();
43    code_block.corner_radii = table.corner_radii.clone();
44    let table_head = gpui::StyleRefinement::default()
45        .bg(theme.table_head)
46        .text_color(theme.table_head_foreground);
47
48    gpui_base::TextViewStyle::default()
49        .with_foreground(theme.foreground)
50        .with_muted_foreground(theme.muted_foreground)
51        .with_link(theme.link)
52        .with_selection(theme.selection)
53        .with_code_background(theme.muted)
54        .with_border(theme.border)
55        .with_code_block(code_block)
56        .with_table(table)
57        .with_table_head(table_head)
58        .with_inline_code(gpui::HighlightStyle {
59            background_color: Some(theme.accent),
60            ..Default::default()
61        })
62        .with_dark(theme.is_dark())
63}
64
65pub(crate) fn install_text_view_defaults(theme: &crate::Theme, cx: &mut gpui::App) {
66    let defaults = gpui_base::TextViewDefaults::new().with_style(base_text_view_style(theme));
67
68    #[cfg(feature = "tree-sitter")]
69    let defaults = defaults.with_code_block_highlighter(component_code_block_highlighter(
70        theme.highlight_theme.clone(),
71    ));
72
73    defaults.install(cx);
74}
75
76#[cfg(feature = "tree-sitter")]
77pub(crate) fn component_code_block_highlighter(
78    highlight_theme: std::sync::Arc<crate::highlighter::HighlightTheme>,
79) -> impl Fn(&gpui_base::text::CodeBlock) -> Vec<(std::ops::Range<usize>, gpui::HighlightStyle)>
80+ Send
81+ Sync
82+ 'static {
83    move |block| {
84        thread_local! {
85            static HIGHLIGHTERS: RefCell<HashMap<gpui::SharedString, SyntaxHighlighter>> =
86                RefCell::new(HashMap::new());
87        }
88
89        let Some(lang) = block.lang() else {
90            return Vec::new();
91        };
92        let code = block.code();
93        HIGHLIGHTERS.with(|cache| {
94            let mut cache = cache.borrow_mut();
95            let highlighter = cache
96                .entry(lang.clone())
97                .or_insert_with(|| SyntaxHighlighter::new(lang.as_ref()));
98            if let Some(config) = LanguageRegistry::singleton().language(lang.as_ref())
99                && highlighter.language() != &config.name
100            {
101                *highlighter = SyntaxHighlighter::new(lang.as_ref());
102            }
103
104            let old_end_byte = highlighter.text().len();
105            let old_end_position = highlighter.text().offset_to_point(old_end_byte);
106            let code_rope = Rope::from_str(code.as_ref());
107            let edit = InputEdit {
108                start_byte: 0,
109                old_end_byte,
110                new_end_byte: code.len(),
111                start_position: Point::new(0, 0),
112                old_end_position,
113                new_end_position: code_rope.offset_to_point(code.len()),
114            };
115            highlighter.update_input(Some(edit), &code_rope, None);
116            highlighter.styles(&(0..code.len()), highlight_theme.as_ref())
117        })
118    }
119}
120
121/// The type [`shared_code_block_highlighter`] returns.
122#[cfg(feature = "tree-sitter")]
123pub(crate) type SharedCodeBlockHighlighter = dyn Fn(&gpui_base::text::CodeBlock) -> Vec<(std::ops::Range<usize>, gpui::HighlightStyle)>
124    + Send
125    + Sync;
126
127/// The [`component_code_block_highlighter`] for `highlight_theme`, built once
128/// and handed out again for the same theme.
129///
130/// A code block reuses its highlights only while the highlighter is the same
131/// `Arc`, and a text view with a custom theme is laid out every frame, so a
132/// fresh highlighter per frame reparsed every code block with tree-sitter on
133/// every frame. Each entry keeps its theme alive, so only the most recent few
134/// themes are kept.
135///
136/// Entries are also keyed on the [`LanguageRegistry`] generation: registering
137/// a language drops them, so the next frame gets a new highlighter and code
138/// blocks painted before the language existed are highlighted again.
139#[cfg(feature = "tree-sitter")]
140pub(crate) fn shared_code_block_highlighter(
141    highlight_theme: &std::sync::Arc<crate::highlighter::HighlightTheme>,
142) -> std::sync::Arc<SharedCodeBlockHighlighter> {
143    shared_code_block_highlighter_at(highlight_theme, LanguageRegistry::singleton().generation())
144}
145
146/// [`shared_code_block_highlighter`] at an explicit registry `generation`.
147#[cfg(feature = "tree-sitter")]
148fn shared_code_block_highlighter_at(
149    highlight_theme: &std::sync::Arc<crate::highlighter::HighlightTheme>,
150    generation: u64,
151) -> std::sync::Arc<SharedCodeBlockHighlighter> {
152    use std::sync::Arc;
153
154    use crate::highlighter::HighlightTheme;
155
156    /// The registry generation the entries were built at, and the entries.
157    type SharedHighlighters = (
158        u64,
159        Vec<(Arc<HighlightTheme>, Arc<SharedCodeBlockHighlighter>)>,
160    );
161
162    const CAPACITY: usize = 4;
163    thread_local! {
164        static SHARED: RefCell<SharedHighlighters> = const { RefCell::new((0, Vec::new())) };
165    }
166
167    SHARED.with(|cache| {
168        let (cached_generation, shared) = &mut *cache.borrow_mut();
169        if *cached_generation != generation {
170            *cached_generation = generation;
171            shared.clear();
172        }
173        if let Some((_, highlighter)) = shared
174            .iter()
175            .find(|(theme, _)| Arc::ptr_eq(theme, highlight_theme))
176        {
177            return highlighter.clone();
178        }
179
180        let highlighter: Arc<SharedCodeBlockHighlighter> =
181            Arc::new(component_code_block_highlighter(highlight_theme.clone()));
182        if shared.len() == CAPACITY {
183            shared.remove(0);
184        }
185        shared.push((highlight_theme.clone(), highlighter.clone()));
186        highlighter
187    })
188}
189
190#[cfg(test)]
191mod tests {
192    use std::sync::Arc;
193
194    use gpui::{StyleRefinement, Styled as _, px};
195
196    use crate::Theme;
197
198    /// The component highlighter is the only place that still knows about
199    /// `LanguageRegistry` and `HighlightTheme`, so these two cases follow it
200    /// here from the code block it used to live in.
201    #[cfg(feature = "tree-sitter")]
202    mod code_block_highlighter {
203        use std::ops::Range;
204
205        use gpui::{HighlightStyle, Hsla, SharedString};
206        use gpui_base::text::CodeBlock;
207
208        use crate::highlighter::{HighlightTheme, LanguageConfig, LanguageRegistry};
209
210        fn register_json(lang: &SharedString) {
211            LanguageRegistry::singleton().register(
212                lang.as_ref(),
213                &LanguageConfig::new(
214                    lang.clone(),
215                    tree_sitter_json::LANGUAGE.into(),
216                    vec![],
217                    "(number) @number",
218                    "",
219                    "",
220                ),
221            );
222        }
223
224        fn color_at(
225            styles: &[(Range<usize>, HighlightStyle)],
226            range: Range<usize>,
227        ) -> Option<Hsla> {
228            styles
229                .iter()
230                .find(|(span, _)| span.start <= range.start && span.end >= range.end)
231                .and_then(|(_, style)| style.color)
232        }
233
234        #[test]
235        fn registering_a_language_refreshes_the_cached_highlighter() {
236            let lang = SharedString::from("json-cache-test");
237            let code = SharedString::from(r#"{"value": 42}"#);
238            let number = code.find("42").unwrap()..code.find("42").unwrap() + 2;
239            let highlighter =
240                super::super::component_code_block_highlighter(HighlightTheme::default_light());
241
242            // The first call caches a plain-text highlighter for the unknown
243            // language; the cache must not outlive the registration.
244            let block = CodeBlock::from_code(code.clone(), Some(lang.clone()));
245            assert_eq!(color_at(&highlighter(&block), number.clone()), None);
246
247            register_json(&lang);
248
249            let block = CodeBlock::from_code(code, Some(lang));
250            assert!(
251                color_at(&highlighter(&block), number).is_some(),
252                "a newly registered language must reach the cached highlighter"
253            );
254        }
255
256        #[test]
257        fn styles_follow_the_highlight_theme_they_were_built_with() {
258            let lang = SharedString::from("json-theme-test");
259            register_json(&lang);
260            let code = SharedString::from(r#"{"value": 42}"#);
261            let number = code.find("42").unwrap()..code.find("42").unwrap() + 2;
262
263            let light = HighlightTheme::default_light();
264            let dark = HighlightTheme::default_dark();
265            let light_number = light.style("number").and_then(|style| style.color);
266            let dark_number = dark.style("number").and_then(|style| style.color);
267            assert_ne!(
268                light_number, dark_number,
269                "the default themes must use different number colors"
270            );
271
272            let block = CodeBlock::from_code(code, Some(lang));
273            let light_styles = super::super::component_code_block_highlighter(light)(&block);
274            let dark_styles = super::super::component_code_block_highlighter(dark)(&block);
275
276            assert_eq!(color_at(&light_styles, number.clone()), light_number);
277            assert_eq!(
278                color_at(&dark_styles, number),
279                dark_number,
280                "a theme change must not reuse syntax styles from the previous theme"
281            );
282        }
283
284        #[test]
285        fn shared_highlighter_is_reused_for_the_same_theme() {
286            // An explicit generation, so registrations by tests running in
287            // parallel cannot drop the entries between calls.
288            const GENERATION: u64 = u64::MAX;
289            let light = HighlightTheme::default_light();
290            let dark = HighlightTheme::default_dark();
291
292            let first = super::super::shared_code_block_highlighter_at(&light, GENERATION);
293            let again = super::super::shared_code_block_highlighter_at(&light, GENERATION);
294            let other = super::super::shared_code_block_highlighter_at(&dark, GENERATION);
295
296            // Code blocks keep their highlights only while the highlighter is
297            // the same `Arc`.
298            assert!(std::sync::Arc::ptr_eq(&first, &again));
299            assert!(!std::sync::Arc::ptr_eq(&first, &other));
300        }
301
302        #[test]
303        fn registering_a_language_replaces_the_shared_highlighter() {
304            let light = HighlightTheme::default_light();
305
306            let before = super::super::shared_code_block_highlighter_at(&light, u64::MAX - 1);
307            let after = super::super::shared_code_block_highlighter_at(&light, u64::MAX - 2);
308
309            // A new `Arc` makes code blocks painted before the registration
310            // highlight again.
311            assert!(!std::sync::Arc::ptr_eq(&before, &after));
312        }
313    }
314
315    #[test]
316    fn component_theme_adapter_maps_text_colors_without_highlighting() {
317        let theme = Theme::default();
318        let style = super::base_text_view_style(&theme);
319
320        assert_eq!(style.foreground(), theme.foreground);
321        assert_eq!(style.muted_foreground(), theme.muted_foreground);
322        assert_eq!(style.link(), theme.link);
323        assert_eq!(style.selection(), theme.selection);
324        assert_eq!(style.inline_code().background_color, Some(theme.accent));
325        let radius = theme.semantic_tokens().radius.md;
326        assert_eq!(style.table().corner_radii.top_left, Some(radius.into()));
327        assert_eq!(style.table().corner_radii.top_right, Some(radius.into()));
328        assert_eq!(style.table().corner_radii.bottom_left, Some(radius.into()));
329        assert_eq!(style.table().corner_radii.bottom_right, Some(radius.into()));
330    }
331
332    #[test]
333    fn component_text_view_table_respects_square_base_radius_token() {
334        let mut theme = Theme::default();
335        theme.radius = gpui::px(0.);
336
337        let style = super::base_text_view_style(&theme);
338        let square = Some(gpui::px(0.).into());
339        assert_eq!(style.table().corner_radii.top_left, square);
340        assert_eq!(style.table().corner_radii.top_right, square);
341        assert_eq!(style.table().corner_radii.bottom_left, square);
342        assert_eq!(style.table().corner_radii.bottom_right, square);
343    }
344
345    #[cfg(feature = "tree-sitter")]
346    #[gpui::test]
347    fn component_initialization_installs_default_code_highlighting(cx: &mut gpui::TestAppContext) {
348        cx.update(crate::init);
349
350        cx.update(|cx| {
351            assert!(gpui_base::TextViewDefaults::global(cx).has_code_block_highlighter());
352        });
353    }
354
355    #[test]
356    fn legacy_text_paths_reexport_base_implementation() {
357        let mut style = super::TextViewStyle::default();
358        style.highlight_theme = crate::highlighter::HighlightTheme::default_dark();
359
360        let _: super::TextView = super::markdown("# compatible")
361            .style(style)
362            .selectable(true)
363            .scrollable(true);
364    }
365
366    #[test]
367    fn legacy_text_view_keeps_element_associated_types() {
368        fn assert_element_types<T>()
369        where
370            T: gpui::Element<
371                    RequestLayoutState = super::TextViewLayoutState,
372                    PrepaintState = super::TextViewPrepaintState,
373                >,
374        {
375        }
376
377        assert_element_types::<super::TextView>();
378    }
379
380    #[test]
381    fn legacy_default_style_keeps_active_component_theme_colors() {
382        let mut theme = Theme::default();
383        theme.foreground = gpui::rgb(0xf4f4f5).into();
384        theme.link = gpui::rgb(0x38bdf8).into();
385        theme.selection = gpui::rgba(0x2563eb66).into();
386
387        let style = super::compat::resolve_component_style(&theme, super::TextViewStyle::default());
388
389        assert_eq!(style.foreground(), theme.foreground);
390        assert_eq!(style.link(), theme.link);
391        assert_eq!(style.selection(), theme.selection);
392    }
393
394    #[test]
395    fn legacy_table_refinement_keeps_component_radius() {
396        let theme = Theme::default();
397        let mut table = gpui::StyleRefinement::default();
398        table.overflow.x = Some(gpui::Overflow::Scroll);
399
400        let style = super::compat::resolve_component_style(
401            &theme,
402            super::TextViewStyle::default().table(table),
403        );
404
405        let radius = Some(theme.semantic_tokens().radius.md.into());
406        assert_eq!(style.table().corner_radii.top_left, radius);
407        assert_eq!(style.table().corner_radii.top_right, radius);
408        assert_eq!(style.table().corner_radii.bottom_left, radius);
409        assert_eq!(style.table().corner_radii.bottom_right, radius);
410        assert_eq!(style.table().overflow.x, Some(gpui::Overflow::Scroll));
411    }
412
413    #[test]
414    fn legacy_partial_styles_refine_component_theme_defaults() {
415        let theme = Theme::default();
416        let mut table_head = gpui::StyleRefinement::default();
417        table_head.text.font_weight = Some(gpui::FontWeight::BOLD);
418        let inline_code = gpui::HighlightStyle {
419            font_style: Some(gpui::FontStyle::Italic),
420            ..Default::default()
421        };
422
423        let style = super::compat::resolve_component_style(
424            &theme,
425            super::TextViewStyle::default()
426                .table_head(table_head)
427                .inline_code(inline_code),
428        );
429
430        assert_eq!(style.table_head().background, Some(theme.table_head.into()));
431        assert_eq!(
432            style.table_head().text.color,
433            Some(theme.table_head_foreground)
434        );
435        assert_eq!(
436            style.table_head().text.font_weight,
437            Some(gpui::FontWeight::BOLD)
438        );
439        assert_eq!(style.inline_code().background_color, Some(theme.accent));
440        assert_eq!(
441            style.inline_code().font_style,
442            Some(gpui::FontStyle::Italic)
443        );
444    }
445
446    #[test]
447    fn legacy_heading_configuration_maps_to_base_heading_refinements() {
448        let theme = Theme::default();
449        let mut legacy = super::TextViewStyle::default();
450        legacy.heading_base_font_size = px(10.);
451        legacy.heading_font_size = Some(Arc::new(|level, base| base * level as f32));
452
453        let style = super::compat::resolve_component_style(&theme, legacy);
454
455        assert_eq!(
456            style.heading(2),
457            StyleRefinement::default().text_size(px(20.))
458        );
459    }
460}