lumis-core 2.4.0

Lumis shared core
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
//! HTML formatter with multiple theme support using CSS variables.
//!
//! Works with pre-computed highlight events from any source.

use super::{Formatter, HtmlElement};
use crate::events::HighlightEvent;
use crate::formatter::html_inline::HighlightLines;
use crate::languages::Language;
use crate::themes::Theme;
use derive_builder::Builder;
use std::collections::HashMap;
use std::io::{self, Write};
use std::str::FromStr;

/// Configuration for which theme to use as the default (inline styles).
#[derive(Clone, Debug)]
pub enum DefaultTheme {
    /// Use a specific named theme as the default (e.g., "light", "dark")
    Theme(String),
    /// Use CSS `light-dark()` function (requires light and dark themes)
    LightDark,
}

impl FromStr for DefaultTheme {
    type Err = std::convert::Infallible;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Ok(match s {
            "light-dark()" => DefaultTheme::LightDark,
            theme_name => DefaultTheme::Theme(theme_name.to_string()),
        })
    }
}

/// HTML formatter with multiple theme support.
#[derive(Builder, Clone, Debug)]
#[builder(default, build_fn(skip))]
pub struct HtmlMultiThemes {
    #[builder(setter(custom))]
    language: Language,
    themes: HashMap<String, Theme>,
    #[builder(setter(custom))]
    default_theme: Option<DefaultTheme>,
    #[builder(setter(into))]
    css_variable_prefix: String,
    pre_class: Option<String>,
    italic: bool,
    include_highlights: bool,
    highlight_lines: Option<HighlightLines>,
    header: Option<HtmlElement>,
}

impl HtmlMultiThemesBuilder {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn language(&mut self, language: Language) -> &mut Self {
        self.language = Some(language);
        self
    }

    #[deprecated(note = "use `.language(...)` instead")]
    pub fn lang(&mut self, language: Language) -> &mut Self {
        self.language(language)
    }

    pub fn default_theme<T: Into<DefaultThemeArg>>(&mut self, value: T) -> &mut Self {
        self.default_theme = Some(value.into().into_enum());
        self
    }

    pub fn build(&mut self) -> Result<HtmlMultiThemes, String> {
        let result = HtmlMultiThemes {
            language: self.language.take().unwrap_or(Language::PlainText),
            themes: self.themes.take().unwrap_or_default(),
            default_theme: self.default_theme.take().flatten(),
            css_variable_prefix: self
                .css_variable_prefix
                .take()
                .unwrap_or_else(|| "--lumis".to_string()),
            pre_class: self.pre_class.take().flatten(),
            italic: self.italic.take().unwrap_or(false),
            include_highlights: self.include_highlights.take().unwrap_or(false),
            highlight_lines: self.highlight_lines.take().flatten(),
            header: self.header.take().flatten(),
        };

        if result.themes.is_empty() {
            return Err("At least one theme is required".to_string());
        }

        match &result.default_theme {
            Some(DefaultTheme::Theme(name)) if !result.themes.contains_key(name) => {
                return Err(format!("Default theme '{}' not found in themes map", name));
            }
            Some(DefaultTheme::LightDark)
                if !result.themes.contains_key("light") || !result.themes.contains_key("dark") =>
            {
                return Err("LightDark mode requires themes named 'light' and 'dark'".to_string());
            }
            _ => {}
        }

        Ok(result)
    }
}

/// Argument type for the `default_theme` builder method.
#[doc(hidden)]
pub enum DefaultThemeArg {
    String(String),
    Bool(bool),
}

impl DefaultThemeArg {
    fn into_enum(self) -> Option<DefaultTheme> {
        match self {
            DefaultThemeArg::String(s) => Some(s.parse().unwrap()),
            DefaultThemeArg::Bool(false) => None,
            DefaultThemeArg::Bool(true) => Some(DefaultTheme::Theme("light".to_string())),
        }
    }
}

impl From<&str> for DefaultThemeArg {
    fn from(s: &str) -> Self {
        DefaultThemeArg::String(s.to_string())
    }
}

impl From<String> for DefaultThemeArg {
    fn from(s: String) -> Self {
        DefaultThemeArg::String(s)
    }
}

impl From<bool> for DefaultThemeArg {
    fn from(b: bool) -> Self {
        DefaultThemeArg::Bool(b)
    }
}

impl Default for HtmlMultiThemes {
    fn default() -> Self {
        Self {
            language: Language::PlainText,
            themes: HashMap::new(),
            default_theme: None,
            css_variable_prefix: "--lumis".to_string(),
            pre_class: None,
            italic: false,
            include_highlights: false,
            highlight_lines: None,
            header: None,
        }
    }
}

impl HtmlMultiThemes {
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        language: Language,
        themes: HashMap<String, Theme>,
        default_theme: Option<DefaultTheme>,
        css_variable_prefix: String,
        pre_class: Option<String>,
        italic: bool,
        include_highlights: bool,
        highlight_lines: Option<HighlightLines>,
        header: Option<HtmlElement>,
    ) -> Self {
        Self {
            language,
            themes,
            default_theme,
            css_variable_prefix,
            pre_class,
            italic,
            include_highlights,
            highlight_lines,
            header,
        }
    }

    fn open_pre_tag(&self, output: &mut dyn Write) -> io::Result<()> {
        crate::formatter::html::open_multi_themes_pre_tag(
            output,
            self.pre_class.as_deref(),
            &self.themes,
            self.default_theme_name(),
            &self.css_variable_prefix,
        )
    }

    fn default_theme_name(&self) -> Option<&str> {
        match &self.default_theme {
            Some(DefaultTheme::Theme(name)) => Some(name.as_str()),
            Some(DefaultTheme::LightDark) => Some("light-dark()"),
            None => None,
        }
    }

    fn get_line_attrs(&self, line_number: usize) -> (Option<String>, Option<String>) {
        let is_highlighted = self
            .highlight_lines
            .as_ref()
            .is_some_and(|hl| hl.lines.iter().any(|r| r.contains(&line_number)));

        if !is_highlighted {
            return (None, None);
        }

        let class_suffix = self
            .highlight_lines
            .as_ref()
            .and_then(|hl| hl.class.as_ref())
            .map(|c| format!(" {}", c));

        let style = self.get_highlight_style();

        (class_suffix, style)
    }

    fn get_highlight_style(&self) -> Option<String> {
        use crate::formatter::html_inline::HighlightLinesStyle;

        let highlight_lines = self.highlight_lines.as_ref()?;

        match &highlight_lines.style {
            Some(HighlightLinesStyle::Theme) => match &self.default_theme {
                Some(DefaultTheme::Theme(default_name)) => {
                    let theme = self.themes.get(default_name)?;
                    let highlighted_style = theme.get_style("highlighted")?;
                    Some(highlighted_style.css(self.italic, " "))
                }
                Some(DefaultTheme::LightDark) => self.light_dark_highlight_style(),
                None => None,
            },
            Some(HighlightLinesStyle::Style(style_string)) => Some(style_string.clone()),
            None => None,
        }
    }

    fn light_dark_highlight_style(&self) -> Option<String> {
        let light = self.themes.get("light")?.get_style("highlighted")?;
        let dark = self.themes.get("dark")?.get_style("highlighted")?;
        let light_bg = light.bg.as_ref()?;
        let dark_bg = dark.bg.as_ref()?;

        Some(format!(
            "background-color: light-dark({light_bg}, {dark_bg});"
        ))
    }

    fn span_attrs_from_index(&self, scope_index: usize, language: &str) -> String {
        let scope = crate::highlights::HIGHLIGHT_NAMES
            .get(scope_index)
            .copied()
            .unwrap_or("");
        let lang = language.parse::<Language>().ok();
        crate::formatter::html::span_multi_themes_attrs(
            scope,
            lang,
            &self.themes,
            self.default_theme_name(),
            &self.css_variable_prefix,
            self.italic,
            self.include_highlights,
        )
    }
}

impl Formatter for HtmlMultiThemes {
    fn render(
        &self,
        source: &str,
        events: &[HighlightEvent],
        output: &mut dyn Write,
    ) -> io::Result<()> {
        let mut buffer = Vec::new();

        if let Some(ref header) = self.header {
            write!(buffer, "{}", header.open_tag)?;
        }

        self.open_pre_tag(&mut buffer)?;
        crate::formatter::html::open_code_tag(&mut buffer, &self.language)?;

        let lines = crate::formatter::html::render_lines_from_events(
            source,
            events,
            |scope_index, language| self.span_attrs_from_index(scope_index, language),
        );

        for (i, line) in lines.iter().enumerate() {
            let line_number = i + 1;
            let line_with_newline = format!("{line}\n");
            let (class_suffix, style) = self.get_line_attrs(line_number);
            let wrapped = crate::formatter::html::wrap_line(
                line_number,
                &line_with_newline,
                class_suffix.as_deref(),
                style.as_deref(),
            );
            write!(&mut buffer, "{}", wrapped)?;
        }

        crate::formatter::html::closing_tags(&mut buffer)?;

        if let Some(ref header) = self.header {
            write!(buffer, "{}", header.close_tag)?;
        }

        output.write_all(&buffer)?;
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn attr_value<'a>(tag: &'a str, attr: &str) -> &'a str {
        let marker = format!(r#"{attr}=""#);
        let start = tag.find(&marker).expect("missing attribute") + marker.len();
        let end = tag[start..].find('"').expect("unterminated attribute");
        &tag[start..start + end]
    }

    fn assert_classes(tag: &str, expected: &[&str]) {
        let classes: std::collections::HashSet<&str> =
            attr_value(tag, "class").split(' ').collect();

        assert_eq!(classes.len(), expected.len());
        for class in expected {
            assert!(classes.contains(class), "missing class {class:?} in {tag}");
        }
    }

    #[test]
    fn render_uses_multi_themes_pre_tag_helper() {
        let mut themes = HashMap::new();
        themes.insert(
            "light".to_string(),
            crate::themes::get("catppuccin_latte").unwrap(),
        );
        themes.insert(
            "dark".to_string(),
            crate::themes::get("catppuccin_mocha").unwrap(),
        );

        let formatter = HtmlMultiThemes::new(
            Language::PlainText,
            themes,
            Some(DefaultTheme::LightDark),
            "--lumis".to_string(),
            Some("custom-pre".to_string()),
            false,
            false,
            None,
            None,
        );
        let mut output = Vec::new();

        formatter.render("", &[], &mut output).unwrap();

        let html = String::from_utf8(output).unwrap();
        let pre_tag = html.split_once('>').expect("missing pre tag").0;

        assert_classes(
            pre_tag,
            &["lumis", "lumis-themes", "custom-pre", "light", "dark"],
        );
        assert_eq!(
            attr_value(pre_tag, "style"),
            "color: light-dark(#4c4f69, #cdd6f4); background-color: light-dark(#eff1f5, #1e1e2e);"
        );
    }

    fn render_highlighted_line(
        default_theme: DefaultTheme,
        light_background: Option<&str>,
        dark_background: Option<&str>,
    ) -> String {
        use crate::formatter::html_inline::{HighlightLines, HighlightLinesStyle};

        let mut themes = HashMap::new();
        let mut light = crate::themes::get("catppuccin_latte").unwrap();
        let light_highlighted = light.highlights.get_mut("highlighted").unwrap();
        light_highlighted.fg = Some("#111111".to_string());
        light_highlighted.bg = light_background.map(str::to_string);
        themes.insert("light".to_string(), light);

        let mut dark = crate::themes::get("catppuccin_mocha").unwrap();
        let dark_highlighted = dark.highlights.get_mut("highlighted").unwrap();
        dark_highlighted.fg = Some("#eeeeee".to_string());
        dark_highlighted.bg = dark_background.map(str::to_string);
        themes.insert("dark".to_string(), dark);

        let formatter = HtmlMultiThemes::new(
            Language::PlainText,
            themes,
            Some(default_theme),
            "--lumis".to_string(),
            None,
            false,
            false,
            Some(HighlightLines {
                lines: std::iter::once(1..=1).collect(),
                style: Some(HighlightLinesStyle::Theme),
                class: None,
            }),
            None,
        );
        let mut output = Vec::new();

        formatter.render("one\ntwo", &[], &mut output).unwrap();

        let html = String::from_utf8(output).unwrap();
        let line_tag = html
            .split_once("<div ")
            .expect("missing first line")
            .1
            .split_once('>')
            .expect("unterminated line tag")
            .0;
        assert!(
            line_tag.contains(r#"data-line="1""#),
            "wrong line: {line_tag}"
        );

        line_tag.to_string()
    }

    #[test]
    fn theme_highlight_lines_follow_the_colour_scheme() {
        let line_tag =
            render_highlighted_line(DefaultTheme::LightDark, Some("#e9ebf1"), Some("#2a2b3c"));
        assert_eq!(
            attr_value(&line_tag, "style"),
            "background-color: light-dark(#e9ebf1, #2a2b3c);"
        );
    }

    #[test]
    fn light_dark_theme_highlight_lines_require_a_light_background() {
        let line_tag = render_highlighted_line(DefaultTheme::LightDark, None, Some("#2a2b3c"));

        assert!(
            !line_tag.contains(" style="),
            "unexpected style: {line_tag}"
        );
    }

    #[test]
    fn light_dark_theme_highlight_lines_require_a_dark_background() {
        let line_tag = render_highlighted_line(DefaultTheme::LightDark, Some("#e9ebf1"), None);

        assert!(
            !line_tag.contains(" style="),
            "unexpected style: {line_tag}"
        );
    }

    #[test]
    fn theme_highlight_lines_use_the_named_default_theme() {
        let line_tag = render_highlighted_line(
            DefaultTheme::Theme("dark".to_string()),
            Some("#e9ebf1"),
            Some("#2a2b3c"),
        );
        assert_eq!(
            attr_value(&line_tag, "style"),
            "color: #eeeeee; background-color: #2a2b3c;"
        );
    }
}