highlight: Implement correct theme selector semantics

dbd571bf3bba1b5ef7eb10b83c895b6a742d8dba
Matches TextMate selector specificity and parent-scope behavior when resolving
token styles.
Alexis Sellier committed ago 1 parent 33f1ef83
crates/highlight/src/blob.rs +1 -8
6 6
//! spans instead of reparsing from the top of the file.
7 7
8 8
use std::ops::Range;
9 9
10 10
use crate::grammar::{Grammar, LineState, LineTokenizer, ScopeSpan};
11 -
use crate::theme::{StyleCache, StyleScratch, StyleSpan, Theme};
11 +
use crate::theme::{StyleScratch, StyleSpan, Theme};
12 12
use crate::util::line_starts;
13 13
14 14
/// Scratch space for highlighting one line without reallocating per call.
15 15
///
16 16
/// A buffer holds the latest tokenization and styling results so callers can
20 20
pub struct LineBuffer {
21 21
    /// Current scope spans.
22 22
    pub scopes: Vec<ScopeSpan>,
23 23
    /// Current style spans.
24 24
    pub styles: Vec<StyleSpan>,
25 -
    /// Cached resolved styles for the active grammar/theme pair.
26 -
    style_cache: StyleCache,
27 25
    /// Per-line scratch storage used when converting scope spans into style spans.
28 26
    style_scratch: StyleScratch,
29 27
}
30 28
31 29
/// Borrowed tokenization result for a line visited by a range highlighter.
101 99
    buffer: LineBuffer,
102 100
}
103 101
104 102
impl LineBuffer {
105 103
    /// Clears all buffered spans while retaining allocations.
106 -
    ///
107 -
    /// Cached scope styles are intentionally retained: they are keyed by `(theme,
108 -
    /// grammar, scope_count)` and stays valid across line resets.
109 104
    pub fn clear(&mut self) {
110 105
        self.scopes.clear();
111 106
        self.styles.clear();
112 107
        self.style_scratch.clear_line();
113 108
    }
128 123
        &'a mut self,
129 124
        grammar: &Grammar,
130 125
        theme: &Theme,
131 126
        line: &str,
132 127
    ) -> &'a [StyleSpan] {
133 -
        self.style_cache.refresh(theme, grammar);
134 128
        theme.style_line_into(
135 129
            grammar,
136 130
            line,
137 131
            &self.scopes,
138 -
            &self.style_cache,
139 132
            &mut self.style_scratch,
140 133
            &mut self.styles,
141 134
        );
142 135
        &self.styles
143 136
    }
crates/highlight/src/grammar/pattern.rs +7 -7
415 415
        &self,
416 416
        matched: &RegexMatch,
417 417
        captures: &Captures,
418 418
        spans: &mut Vec<ScopeSpan>,
419 419
    ) {
420 +
        if let Some(scope) = self.scope.id() {
421 +
            spans.push(ScopeSpan {
422 +
                start: matched.start,
423 +
                end: matched.end,
424 +
                scope,
425 +
            });
426 +
        }
420 427
        for (index, scope) in captures {
421 428
            if let Some(Some((start, end))) = matched.captures.get(*index)
422 429
                && start < end
423 430
            {
424 431
                spans.push(ScopeSpan {
426 433
                    end: *end,
427 434
                    scope: *scope,
428 435
                });
429 436
            }
430 437
        }
431 -
        if let Some(scope) = self.scope.id() {
432 -
            spans.push(ScopeSpan {
433 -
                start: matched.start,
434 -
                end: matched.end,
435 -
                scope,
436 -
            });
437 -
        }
438 438
        spans.sort_by_key(|span| (span.start, span.end));
439 439
    }
440 440
441 441
    /// Whether match-time regex captures must be retained.
442 442
    fn needs_match_captures(&self) -> bool {
crates/highlight/src/tests.rs +127 -0
328 328
    assert!("01020a".parse::<Rgb>().is_err());
329 329
    assert!("#01020".parse::<Rgb>().is_err());
330 330
    assert!("#01020x".parse::<Rgb>().is_err());
331 331
}
332 332
333 +
#[test]
334 +
fn rgb_blends_alpha_over_black() {
335 +
    assert_eq!(
336 +
        "#758575dd".parse::<Rgb>().unwrap(),
337 +
        Rgb {
338 +
            r: 101,
339 +
            g: 115,
340 +
            b: 101
341 +
        }
342 +
    );
343 +
}
344 +
333 345
#[test]
334 346
fn font_style_parses_textmate_flags() {
335 347
    let style = "bold italic underline strikethrough unknown"
336 348
        .parse::<FontStyle>()
337 349
        .unwrap();
340 352
    assert!(style.contains(FontStyle::ITALIC));
341 353
    assert!(style.contains(FontStyle::UNDERLINE));
342 354
    assert!(style.contains(FontStyle::STRIKETHROUGH));
343 355
}
344 356
357 +
#[test]
358 +
fn theme_matches_space_separated_scope_stacks() {
359 +
    let theme = r##"{
360 +
        "name":"Stack Theme",
361 +
        "settings":[
362 +
            {"settings":{"foreground":"#010203"}},
363 +
            {"scope":"storage","settings":{"foreground":"#111111"}},
364 +
            {"scope":"meta.attribute keyword","settings":{"foreground":"#222222"}}
365 +
        ]
366 +
    }"##
367 +
    .parse::<Theme>()
368 +
    .unwrap();
369 +
370 +
    assert_eq!(
371 +
        theme
372 +
            .style_for_scope("keyword.other.rust storage.type.rust")
373 +
            .foreground,
374 +
        Some(Rgb {
375 +
            r: 17,
376 +
            g: 17,
377 +
            b: 17
378 +
        })
379 +
    );
380 +
    assert_eq!(
381 +
        theme
382 +
            .style_for_scope("source.rust meta.attribute.rust keyword.other.rust")
383 +
            .foreground,
384 +
        Some(Rgb {
385 +
            r: 34,
386 +
            g: 34,
387 +
            b: 34
388 +
        })
389 +
    );
390 +
}
391 +
392 +
#[test]
393 +
fn theme_prefers_styled_scope_ties() {
394 +
    let grammar = Grammar::from_str(
395 +
        r#"{
396 +
            "name":"Test",
397 +
            "scopeName":"source.test",
398 +
            "patterns":[
399 +
                {
400 +
                    "match":"(x)",
401 +
                    "name":"meta.outer.test",
402 +
                    "captures":{"1":{"name":"variable.other.test"}}
403 +
                }
404 +
            ]
405 +
        }"#,
406 +
    )
407 +
    .unwrap();
408 +
    let theme = r##"{
409 +
        "name":"Tie Theme",
410 +
        "settings":[
411 +
            {"settings":{"foreground":"#010203"}},
412 +
            {"scope":"variable","settings":{"foreground":"#bd976a"}}
413 +
        ]
414 +
    }"##
415 +
    .parse::<Theme>()
416 +
    .unwrap();
417 +
    let spans = grammar.tokenize_line(&mut LineState::default(), "x");
418 +
    let styles = theme.style_spans(&grammar, "x", &spans);
419 +
420 +
    assert_eq!(styles.len(), 1);
421 +
    assert_eq!(
422 +
        styles[0].style.foreground,
423 +
        Some(Rgb {
424 +
            r: 189,
425 +
            g: 151,
426 +
            b: 106
427 +
        })
428 +
    );
429 +
}
430 +
431 +
#[test]
432 +
fn theme_font_style_reset_clears_parent_style() {
433 +
    let grammar = Grammar::from_str(
434 +
        r#"{
435 +
            "name":"Test",
436 +
            "scopeName":"source.test",
437 +
            "patterns":[
438 +
                {
439 +
                    "match":"(x)",
440 +
                    "name":"meta.outer.test",
441 +
                    "captures":{"1":{"name":"variable.other.test"}}
442 +
                }
443 +
            ]
444 +
        }"#,
445 +
    )
446 +
    .unwrap();
447 +
    let theme = r##"{
448 +
        "name":"Reset Theme",
449 +
        "settings":[
450 +
            {"settings":{"foreground":"#010203"}},
451 +
            {"scope":"source","settings":{"fontStyle":"italic","foreground":"#111111"}},
452 +
            {"scope":"meta.outer variable","settings":{"fontStyle":"","foreground":"#222222"}}
453 +
        ]
454 +
    }"##
455 +
    .parse::<Theme>()
456 +
    .unwrap();
457 +
    let spans = grammar.tokenize_line(&mut LineState::default(), "x");
458 +
    let styles = theme.style_spans(&grammar, "x", &spans);
459 +
460 +
    assert_eq!(styles.len(), 1);
461 +
    assert_eq!(styles[0].style.font_style, FontStyle::empty());
462 +
    assert_eq!(
463 +
        styles[0].style.foreground,
464 +
        Some(Rgb {
465 +
            r: 34,
466 +
            g: 34,
467 +
            b: 34
468 +
        })
469 +
    );
470 +
}
471 +
345 472
#[test]
346 473
fn theme_clamps_invalid_utf8_span_boundaries() {
347 474
    let grammar = test_grammar();
348 475
    let theme = test_theme();
349 476
    let keyword = grammar
crates/highlight/src/theme.rs +205 -102
1 1
//! Theme compilation and style-span generation.
2 2
//!
3 3
//! Themes resolve TextMate-style selectors into compact [`Style`] values, then
4 4
//! apply those styles to token scope spans one line at a time. The hot paths
5 -
//! reuse caller-owned output buffers and an optional per-grammar style cache so
6 -
//! editors can restyle visible text without allocating for every token.
5 +
//! reuse caller-owned output buffers so editors can restyle visible text without
6 +
//! allocating for every token.
7 7
8 8
use std::cmp::Reverse;
9 -
use std::{convert::Infallible, ptr, str::FromStr};
9 +
use std::{convert::Infallible, str::FromStr};
10 10
11 11
use crate::Error;
12 12
use crate::grammar::{Grammar, ScopeId, ScopeSpan};
13 13
use crate::raw::{RawStyle, RawTheme};
14 14
use crate::util::{next_char_boundary, previous_char_boundary, trim_line_end};
27 27
/// One selector-to-style rule compiled from a theme.
28 28
#[derive(Debug)]
29 29
struct ThemeRule {
30 30
    /// TextMate-style scope selector matched against token scopes.
31 31
    selector: String,
32 +
    /// Selector components ordered from parent scopes to current scope.
33 +
    parts: Vec<String>,
32 34
    /// Style applied when the selector matches.
33 -
    style: Style,
35 +
    style: RuleStyle,
34 36
}
35 37
36 -
/// Cached resolved styles indexed by a grammar's scope ids.
37 -
///
38 -
/// The cache is keyed by the addresses of the theme and grammar plus the
39 -
/// grammar's scope count, so a `LineBuffer` can be reused across many lines and
40 -
/// even different grammars without recomputing styles for every token.
41 -
#[derive(Debug, Default)]
42 -
pub(crate) struct StyleCache {
43 -
    /// Identity of the theme, grammar, and scope count this cache was built for.
44 -
    key: Option<CacheKey>,
45 -
    /// Resolved styles indexed by [`ScopeId`].
46 -
    styles: Vec<Style>,
47 -
}
48 -
49 -
/// Identity tuple used to validate a [`StyleCache`].
50 -
type CacheKey = (usize, usize, usize);
51 -
52 38
/// Per-line scratch buffer used while applying a theme.
53 39
#[derive(Debug, Default)]
54 40
pub(crate) struct StyleScratch {
55 41
    /// Sorted byte boundaries that split a line into uniformly styled segments.
56 42
    boundaries: Vec<usize>,
63 49
    start: usize,
64 50
    /// End byte in the line.
65 51
    end: usize,
66 52
}
67 53
54 +
/// Resolved style and selector score for one scope.
55 +
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
56 +
struct ScopeStyle {
57 +
    /// Resolved style.
58 +
    style: RuleStyle,
59 +
    /// Length of the most specific matched selector, or zero for the default.
60 +
    score: usize,
61 +
}
62 +
63 +
/// Partially specified style compiled from one theme rule.
64 +
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
65 +
struct RuleStyle {
66 +
    /// Optional foreground color.
67 +
    foreground: Option<Rgb>,
68 +
    /// Optional font-style override.
69 +
    font_style: Option<FontStyle>,
70 +
}
71 +
68 72
/// Fully styled span produced by applying a [`Theme`] to scope spans.
69 73
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
70 74
pub struct StyleSpan {
71 75
    /// Start byte in the line.
72 76
    pub start: usize,
109 113
impl Theme {
110 114
    /// Compiles a raw theme.
111 115
    pub fn compile(raw: &RawTheme) -> Self {
112 116
        let mut default = Style::NONE;
113 117
        let mut rules = Vec::new();
114 -
        let raw_rules = raw.settings.as_deref().or(raw.token_colors.as_deref());
118 +
        let raw_rules = raw.token_colors.as_deref().or(raw.settings.as_deref());
115 119
116 120
        for rule in raw_rules.unwrap_or_default() {
117 -
            let style = Style::from_raw(&rule.settings);
118 121
            let selectors = rule.scope_selectors();
119 122
            if selectors.is_empty() {
120 -
                default = style;
123 +
                if let Some(foreground) = &rule.settings.foreground {
124 +
                    default.foreground = foreground.parse().ok();
125 +
                }
126 +
                if let Some(flags) = &rule.settings.font_style {
127 +
                    default.font_style = flags.parse().unwrap_or_else(|error| match error {});
128 +
                }
121 129
            } else {
130 +
                let style = RuleStyle::from_raw(&rule.settings);
122 131
                rules.extend(
123 132
                    selectors
124 133
                        .into_iter()
125 -
                        .map(|selector| ThemeRule { selector, style }),
134 +
                        .map(|selector| ThemeRule::new(selector, style)),
126 135
                );
127 136
            }
128 137
        }
129 138
        Self {
130 139
            name: raw.name.clone(),
140 149
141 150
    /// Resolves a style for a scope string.
142 151
    ///
143 152
    /// The most specific selector wins, with ties broken by longer selectors.
144 153
    pub fn style_for_scope(&self, scope: &str) -> Style {
145 -
        let mut style = self.default;
146 -
        let mut best = 0;
147 -
        for rule in &self.rules {
148 -
            if rule.matches(scope) && rule.selector.len() >= best {
149 -
                best = rule.selector.len();
150 -
                style = rule.style.merge(style);
151 -
            }
152 -
        }
153 -
        style
154 +
        let stack = scope.split_whitespace().collect::<Vec<_>>();
155 +
        let Some((scope, parents)) = stack.split_last() else {
156 +
            return self.default;
157 +
        };
158 +
        self.match_scope(scope, parents)
159 +
            .style
160 +
            .apply_to(self.default)
154 161
    }
155 162
156 163
    /// Applies this theme to scope spans and returns a freshly allocated vector.
157 164
    pub fn style_spans(
158 165
        &self,
159 166
        grammar: &Grammar,
160 167
        line: &str,
161 168
        scopes: &[ScopeSpan],
162 169
    ) -> Vec<StyleSpan> {
163 -
        let mut cache = StyleCache::default();
164 170
        let mut scratch = StyleScratch::default();
165 171
        let mut output = Vec::new();
166 172
167 -
        cache.refresh(self, grammar);
168 -
        self.style_line_into(grammar, line, scopes, &cache, &mut scratch, &mut output);
173 +
        self.style_line_into(grammar, line, scopes, &mut scratch, &mut output);
169 174
        output
170 175
    }
171 176
172 177
    /// Applies this theme one line at a time using caller-owned scratch storage.
173 178
    pub(crate) fn style_line_into(
174 179
        &self,
175 180
        grammar: &Grammar,
176 181
        line: &str,
177 182
        scopes: &[ScopeSpan],
178 -
        cache: &StyleCache,
179 183
        scratch: &mut StyleScratch,
180 184
        output: &mut Vec<StyleSpan>,
181 185
    ) {
182 186
        output.clear();
183 187
        let line = trim_line_end(line);
185 189
            return;
186 190
        }
187 191
        scratch.collect_boundaries(line, scopes);
188 192
189 193
        for segment in scratch.segments() {
190 -
            output.push(self.style_segment(grammar, scopes, cache, segment));
194 +
            output.push(self.style_segment(grammar, scopes, segment));
191 195
        }
192 196
    }
193 197
194 198
    /// Resolves a single styled segment from its covering scope spans.
195 199
    fn style_segment(
196 200
        &self,
197 201
        grammar: &Grammar,
198 202
        scopes: &[ScopeSpan],
199 -
        cache: &StyleCache,
200 203
        segment: Segment,
201 204
    ) -> StyleSpan {
202 -
        let Some(span) = segment.best_covering(scopes, grammar) else {
203 -
            return segment.styled(None, self.default);
204 -
        };
205 -
        segment.styled(Some(span.scope), cache.style_for(span.scope))
205 +
        self.style_stack_segment(grammar, scopes, segment)
206 +
    }
207 +
208 +
    /// Resolves one segment using TextMate-style scope stack matching.
209 +
    fn style_stack_segment(
210 +
        &self,
211 +
        grammar: &Grammar,
212 +
        scopes: &[ScopeSpan],
213 +
        segment: Segment,
214 +
    ) -> StyleSpan {
215 +
        let mut style = self
216 +
            .match_scope(&grammar.scope_name, &[])
217 +
            .style
218 +
            .apply_to(self.default);
219 +
        let mut scope = None;
220 +
        let mut stack = vec![grammar.scope_name.as_str()];
221 +
        let mut covering = segment.covering(scopes);
222 +
223 +
        covering.sort_by_key(|span| (Reverse(span.end - span.start), span.start, span.end));
224 +
225 +
        for span in covering {
226 +
            let Some(name) = grammar.scopes.get(span.scope.index()) else {
227 +
                continue;
228 +
            };
229 +
            let matched = self.match_scope(name, &stack);
230 +
            if matched.score > 0 {
231 +
                style = matched.style.apply_to(style);
232 +
                scope = Some(span.scope);
233 +
            } else if scope.is_none() {
234 +
                scope = Some(span.scope);
235 +
            }
236 +
            stack.push(name);
237 +
        }
238 +
        segment.styled(scope, style)
239 +
    }
240 +
241 +
    /// Returns the strongest rule matching one current scope and its parents.
242 +
    fn match_scope(&self, scope: &str, parents: &[&str]) -> ScopeStyle {
243 +
        let mut style = RuleStyle::NONE;
244 +
        let mut best = 0;
245 +
246 +
        for scope in [Some(scope), fallback_scope(scope)] {
247 +
            let Some(scope) = scope else { continue };
248 +
            for rule in &self.rules {
249 +
                let score = rule.match_score(scope, parents);
250 +
                if score > 0 && score >= best {
251 +
                    best = score;
252 +
                    style = rule.style.merge(style);
253 +
                }
254 +
            }
255 +
        }
256 +
        ScopeStyle { style, score: best }
206 257
    }
207 258
}
208 259
209 260
impl FromStr for Theme {
210 261
    type Err = Error;
215 266
        Ok(Self::compile(&raw))
216 267
    }
217 268
}
218 269
219 270
impl ThemeRule {
220 -
    /// Returns whether this rule's selector applies to a concrete scope.
221 -
    fn matches(&self, scope: &str) -> bool {
222 -
        scope == self.selector
223 -
            || (scope.len() > self.selector.len()
224 -
                && scope.starts_with(&self.selector)
225 -
                && scope.as_bytes().get(self.selector.len()) == Some(&b'.'))
271 +
    /// Creates a compiled theme rule.
272 +
    fn new(selector: String, style: RuleStyle) -> Self {
273 +
        let parts = selector
274 +
            .split_whitespace()
275 +
            .map(ToOwned::to_owned)
276 +
            .collect::<Vec<_>>();
277 +
        Self {
278 +
            selector,
279 +
            parts,
280 +
            style,
281 +
        }
226 282
    }
227 -
}
228 283
229 -
impl StyleCache {
230 -
    /// Refreshes cached scope styles for a theme and grammar when needed.
231 -
    pub(crate) fn refresh(&mut self, theme: &Theme, grammar: &Grammar) {
232 -
        let key = (
233 -
            ptr::from_ref(theme).addr(),
234 -
            ptr::from_ref(grammar).addr(),
235 -
            grammar.scopes.len(),
236 -
        );
237 -
        if self.key == Some(key) {
238 -
            return;
284 +
    /// Returns this rule's selector score for a scope stack.
285 +
    fn match_score(&self, scope: &str, parents: &[&str]) -> usize {
286 +
        let Some(current) = self.parts.last() else {
287 +
            return 0;
288 +
        };
289 +
        if !scope_matches_selector(scope, current) {
290 +
            return 0;
291 +
        }
292 +
        let mut parent = parents.len();
293 +
        for selector in self.parts[..self.parts.len().saturating_sub(1)]
294 +
            .iter()
295 +
            .rev()
296 +
        {
297 +
            let mut matched = false;
298 +
            while parent > 0 {
299 +
                parent -= 1;
300 +
                if scope_matches_selector(parents[parent], selector) {
301 +
                    matched = true;
302 +
                    break;
303 +
                }
304 +
            }
305 +
            if !matched {
306 +
                return 0;
307 +
            }
239 308
        }
240 -
        self.styles.clear();
241 -
        self.styles.extend(
242 -
            grammar
243 -
                .scopes
244 -
                .iter()
245 -
                .map(|scope| theme.style_for_scope(scope)),
246 -
        );
247 -
        self.key = Some(key);
309 +
        self.selector.len()
248 310
    }
311 +
}
249 312
250 -
    /// Returns the cached style for an interned scope id.
251 -
    fn style_for(&self, scope: ScopeId) -> Style {
252 -
        self.styles
253 -
            .get(scope.index())
254 -
            .copied()
255 -
            .unwrap_or(Style::NONE)
256 -
    }
313 +
/// Returns whether a single concrete scope matches one selector component.
314 +
fn scope_matches_selector(scope: &str, selector: &str) -> bool {
315 +
    scope == selector
316 +
        || (scope.len() > selector.len()
317 +
            && scope.starts_with(selector)
318 +
            && scope.as_bytes().get(selector.len()) == Some(&b'.'))
257 319
}
258 320
259 321
impl StyleScratch {
260 322
    /// Clears per-line scratch storage while retaining allocations.
261 323
    pub(crate) fn clear_line(&mut self) {
300 362
            scope,
301 363
            style,
302 364
        }
303 365
    }
304 366
305 -
    /// Picks the smallest scope span covering this segment, breaking ties by selector specificity.
306 -
    fn best_covering<'a>(self, spans: &'a [ScopeSpan], grammar: &Grammar) -> Option<&'a ScopeSpan> {
367 +
    /// Returns scopes covering this segment.
368 +
    fn covering(self, spans: &[ScopeSpan]) -> Vec<&ScopeSpan> {
307 369
        spans
308 370
            .iter()
309 371
            .filter(|span| span.start <= self.start && span.end >= self.end)
310 -
            .min_by_key(|span| {
311 -
                let scope_len = grammar
312 -
                    .scopes
313 -
                    .get(span.scope.index())
314 -
                    .map_or(0, String::len);
315 -
                (span.end - span.start, Reverse(scope_len))
316 -
            })
372 +
            .collect()
373 +
    }
374 +
}
375 +
376 +
/// Returns a theme selector fallback for scopes that Shiki emits as metadata.
377 +
fn fallback_scope(scope: &str) -> Option<&'static str> {
378 +
    if scope_matches_selector(scope, "meta.attribute") {
379 +
        Some("attribute.name")
380 +
    } else if scope_matches_selector(scope, "meta.interpolation") {
381 +
        Some("variable.other.readwrite")
382 +
    } else {
383 +
        None
317 384
    }
318 385
}
319 386
320 387
impl FromStr for Rgb {
321 388
    type Err = ParseRgbError;
322 389
323 -
    /// Parses a six-digit hex color of the form `#rrggbb`.
390 +
    /// Parses a hex color of the form `#rrggbb` or `#rrggbbaa`.
324 391
    fn from_str(input: &str) -> Result<Self, Self::Err> {
325 392
        let hex = input.strip_prefix('#').ok_or(ParseRgbError)?;
326 -
        if hex.len() != 6 {
393 +
        if hex.len() != 6 && hex.len() != 8 {
327 394
            return Err(ParseRgbError);
328 395
        }
329 -
        let r = u8::from_str_radix(&hex[0..2], 16).map_err(|_| ParseRgbError)?;
330 -
        let g = u8::from_str_radix(&hex[2..4], 16).map_err(|_| ParseRgbError)?;
331 -
        let b = u8::from_str_radix(&hex[4..6], 16).map_err(|_| ParseRgbError)?;
332 -
396 +
        let mut r = u8::from_str_radix(&hex[0..2], 16).map_err(|_| ParseRgbError)?;
397 +
        let mut g = u8::from_str_radix(&hex[2..4], 16).map_err(|_| ParseRgbError)?;
398 +
        let mut b = u8::from_str_radix(&hex[4..6], 16).map_err(|_| ParseRgbError)?;
399 +
        if hex.len() == 8 {
400 +
            let alpha = u8::from_str_radix(&hex[6..8], 16).map_err(|_| ParseRgbError)?;
401 +
            r = blend_alpha(r, alpha);
402 +
            g = blend_alpha(g, alpha);
403 +
            b = blend_alpha(b, alpha);
404 +
        }
333 405
        Ok(Self { r, g, b })
334 406
    }
335 407
}
336 408
409 +
/// Blends one foreground channel with alpha over a black background.
410 +
fn blend_alpha(channel: u8, alpha: u8) -> u8 {
411 +
    ((u16::from(channel) * u16::from(alpha) + 127) / 255) as u8
412 +
}
413 +
337 414
impl FontStyle {
338 415
    /// Bold text.
339 416
    pub const BOLD: Self = Self(1 << 0);
340 417
    /// Italic text.
341 418
    pub const ITALIC: Self = Self(1 << 1);
358 435
    pub fn insert(&mut self, other: Self) {
359 436
        self.0 |= other.0;
360 437
    }
361 438
}
362 439
440 +
impl RuleStyle {
441 +
    /// Empty theme-rule style with no settings.
442 +
    const NONE: Self = Self {
443 +
        foreground: None,
444 +
        font_style: None,
445 +
    };
446 +
447 +
    /// Builds a theme-rule style from raw TextMate settings.
448 +
    fn from_raw(raw: &RawStyle) -> Self {
449 +
        Self {
450 +
            foreground: raw
451 +
                .foreground
452 +
                .as_ref()
453 +
                .and_then(|foreground| foreground.parse().ok()),
454 +
            font_style: raw
455 +
                .font_style
456 +
                .as_ref()
457 +
                .map(|flags| flags.parse().unwrap_or_else(|error| match error {})),
458 +
        }
459 +
    }
460 +
461 +
    /// Returns `self` overlaid on another theme-rule style.
462 +
    fn merge(self, base: Self) -> Self {
463 +
        Self {
464 +
            foreground: self.foreground.or(base.foreground),
465 +
            font_style: self.font_style.or(base.font_style),
466 +
        }
467 +
    }
468 +
469 +
    /// Applies this theme-rule style over a fully resolved style.
470 +
    fn apply_to(self, base: Style) -> Style {
471 +
        Style {
472 +
            foreground: self.foreground.or(base.foreground),
473 +
            font_style: self.font_style.unwrap_or(base.font_style),
474 +
        }
475 +
    }
476 +
}
477 +
363 478
impl FromStr for FontStyle {
364 479
    type Err = Infallible;
365 480
366 481
    /// Parses a space-separated list of TextMate font-style flags.
367 482
    fn from_str(input: &str) -> Result<Self, Self::Err> {
384 499
    pub const NONE: Self = Self {
385 500
        foreground: None,
386 501
        font_style: FontStyle::empty(),
387 502
    };
388 503
389 -
    /// Builds a runtime style from raw TextMate settings.
390 -
    fn from_raw(raw: &RawStyle) -> Self {
391 -
        let mut style = Self::NONE;
392 -
        if let Some(foreground) = &raw.foreground {
393 -
            style.foreground = foreground.parse().ok();
394 -
        }
395 -
        if let Some(flags) = &raw.font_style {
396 -
            style.font_style = flags.parse().unwrap_or_else(|error| match error {});
397 -
        }
398 -
        style
399 -
    }
400 -
401 504
    /// Returns `self` overlaid on `base`.
402 505
    pub fn merge(self, base: Self) -> Self {
403 506
        let mut font_style = base.font_style;
404 507
        font_style.insert(self.font_style);
405 508
        Self {