crates/highlight/src/theme.rs 18.7 KiB raw
1
//! Theme compilation and style-span generation.
2
//!
3
//! Themes resolve TextMate-style selectors into compact [`Style`] values, then
4
//! apply those styles to token scope spans one line at a time. The hot paths
5
//! reuse caller-owned output buffers so editors can restyle visible text without
6
//! allocating for every token.
7
8
use std::cmp::Reverse;
9
use std::{convert::Infallible, str::FromStr};
10
11
use crate::Error;
12
use crate::grammar::{Grammar, ScopeId, ScopeSpan};
13
use crate::raw::{RawStyle, RawTheme};
14
use crate::util::{next_char_boundary, previous_char_boundary, trim_line_end};
15
16
/// Immutable compiled theme data.
17
#[derive(Debug)]
18
pub struct Theme {
19
    /// Theme name.
20
    pub name: String,
21
    /// Default style for unscoped text.
22
    pub default: Style,
23
    /// Compiled selector rules.
24
    rules: Vec<ThemeRule>,
25
}
26
27
/// One selector-to-style rule compiled from a theme.
28
#[derive(Debug)]
29
struct ThemeRule {
30
    /// TextMate-style scope selector matched against token scopes.
31
    selector: String,
32
    /// Selector components ordered from parent scopes to current scope.
33
    parts: Vec<String>,
34
    /// Style applied when the selector matches.
35
    style: RuleStyle,
36
}
37
38
/// Per-line scratch buffer used while applying a theme.
39
#[derive(Debug, Default)]
40
pub(crate) struct StyleScratch {
41
    /// Theme and grammar identity this scratch cache belongs to.
42
    context: Option<StyleScratchContext>,
43
    /// Sorted byte boundaries that split a line into uniformly styled segments.
44
    boundaries: Vec<usize>,
45
    /// Uniformly styled segments for the current line.
46
    segments: Vec<Segment>,
47
    /// Scope spans covering the current segment.
48
    covering: Vec<ScopeSpan>,
49
    /// Scope stack for the current segment.
50
    stack: Vec<ScopeId>,
51
    /// Cached style results for repeated scope stacks.
52
    styles: Vec<StyleStackEntry>,
53
}
54
55
/// Byte range for one fully resolved style segment.
56
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
57
struct Segment {
58
    /// Start byte in the line.
59
    start: usize,
60
    /// End byte in the line.
61
    end: usize,
62
}
63
64
/// Identity of the immutable inputs used by style scratch caches.
65
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
66
struct StyleScratchContext {
67
    /// Theme object address.
68
    theme: usize,
69
    /// Grammar object address.
70
    grammar: usize,
71
}
72
73
/// Cached style result for one ordered scope stack.
74
#[derive(Clone, Debug, Eq, PartialEq)]
75
struct StyleStackEntry {
76
    /// Ordered scopes covering a segment.
77
    stack: Vec<ScopeId>,
78
    /// The most specific scope covering this styled span, if any.
79
    scope: Option<ScopeId>,
80
    /// Resolved style.
81
    style: Style,
82
}
83
84
/// Resolved style and selector score for one scope.
85
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
86
struct ScopeStyle {
87
    /// Resolved style.
88
    style: RuleStyle,
89
    /// Length of the most specific matched selector, or zero for the default.
90
    score: usize,
91
}
92
93
/// Partially specified style compiled from one theme rule.
94
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
95
struct RuleStyle {
96
    /// Optional foreground color.
97
    foreground: Option<Rgb>,
98
    /// Optional font-style override.
99
    font_style: Option<FontStyle>,
100
}
101
102
/// Fully styled span produced by applying a [`Theme`] to scope spans.
103
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
104
pub struct StyleSpan {
105
    /// Start byte in the line.
106
    pub start: usize,
107
    /// End byte in the line.
108
    pub end: usize,
109
    /// The most specific scope covering this styled span, if any.
110
    pub scope: Option<ScopeId>,
111
    /// Resolved style.
112
    pub style: Style,
113
}
114
115
/// RGB color parsed from a theme.
116
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
117
pub struct Rgb {
118
    /// Red channel.
119
    pub r: u8,
120
    /// Green channel.
121
    pub g: u8,
122
    /// Blue channel.
123
    pub b: u8,
124
}
125
126
/// Error returned when parsing an RGB color.
127
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
128
pub struct ParseRgbError;
129
130
/// Bitset of font style flags.
131
#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
132
pub struct FontStyle(u8);
133
134
/// Resolved style for a token.
135
#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
136
pub struct Style {
137
    /// Optional foreground color.
138
    pub foreground: Option<Rgb>,
139
    /// Font style flags.
140
    pub font_style: FontStyle,
141
}
142
143
impl Theme {
144
    /// Compiles a raw theme.
145
    pub fn compile(raw: &RawTheme) -> Self {
146
        let mut default = Style::NONE;
147
        let mut rules = Vec::new();
148
        let raw_rules = if raw.token_colors.is_empty() {
149
            &raw.settings
150
        } else {
151
            &raw.token_colors
152
        };
153
154
        for rule in raw_rules {
155
            let selectors = rule.scope_selectors();
156
            if selectors.is_empty() {
157
                if let Some(foreground) = &rule.settings.foreground {
158
                    default.foreground = foreground.parse().ok();
159
                }
160
                if let Some(flags) = &rule.settings.font_style {
161
                    default.font_style = flags.parse().unwrap_or_else(|error| match error {});
162
                }
163
            } else {
164
                let style = RuleStyle::from_raw(&rule.settings);
165
                rules.extend(
166
                    selectors
167
                        .into_iter()
168
                        .map(|selector| ThemeRule::new(selector, style)),
169
                );
170
            }
171
        }
172
        Self {
173
            name: raw.name.clone(),
174
            default,
175
            rules,
176
        }
177
    }
178
179
    /// Parses and compiles a theme from JSON.
180
    pub fn parse(input: &str) -> Result<Self, Error> {
181
        input.parse()
182
    }
183
184
    /// Resolves a style for a scope string.
185
    ///
186
    /// The most specific selector wins, with ties broken by longer selectors.
187
    pub fn style_for_scope(&self, scope: &str) -> Style {
188
        let stack = scope.split_whitespace().collect::<Vec<_>>();
189
        let Some((scope, parents)) = stack.split_last() else {
190
            return self.default;
191
        };
192
        self.match_scope(scope, parents)
193
            .style
194
            .apply_to(self.default)
195
    }
196
197
    /// Applies this theme to scope spans and returns a freshly allocated vector.
198
    pub fn style_spans(
199
        &self,
200
        grammar: &Grammar,
201
        line: &str,
202
        scopes: &[ScopeSpan],
203
    ) -> Vec<StyleSpan> {
204
        let mut scratch = StyleScratch::default();
205
        let mut output = Vec::new();
206
207
        self.style_line_into(grammar, line, scopes, &mut scratch, &mut output);
208
        output
209
    }
210
211
    /// Applies this theme one line at a time using caller-owned scratch storage.
212
    pub(crate) fn style_line_into(
213
        &self,
214
        grammar: &Grammar,
215
        line: &str,
216
        scopes: &[ScopeSpan],
217
        scratch: &mut StyleScratch,
218
        output: &mut Vec<StyleSpan>,
219
    ) {
220
        output.clear();
221
        let line = trim_line_end(line);
222
        if line.is_empty() {
223
            return;
224
        }
225
        scratch.prepare(self, grammar);
226
        scratch.collect_boundaries(line, scopes);
227
228
        for index in 0..scratch.segment_count() {
229
            let segment = scratch.segment(index);
230
            output.push(self.style_stack_segment(grammar, scopes, scratch, segment));
231
        }
232
    }
233
234
    /// Resolves one segment using TextMate-style scope stack matching.
235
    fn style_stack_segment(
236
        &self,
237
        grammar: &Grammar,
238
        scopes: &[ScopeSpan],
239
        scratch: &mut StyleScratch,
240
        segment: Segment,
241
    ) -> StyleSpan {
242
        scratch.collect_covering(segment, scopes);
243
244
        if let Some(entry) = scratch.cached_stack() {
245
            return segment.styled(entry.scope, entry.style);
246
        }
247
248
        let mut style = self.root_style(grammar);
249
        let mut scope = None;
250
        let mut parents = vec![grammar.scope_name.as_str()];
251
252
        for span in scratch.covering() {
253
            let Some(name) = grammar.scopes.get(span.scope.index()) else {
254
                continue;
255
            };
256
            let matched = self.match_scope(name, &parents);
257
            if matched.score > 0 {
258
                style = matched.style.apply_to(style);
259
                scope = Some(span.scope);
260
            } else if scope.is_none() {
261
                scope = Some(span.scope);
262
            }
263
            parents.push(name);
264
        }
265
        scratch.insert_cached_stack(scope, style);
266
        segment.styled(scope, style)
267
    }
268
269
    /// Returns the base style for the grammar root scope.
270
    fn root_style(&self, grammar: &Grammar) -> Style {
271
        self.match_scope(&grammar.scope_name, &[])
272
            .style
273
            .apply_to(self.default)
274
    }
275
276
    /// Returns the strongest rule matching one current scope and its parents.
277
    fn match_scope(&self, scope: &str, parents: &[&str]) -> ScopeStyle {
278
        let mut style = RuleStyle::NONE;
279
        let mut best = 0;
280
281
        for scope in [Some(scope), fallback_scope(scope)] {
282
            let Some(scope) = scope else { continue };
283
            for rule in &self.rules {
284
                let score = rule.match_score(scope, parents);
285
                if score > 0 && score >= best {
286
                    best = score;
287
                    style = rule.style.merge(style);
288
                }
289
            }
290
        }
291
        ScopeStyle { style, score: best }
292
    }
293
}
294
295
impl FromStr for Theme {
296
    type Err = Error;
297
298
    /// Parses and compiles a theme from JSON.
299
    fn from_str(input: &str) -> Result<Self, Self::Err> {
300
        let raw = RawTheme::from_str(input)?;
301
        Ok(Self::compile(&raw))
302
    }
303
}
304
305
impl ThemeRule {
306
    /// Creates a compiled theme rule.
307
    fn new(selector: String, style: RuleStyle) -> Self {
308
        let parts = selector
309
            .split_whitespace()
310
            .map(ToOwned::to_owned)
311
            .collect::<Vec<_>>();
312
        Self {
313
            selector,
314
            parts,
315
            style,
316
        }
317
    }
318
319
    /// Returns this rule's selector score for a scope stack.
320
    fn match_score(&self, scope: &str, parents: &[&str]) -> usize {
321
        let Some(current) = self.parts.last() else {
322
            return 0;
323
        };
324
        if !scope_matches_selector(scope, current) {
325
            return 0;
326
        }
327
        let mut parent = parents.len();
328
        for selector in self.parts[..self.parts.len().saturating_sub(1)]
329
            .iter()
330
            .rev()
331
        {
332
            let mut matched = false;
333
            while parent > 0 {
334
                parent -= 1;
335
                if scope_matches_selector(parents[parent], selector) {
336
                    matched = true;
337
                    break;
338
                }
339
            }
340
            if !matched {
341
                return 0;
342
            }
343
        }
344
        self.selector.len()
345
    }
346
}
347
348
/// Returns whether a single concrete scope matches one selector component.
349
fn scope_matches_selector(scope: &str, selector: &str) -> bool {
350
    scope == selector
351
        || (scope.len() > selector.len()
352
            && scope.starts_with(selector)
353
            && scope.as_bytes().get(selector.len()) == Some(&b'.'))
354
}
355
356
impl StyleScratch {
357
    /// Clears per-line scratch storage while retaining allocations.
358
    pub(crate) fn clear_line(&mut self) {
359
        self.boundaries.clear();
360
        self.segments.clear();
361
        self.covering.clear();
362
        self.stack.clear();
363
    }
364
365
    /// Prepares scratch caches for one immutable theme and grammar pair.
366
    fn prepare(&mut self, theme: &Theme, grammar: &Grammar) {
367
        let context = StyleScratchContext {
368
            theme: theme as *const Theme as usize,
369
            grammar: grammar as *const Grammar as usize,
370
        };
371
        if self.context == Some(context) {
372
            return;
373
        }
374
        self.context = Some(context);
375
        self.styles.clear();
376
    }
377
378
    /// Collects sorted byte boundaries for the style segments in a line.
379
    fn collect_boundaries(&mut self, line: &str, scopes: &[ScopeSpan]) {
380
        self.boundaries.clear();
381
        self.boundaries.push(0);
382
        self.boundaries.push(line.len());
383
384
        for span in scopes {
385
            let start = next_char_boundary(line, span.start);
386
            let end = previous_char_boundary(line, span.end);
387
            if start < end {
388
                self.boundaries.push(start);
389
                self.boundaries.push(end);
390
            }
391
        }
392
        self.boundaries.sort_unstable();
393
        self.boundaries.dedup();
394
395
        self.segments.clear();
396
        self.segments
397
            .extend(self.boundaries.windows(2).filter_map(|window| {
398
                let [start, end] = *window else {
399
                    return None;
400
                };
401
                (start < end).then_some(Segment { start, end })
402
            }));
403
    }
404
405
    /// Returns how many segments are in the current line.
406
    fn segment_count(&self) -> usize {
407
        self.segments.len()
408
    }
409
410
    /// Returns one segment by index.
411
    fn segment(&self, index: usize) -> Segment {
412
        self.segments[index]
413
    }
414
415
    /// Collects ordered scope spans covering a segment.
416
    fn collect_covering(&mut self, segment: Segment, spans: &[ScopeSpan]) {
417
        self.covering.clear();
418
        self.stack.clear();
419
420
        self.covering.extend(
421
            spans
422
                .iter()
423
                .copied()
424
                .filter(|span| span.start <= segment.start && span.end >= segment.end),
425
        );
426
        self.covering
427
            .sort_by_key(|span| (Reverse(span.end - span.start), span.start, span.end));
428
        self.stack
429
            .extend(self.covering.iter().map(|span| span.scope));
430
    }
431
432
    /// Returns the cached style result for the current scope stack.
433
    fn cached_stack(&self) -> Option<&StyleStackEntry> {
434
        self.styles
435
            .iter()
436
            .find(|entry| entry.stack.as_slice() == self.stack.as_slice())
437
    }
438
439
    /// Inserts a style result for the current scope stack.
440
    fn insert_cached_stack(&mut self, scope: Option<ScopeId>, style: Style) {
441
        self.styles.push(StyleStackEntry {
442
            stack: self.stack.clone(),
443
            scope,
444
            style,
445
        });
446
    }
447
448
    /// Returns the current segment's ordered covering scopes.
449
    fn covering(&self) -> &[ScopeSpan] {
450
        &self.covering
451
    }
452
}
453
impl Segment {
454
    /// Builds a styled span from this segment.
455
    fn styled(self, scope: Option<ScopeId>, style: Style) -> StyleSpan {
456
        StyleSpan {
457
            start: self.start,
458
            end: self.end,
459
            scope,
460
            style,
461
        }
462
    }
463
}
464
465
/// Returns a theme selector fallback for scopes that Shiki emits as metadata.
466
fn fallback_scope(scope: &str) -> Option<&'static str> {
467
    if scope_matches_selector(scope, "meta.attribute") {
468
        Some("attribute.name")
469
    } else if scope_matches_selector(scope, "meta.interpolation") {
470
        Some("variable.other.readwrite")
471
    } else {
472
        None
473
    }
474
}
475
476
impl FromStr for Rgb {
477
    type Err = ParseRgbError;
478
479
    /// Parses a hex color of the form `#rrggbb` or `#rrggbbaa`.
480
    fn from_str(input: &str) -> Result<Self, Self::Err> {
481
        let hex = input.strip_prefix('#').ok_or(ParseRgbError)?;
482
        if hex.len() != 6 && hex.len() != 8 {
483
            return Err(ParseRgbError);
484
        }
485
        let mut r = u8::from_str_radix(&hex[0..2], 16).map_err(|_| ParseRgbError)?;
486
        let mut g = u8::from_str_radix(&hex[2..4], 16).map_err(|_| ParseRgbError)?;
487
        let mut b = u8::from_str_radix(&hex[4..6], 16).map_err(|_| ParseRgbError)?;
488
        if hex.len() == 8 {
489
            let alpha = u8::from_str_radix(&hex[6..8], 16).map_err(|_| ParseRgbError)?;
490
            r = blend_alpha(r, alpha);
491
            g = blend_alpha(g, alpha);
492
            b = blend_alpha(b, alpha);
493
        }
494
        Ok(Self { r, g, b })
495
    }
496
}
497
498
/// Blends one foreground channel with alpha over a black background.
499
fn blend_alpha(channel: u8, alpha: u8) -> u8 {
500
    ((u16::from(channel) * u16::from(alpha) + 127) / 255) as u8
501
}
502
503
impl FontStyle {
504
    /// Bold text.
505
    pub const BOLD: Self = Self(1 << 0);
506
    /// Italic text.
507
    pub const ITALIC: Self = Self(1 << 1);
508
    /// Underlined text.
509
    pub const UNDERLINE: Self = Self(1 << 2);
510
    /// Strikethrough text.
511
    pub const STRIKETHROUGH: Self = Self(1 << 3);
512
513
    /// Returns an empty font-style set.
514
    pub const fn empty() -> Self {
515
        Self(0)
516
    }
517
518
    /// Returns true when all flags in `other` are set.
519
    pub const fn contains(self, other: Self) -> bool {
520
        (self.0 & other.0) == other.0
521
    }
522
523
    /// Adds all flags from `other`.
524
    pub fn insert(&mut self, other: Self) {
525
        self.0 |= other.0;
526
    }
527
}
528
529
impl RuleStyle {
530
    /// Empty theme-rule style with no settings.
531
    const NONE: Self = Self {
532
        foreground: None,
533
        font_style: None,
534
    };
535
536
    /// Builds a theme-rule style from raw TextMate settings.
537
    fn from_raw(raw: &RawStyle) -> Self {
538
        Self {
539
            foreground: raw
540
                .foreground
541
                .as_ref()
542
                .and_then(|foreground| foreground.parse().ok()),
543
            font_style: raw
544
                .font_style
545
                .as_ref()
546
                .map(|flags| flags.parse().unwrap_or_else(|error| match error {})),
547
        }
548
    }
549
550
    /// Returns `self` overlaid on another theme-rule style.
551
    fn merge(self, base: Self) -> Self {
552
        Self {
553
            foreground: self.foreground.or(base.foreground),
554
            font_style: self.font_style.or(base.font_style),
555
        }
556
    }
557
558
    /// Applies this theme-rule style over a fully resolved style.
559
    fn apply_to(self, base: Style) -> Style {
560
        Style {
561
            foreground: self.foreground.or(base.foreground),
562
            font_style: self.font_style.unwrap_or(base.font_style),
563
        }
564
    }
565
}
566
567
impl FromStr for FontStyle {
568
    type Err = Infallible;
569
570
    /// Parses a space-separated list of TextMate font-style flags.
571
    fn from_str(input: &str) -> Result<Self, Self::Err> {
572
        let mut style = Self::empty();
573
        for flag in input.split_whitespace() {
574
            match flag {
575
                "bold" => style.insert(Self::BOLD),
576
                "italic" => style.insert(Self::ITALIC),
577
                "underline" => style.insert(Self::UNDERLINE),
578
                "strikethrough" => style.insert(Self::STRIKETHROUGH),
579
                _ => {}
580
            }
581
        }
582
        Ok(style)
583
    }
584
}
585
586
impl Style {
587
    /// Empty style with no foreground color or font flags.
588
    pub const NONE: Self = Self {
589
        foreground: None,
590
        font_style: FontStyle::empty(),
591
    };
592
593
    /// Returns this style with a foreground color.
594
    pub const fn fg(mut self, color: Rgb) -> Self {
595
        self.foreground = Some(color);
596
        self
597
    }
598
599
    /// Returns this style with bold enabled.
600
    pub fn bold(mut self) -> Self {
601
        self.font_style.insert(FontStyle::BOLD);
602
        self
603
    }
604
605
    /// Returns this style with italic enabled.
606
    pub fn italic(mut self) -> Self {
607
        self.font_style.insert(FontStyle::ITALIC);
608
        self
609
    }
610
611
    /// Returns this style with underline enabled.
612
    pub fn underline(mut self) -> Self {
613
        self.font_style.insert(FontStyle::UNDERLINE);
614
        self
615
    }
616
617
    /// Returns this style with strikethrough enabled.
618
    pub fn strikethrough(mut self) -> Self {
619
        self.font_style.insert(FontStyle::STRIKETHROUGH);
620
        self
621
    }
622
}