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