Skip to main content

iced_code_editor/
theme.rs

1//! Theming support for the code editor widget.
2//!
3//! Defines the [`Style`] appearance record, the [`Catalog`] trait used to
4//! derive a `Style` from an `iced::Theme`, and helpers to build a default
5//! style from any Iced theme's palette.
6
7use iced::Color;
8
9/// The appearance of a code editor.
10///
11/// Build one with [`from_iced_theme`] to follow the application's Iced theme,
12/// then override individual fields for anything that needs to differ.
13///
14/// # Examples
15///
16/// ```
17/// use iced_code_editor::{CodeEditor, theme};
18///
19/// let mut style = theme::from_iced_theme(&iced::Theme::TokyoNightStorm);
20///
21/// // Tweak one color while keeping the rest of the derived palette.
22/// style.current_line_highlight = iced::Color::from_rgba(1.0, 1.0, 1.0, 0.05);
23///
24/// let mut editor = CodeEditor::new("fn main() {}", "rs");
25/// editor.set_theme(style);
26/// ```
27#[derive(Debug, Clone, Copy)]
28pub struct Style {
29    /// Main editor background color
30    pub background: Color,
31    /// Text content color
32    pub text_color: Color,
33    /// Line numbers gutter background color
34    pub gutter_background: Color,
35    /// Border color for the gutter
36    pub gutter_border: Color,
37    /// Color for line numbers text
38    pub line_number_color: Color,
39    /// Color for the line number of the line(s) holding a cursor
40    pub line_number_active_color: Color,
41    /// Scrollbar background color
42    pub scrollbar_background: Color,
43    /// Scrollbar scroller (thumb) color
44    pub scroller_color: Color,
45    /// Highlight color for the current line where cursor is located
46    pub current_line_highlight: Color,
47    /// Color for visible whitespace characters (spaces as `·`, tabs as `→`)
48    pub whitespace_color: Color,
49    /// Color of the vertical indentation guides drawn behind the text
50    pub indent_guide_color: Color,
51    /// Highlight fill color for non-current search matches
52    pub search_match_color: Color,
53    /// Highlight fill color for the currently active search match
54    pub search_match_current_color: Color,
55    /// Fill color for text selection ranges
56    pub selection_color: Color,
57    /// Fill color used to highlight a matching bracket pair
58    pub bracket_match_color: Color,
59    /// Background fill color for the IME preedit (composition) region
60    pub ime_preedit_background_color: Color,
61}
62
63/// The theme catalog of a code editor.
64///
65/// Implemented for [`iced::Theme`] out of the box, following the same catalog
66/// pattern Iced's own widgets use. Implement it for a custom theme type to
67/// make this editor themable alongside the rest of an application.
68///
69/// # Examples
70///
71/// ```
72/// use iced_code_editor::theme::{Catalog, Style};
73///
74/// // `iced::Theme` implements `Catalog`, so a style comes from the theme
75/// // itself rather than being hardcoded.
76/// let class = <iced::Theme as Catalog>::default();
77/// let style: Style = Catalog::style(&iced::Theme::Dracula, &class);
78///
79/// // A dark theme yields a dark editor background.
80/// assert!(style.background.r < 0.5);
81/// ```
82pub trait Catalog {
83    /// The item class of the [`Catalog`].
84    type Class<'a>;
85
86    /// The default class produced by the [`Catalog`].
87    fn default<'a>() -> Self::Class<'a>;
88
89    /// The [`Style`] of a class with the given status.
90    fn style(&self, class: &Self::Class<'_>) -> Style;
91}
92
93/// A styling function for a code editor.
94///
95/// This is a shorthand for a function that takes a reference to a
96/// [`Theme`](iced::Theme) and returns a [`Style`].
97///
98/// # Examples
99///
100/// ```
101/// use iced_code_editor::theme::{self, Style, StyleFn};
102///
103/// // A styling function that derives from the theme, then dims the gutter.
104/// let styling: StyleFn<'_, iced::Theme> = Box::new(|theme| {
105///     let mut style = theme::from_iced_theme(theme);
106///     style.line_number_color.a *= 0.5;
107///     style
108/// });
109///
110/// let style: Style = styling(&iced::Theme::Dracula);
111/// assert!(style.line_number_color.a < 1.0);
112/// ```
113pub type StyleFn<'a, Theme> = Box<dyn Fn(&Theme) -> Style + 'a>;
114
115impl Catalog for iced::Theme {
116    type Class<'a> = StyleFn<'a, Self>;
117
118    fn default<'a>() -> Self::Class<'a> {
119        Box::new(from_iced_theme)
120    }
121
122    fn style(&self, class: &Self::Class<'_>) -> Style {
123        class(self)
124    }
125}
126
127/// Creates a theme style automatically from any Iced theme.
128///
129/// This is the default styling function that adapts to all native Iced themes including:
130/// - Basic themes: Light, Dark
131/// - Popular themes: Dracula, Nord, Solarized, Gruvbox
132/// - Catppuccin variants: Latte, Frappé, Macchiato, Mocha
133/// - Tokyo Night variants: Tokyo Night, Storm, Light
134/// - Kanagawa variants: Wave, Dragon, Lotus
135/// - And more: Moonfly, Nightfly, Oxocarbon, Ferra
136///
137/// The function automatically detects if the theme is dark or light and adjusts
138/// colors accordingly for optimal contrast and readability in code editing.
139///
140/// # Color Mapping
141///
142/// - `background`: Uses the theme's base background color
143/// - `text_color`: Uses the theme's base text color
144/// - `gutter_background`: Slightly darker/lighter than background
145/// - `gutter_border`: Border between gutter and editor
146/// - `line_number_color`: Dimmed text color for subtle line numbers
147/// - `line_number_active_color`: Full text color for the cursor's line number
148/// - `scrollbar_background`: Matches editor background
149/// - `scroller_color`: Uses secondary color for visibility
150/// - `current_line_highlight`: Subtle highlight using primary color
151///
152/// # Example
153///
154/// ```
155/// use iced_code_editor::theme;
156///
157/// let tokyo_night = iced::Theme::TokyoNightStorm;
158/// let style = theme::from_iced_theme(&tokyo_night);
159///
160/// // Or use with any theme variant
161/// let dracula = iced::Theme::Dracula;
162/// let style = theme::from_iced_theme(&dracula);
163/// ```
164pub fn from_iced_theme(theme: &iced::Theme) -> Style {
165    let palette = theme.extended_palette();
166    let is_dark = palette.is_dark;
167
168    // Base colors from theme palette
169    let background = palette.background.base.color;
170    let text_color = palette.background.base.text;
171
172    // Gutter colors: slightly offset from background for subtle distinction
173    let gutter_background = palette.background.weak.color;
174    let gutter_border = if is_dark {
175        darken(palette.background.strong.color, 0.1)
176    } else {
177        lighten(palette.background.strong.color, 0.1)
178    };
179
180    // Line numbers: dimmed text color for subtlety
181    // For dark themes: dim the bright text (make it darker)
182    // For light themes: blend text towards background (make it lighter/grayer)
183    let line_number_color = if is_dark {
184        dim_color(text_color, 0.5)
185    } else {
186        // For light themes, blend text color towards background
187        blend_colors(text_color, background, 0.5)
188    };
189    // The cursor's line number uses the full text color so it stands out.
190    let line_number_active_color = text_color;
191
192    // Scrollbar colors: blend with background
193    let scrollbar_background = background;
194    let scroller_color = palette.secondary.weak.color;
195
196    // Current line highlight: very subtle with primary color
197    let current_line_highlight = with_alpha(
198        palette.primary.weak.color,
199        if is_dark {
200            0.15
201        } else {
202            0.25
203        },
204    );
205
206    let whitespace_color = if is_dark {
207        dim_color(text_color, 0.65)
208    } else {
209        blend_colors(text_color, background, 0.65)
210    };
211
212    // Indentation guides: fainter than visible whitespace, since a guide spans
213    // the full line height and would otherwise compete with the code itself.
214    let indent_guide_color = with_alpha(
215        text_color,
216        if is_dark {
217            0.18
218        } else {
219            0.22
220        },
221    );
222
223    // Search matches: orange for the current match, yellow for the rest.
224    // Fixed values (not palette-derived) to preserve the conventional
225    // search-highlight look regardless of the active theme.
226    let search_match_color = Color {
227        r: 1.0,
228        g: 1.0,
229        b: 0.0,
230        a: 0.3,
231    };
232    let search_match_current_color = Color {
233        r: 1.0,
234        g: 0.6,
235        b: 0.0,
236        a: 0.4,
237    };
238
239    // Text selection fill.
240    let selection_color = Color {
241        r: 0.3,
242        g: 0.5,
243        b: 0.8,
244        a: 0.3,
245    };
246
247    // Matching bracket/quote pair highlight.
248    let bracket_match_color = Color {
249        r: 0.5,
250        g: 0.5,
251        b: 0.5,
252        a: 0.4,
253    };
254
255    // IME preedit (composition) background.
256    let ime_preedit_background_color = Color {
257        r: 1.0,
258        g: 1.0,
259        b: 1.0,
260        a: 0.08,
261    };
262
263    Style {
264        background,
265        text_color,
266        gutter_background,
267        gutter_border,
268        line_number_color,
269        line_number_active_color,
270        scrollbar_background,
271        scroller_color,
272        current_line_highlight,
273        whitespace_color,
274        indent_guide_color,
275        search_match_color,
276        search_match_current_color,
277        selection_color,
278        bracket_match_color,
279        ime_preedit_background_color,
280    }
281}
282
283/// Darkens a color by a given factor (0.0 to 1.0).
284fn darken(color: Color, factor: f32) -> Color {
285    Color {
286        r: color.r * (1.0 - factor),
287        g: color.g * (1.0 - factor),
288        b: color.b * (1.0 - factor),
289        a: color.a,
290    }
291}
292
293/// Lightens a color by a given factor (0.0 to 1.0).
294fn lighten(color: Color, factor: f32) -> Color {
295    Color {
296        r: color.r + (1.0 - color.r) * factor,
297        g: color.g + (1.0 - color.g) * factor,
298        b: color.b + (1.0 - color.b) * factor,
299        a: color.a,
300    }
301}
302
303/// Dims a color by reducing its intensity.
304fn dim_color(color: Color, factor: f32) -> Color {
305    Color {
306        r: color.r * factor,
307        g: color.g * factor,
308        b: color.b * factor,
309        a: color.a,
310    }
311}
312
313/// Blends two colors together by a given factor (0.0 = first color, 1.0 = second color).
314fn blend_colors(color1: Color, color2: Color, factor: f32) -> Color {
315    Color {
316        r: color1.r + (color2.r - color1.r) * factor,
317        g: color1.g + (color2.g - color1.g) * factor,
318        b: color1.b + (color2.b - color1.b) * factor,
319        a: color1.a + (color2.a - color1.a) * factor,
320    }
321}
322
323/// Applies an alpha transparency to a color.
324fn with_alpha(color: Color, alpha: f32) -> Color {
325    Color {
326        r: color.r,
327        g: color.g,
328        b: color.b,
329        a: alpha,
330    }
331}
332
333#[cfg(test)]
334mod tests {
335    use super::*;
336
337    #[test]
338    fn test_from_iced_theme_dark() {
339        let theme = iced::Theme::Dark;
340        let style = from_iced_theme(&theme);
341
342        // Dark theme should have dark background
343        let brightness = (style.background.r + style.background.g + style.background.b) / 3.0;
344        assert!(brightness < 0.5, "Dark theme should have dark background");
345
346        // Text should be bright for contrast
347        let text_brightness = (style.text_color.r + style.text_color.g + style.text_color.b) / 3.0;
348        assert!(text_brightness > 0.5, "Dark theme should have bright text");
349    }
350
351    #[test]
352    fn test_from_iced_theme_light() {
353        let theme = iced::Theme::Light;
354        let style = from_iced_theme(&theme);
355
356        // Light theme should have bright background
357        let brightness = (style.background.r + style.background.g + style.background.b) / 3.0;
358        assert!(
359            brightness > 0.5,
360            "Light theme should have bright background"
361        );
362
363        // Text should be dark for contrast
364        let text_brightness = (style.text_color.r + style.text_color.g + style.text_color.b) / 3.0;
365        assert!(text_brightness < 0.5, "Light theme should have dark text");
366    }
367
368    #[test]
369    fn test_all_iced_themes_produce_valid_styles() {
370        // Test all native Iced themes
371        for theme in iced::Theme::ALL {
372            let style = from_iced_theme(theme);
373
374            // All color components should be valid (0.0 to 1.0)
375            assert!(style.background.r >= 0.0 && style.background.r <= 1.0);
376            assert!(style.text_color.r >= 0.0 && style.text_color.r <= 1.0);
377            assert!(style.gutter_background.r >= 0.0 && style.gutter_background.r <= 1.0);
378            assert!(style.line_number_color.r >= 0.0 && style.line_number_color.r <= 1.0);
379
380            // Current line highlight should have transparency
381            assert!(
382                style.current_line_highlight.a < 1.0,
383                "Current line highlight should be semi-transparent for theme: {:?}",
384                theme
385            );
386
387            // New overlay colors should have valid components and visible
388            // (but not opaque) alpha for every theme.
389            for (name, color) in [
390                ("search_match_color", style.search_match_color),
391                (
392                    "search_match_current_color",
393                    style.search_match_current_color,
394                ),
395                ("selection_color", style.selection_color),
396                ("bracket_match_color", style.bracket_match_color),
397                (
398                    "ime_preedit_background_color",
399                    style.ime_preedit_background_color,
400                ),
401            ] {
402                assert!(
403                    color.r >= 0.0 && color.r <= 1.0,
404                    "{name}.r out of range for theme: {theme:?}"
405                );
406                assert!(
407                    color.g >= 0.0 && color.g <= 1.0,
408                    "{name}.g out of range for theme: {theme:?}"
409                );
410                assert!(
411                    color.b >= 0.0 && color.b <= 1.0,
412                    "{name}.b out of range for theme: {theme:?}"
413                );
414                assert!(
415                    color.a > 0.0 && color.a < 1.0,
416                    "{name} should be semi-transparent for theme: {theme:?}"
417                );
418            }
419        }
420    }
421
422    #[test]
423    fn test_overlay_colors_are_theme_independent() {
424        // The 5 overlay colors are fixed constants (not palette-derived), so
425        // they must be identical across very different themes.
426        let light = from_iced_theme(&iced::Theme::Light);
427        let dark = from_iced_theme(&iced::Theme::Dark);
428
429        for (light_color, dark_color) in [
430            (light.search_match_color, dark.search_match_color),
431            (
432                light.search_match_current_color,
433                dark.search_match_current_color,
434            ),
435            (light.selection_color, dark.selection_color),
436            (light.bracket_match_color, dark.bracket_match_color),
437            (
438                light.ime_preedit_background_color,
439                dark.ime_preedit_background_color,
440            ),
441        ] {
442            assert!((light_color.r - dark_color.r).abs() < f32::EPSILON);
443            assert!((light_color.g - dark_color.g).abs() < f32::EPSILON);
444            assert!((light_color.b - dark_color.b).abs() < f32::EPSILON);
445            assert!((light_color.a - dark_color.a).abs() < f32::EPSILON);
446        }
447    }
448
449    #[test]
450    fn test_tokyo_night_themes() {
451        // Test Tokyo Night variants specifically
452        let tokyo_night = iced::Theme::TokyoNight;
453        let style = from_iced_theme(&tokyo_night);
454        assert!(style.background.r >= 0.0 && style.background.r <= 1.0);
455
456        let tokyo_storm = iced::Theme::TokyoNightStorm;
457        let style = from_iced_theme(&tokyo_storm);
458        assert!(style.background.r >= 0.0 && style.background.r <= 1.0);
459
460        let tokyo_light = iced::Theme::TokyoNightLight;
461        let style = from_iced_theme(&tokyo_light);
462        let brightness = (style.background.r + style.background.g + style.background.b) / 3.0;
463        assert!(
464            brightness > 0.5,
465            "Tokyo Night Light should have bright background"
466        );
467    }
468
469    #[test]
470    fn test_catppuccin_themes() {
471        // Test Catppuccin variants
472        let themes = [
473            iced::Theme::CatppuccinLatte,
474            iced::Theme::CatppuccinFrappe,
475            iced::Theme::CatppuccinMacchiato,
476            iced::Theme::CatppuccinMocha,
477        ];
478
479        for theme in themes {
480            let style = from_iced_theme(&theme);
481            // All should produce valid styles
482            assert!(style.background.r >= 0.0 && style.background.r <= 1.0);
483            assert!(style.text_color.r >= 0.0 && style.text_color.r <= 1.0);
484        }
485    }
486
487    #[test]
488    fn test_gutter_colors_distinct_from_background() {
489        let theme = iced::Theme::Dark;
490        let style = from_iced_theme(&theme);
491
492        // Gutter background should be different from editor background
493        let gutter_diff = (style.gutter_background.r - style.background.r).abs()
494            + (style.gutter_background.g - style.background.g).abs()
495            + (style.gutter_background.b - style.background.b).abs();
496
497        assert!(
498            gutter_diff > 0.0,
499            "Gutter should be visually distinct from background"
500        );
501    }
502
503    #[test]
504    fn test_from_iced_theme_active_line_number_stands_out() {
505        for theme in [iced::Theme::Dark, iced::Theme::Light] {
506            let style = from_iced_theme(&theme);
507            let contrast = |c: Color| {
508                (c.r - style.background.r).abs()
509                    + (c.g - style.background.g).abs()
510                    + (c.b - style.background.b).abs()
511            };
512            assert!(
513                contrast(style.line_number_active_color) > contrast(style.line_number_color),
514                "active line number should contrast more with the background than inactive ones"
515            );
516        }
517    }
518
519    #[test]
520    fn test_line_numbers_visible_but_subtle() {
521        for theme in [iced::Theme::Dark, iced::Theme::Light] {
522            let style = from_iced_theme(&theme);
523            let palette = theme.extended_palette();
524
525            // Line numbers should be dimmed compared to text
526            let line_num_brightness =
527                (style.line_number_color.r + style.line_number_color.g + style.line_number_color.b)
528                    / 3.0;
529
530            let text_brightness =
531                (style.text_color.r + style.text_color.g + style.text_color.b) / 3.0;
532
533            let bg_brightness =
534                (style.background.r + style.background.g + style.background.b) / 3.0;
535
536            // Line numbers should be between text and background (more subtle than text)
537            // For dark themes: text is bright, line numbers dimmer, background dark
538            // For light themes: text is dark, line numbers lighter (gray), background bright
539            if palette.is_dark {
540                // Dark theme: line numbers should be less bright than text
541                assert!(
542                    line_num_brightness < text_brightness,
543                    "Dark theme line numbers should be dimmer than text. Line num: {}, Text: {}",
544                    line_num_brightness,
545                    text_brightness
546                );
547            } else {
548                // Light theme: line numbers should be between text (dark) and background (bright)
549                assert!(
550                    line_num_brightness > text_brightness && line_num_brightness < bg_brightness,
551                    "Light theme line numbers should be between text and background. Text: {}, Line num: {}, Bg: {}",
552                    text_brightness,
553                    line_num_brightness,
554                    bg_brightness
555                );
556            }
557        }
558    }
559
560    #[test]
561    fn test_color_helper_functions() {
562        let color = Color::from_rgb(0.5, 0.5, 0.5);
563
564        // Test darken
565        let darker = darken(color, 0.5);
566        assert!(darker.r < color.r);
567        assert!(darker.g < color.g);
568        assert!(darker.b < color.b);
569
570        // Test lighten
571        let lighter = lighten(color, 0.5);
572        assert!(lighter.r > color.r);
573        assert!(lighter.g > color.g);
574        assert!(lighter.b > color.b);
575
576        // Test dim_color
577        let dimmed = dim_color(color, 0.5);
578        assert!(dimmed.r < color.r);
579
580        // Test with_alpha
581        let transparent = with_alpha(color, 0.3);
582        assert!((transparent.a - 0.3).abs() < f32::EPSILON);
583        assert!((transparent.r - color.r).abs() < f32::EPSILON);
584    }
585
586    #[test]
587    fn test_style_copy() {
588        let theme = iced::Theme::Dark;
589        let style1 = from_iced_theme(&theme);
590        let style2 = style1;
591
592        // Verify colors are approximately equal (using epsilon for float comparison)
593        assert!((style1.background.r - style2.background.r).abs() < f32::EPSILON);
594        assert!((style1.text_color.r - style2.text_color.r).abs() < f32::EPSILON);
595        assert!((style1.gutter_background.r - style2.gutter_background.r).abs() < f32::EPSILON);
596        assert!((style1.selection_color.r - style2.selection_color.r).abs() < f32::EPSILON);
597    }
598
599    #[test]
600    fn test_catalog_default() {
601        let theme = iced::Theme::Dark;
602        let class = <iced::Theme as Catalog>::default();
603        let style = theme.style(&class);
604
605        // Should produce a valid style
606        assert!(style.background.r >= 0.0 && style.background.r <= 1.0);
607        assert!(style.text_color.r >= 0.0 && style.text_color.r <= 1.0);
608    }
609}