//! Theme compilation and style-span generation. //! //! Themes resolve TextMate-style selectors into compact [`Style`] values, then //! apply those styles to token scope spans one line at a time. The hot paths //! reuse caller-owned output buffers so editors can restyle visible text without //! allocating for every token. use std::cmp::Reverse; use std::{convert::Infallible, str::FromStr}; use crate::Error; use crate::grammar::{Grammar, ScopeId, ScopeSpan}; use crate::raw::{RawStyle, RawTheme}; use crate::util::{next_char_boundary, previous_char_boundary, trim_line_end}; /// Immutable compiled theme data. #[derive(Debug)] pub struct Theme { /// Theme name. pub name: String, /// Default style for unscoped text. pub default: Style, /// Compiled selector rules. rules: Vec, } /// One selector-to-style rule compiled from a theme. #[derive(Debug)] struct ThemeRule { /// TextMate-style scope selector matched against token scopes. selector: String, /// Selector components ordered from parent scopes to current scope. parts: Vec, /// Style applied when the selector matches. style: RuleStyle, } /// Per-line scratch buffer used while applying a theme. #[derive(Debug, Default)] pub(crate) struct StyleScratch { /// Theme and grammar identity this scratch cache belongs to. context: Option, /// Sorted byte boundaries that split a line into uniformly styled segments. boundaries: Vec, /// Uniformly styled segments for the current line. segments: Vec, /// Scope spans covering the current segment. covering: Vec, /// Scope stack for the current segment. stack: Vec, /// Cached style results for repeated scope stacks. styles: Vec, } /// Byte range for one fully resolved style segment. #[derive(Clone, Copy, Debug, Eq, PartialEq)] struct Segment { /// Start byte in the line. start: usize, /// End byte in the line. end: usize, } /// Identity of the immutable inputs used by style scratch caches. #[derive(Clone, Copy, Debug, Eq, PartialEq)] struct StyleScratchContext { /// Theme object address. theme: usize, /// Grammar object address. grammar: usize, } /// Cached style result for one ordered scope stack. #[derive(Clone, Debug, Eq, PartialEq)] struct StyleStackEntry { /// Ordered scopes covering a segment. stack: Vec, /// The most specific scope covering this styled span, if any. scope: Option, /// Resolved style. style: Style, } /// Resolved style and selector score for one scope. #[derive(Clone, Copy, Debug, Eq, PartialEq)] struct ScopeStyle { /// Resolved style. style: RuleStyle, /// Length of the most specific matched selector, or zero for the default. score: usize, } /// Partially specified style compiled from one theme rule. #[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] struct RuleStyle { /// Optional foreground color. foreground: Option, /// Optional font-style override. font_style: Option, } /// Fully styled span produced by applying a [`Theme`] to scope spans. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub struct StyleSpan { /// Start byte in the line. pub start: usize, /// End byte in the line. pub end: usize, /// The most specific scope covering this styled span, if any. pub scope: Option, /// Resolved style. pub style: Style, } /// RGB color parsed from a theme. #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub struct Rgb { /// Red channel. pub r: u8, /// Green channel. pub g: u8, /// Blue channel. pub b: u8, } /// Error returned when parsing an RGB color. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub struct ParseRgbError; /// Bitset of font style flags. #[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)] pub struct FontStyle(u8); /// Resolved style for a token. #[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)] pub struct Style { /// Optional foreground color. pub foreground: Option, /// Font style flags. pub font_style: FontStyle, } impl Theme { /// Compiles a raw theme. pub fn compile(raw: &RawTheme) -> Self { let mut default = Style::NONE; let mut rules = Vec::new(); let raw_rules = if raw.token_colors.is_empty() { &raw.settings } else { &raw.token_colors }; for rule in raw_rules { let selectors = rule.scope_selectors(); if selectors.is_empty() { if let Some(foreground) = &rule.settings.foreground { default.foreground = foreground.parse().ok(); } if let Some(flags) = &rule.settings.font_style { default.font_style = flags.parse().unwrap_or_else(|error| match error {}); } } else { let style = RuleStyle::from_raw(&rule.settings); rules.extend( selectors .into_iter() .map(|selector| ThemeRule::new(selector, style)), ); } } Self { name: raw.name.clone(), default, rules, } } /// Parses and compiles a theme from JSON. pub fn parse(input: &str) -> Result { input.parse() } /// Resolves a style for a scope string. /// /// The most specific selector wins, with ties broken by longer selectors. pub fn style_for_scope(&self, scope: &str) -> Style { let stack = scope.split_whitespace().collect::>(); let Some((scope, parents)) = stack.split_last() else { return self.default; }; self.match_scope(scope, parents) .style .apply_to(self.default) } /// Applies this theme to scope spans and returns a freshly allocated vector. pub fn style_spans( &self, grammar: &Grammar, line: &str, scopes: &[ScopeSpan], ) -> Vec { let mut scratch = StyleScratch::default(); let mut output = Vec::new(); self.style_line_into(grammar, line, scopes, &mut scratch, &mut output); output } /// Applies this theme one line at a time using caller-owned scratch storage. pub(crate) fn style_line_into( &self, grammar: &Grammar, line: &str, scopes: &[ScopeSpan], scratch: &mut StyleScratch, output: &mut Vec, ) { output.clear(); let line = trim_line_end(line); if line.is_empty() { return; } scratch.prepare(self, grammar); scratch.collect_boundaries(line, scopes); for index in 0..scratch.segment_count() { let segment = scratch.segment(index); output.push(self.style_stack_segment(grammar, scopes, scratch, segment)); } } /// Resolves one segment using TextMate-style scope stack matching. fn style_stack_segment( &self, grammar: &Grammar, scopes: &[ScopeSpan], scratch: &mut StyleScratch, segment: Segment, ) -> StyleSpan { scratch.collect_covering(segment, scopes); if let Some(entry) = scratch.cached_stack() { return segment.styled(entry.scope, entry.style); } let mut style = self.root_style(grammar); let mut scope = None; let mut parents = vec![grammar.scope_name.as_str()]; for span in scratch.covering() { let Some(name) = grammar.scopes.get(span.scope.index()) else { continue; }; let matched = self.match_scope(name, &parents); if matched.score > 0 { style = matched.style.apply_to(style); scope = Some(span.scope); } else if scope.is_none() { scope = Some(span.scope); } parents.push(name); } scratch.insert_cached_stack(scope, style); segment.styled(scope, style) } /// Returns the base style for the grammar root scope. fn root_style(&self, grammar: &Grammar) -> Style { self.match_scope(&grammar.scope_name, &[]) .style .apply_to(self.default) } /// Returns the strongest rule matching one current scope and its parents. fn match_scope(&self, scope: &str, parents: &[&str]) -> ScopeStyle { let mut style = RuleStyle::NONE; let mut best = 0; for scope in [Some(scope), fallback_scope(scope)] { let Some(scope) = scope else { continue }; for rule in &self.rules { let score = rule.match_score(scope, parents); if score > 0 && score >= best { best = score; style = rule.style.merge(style); } } } ScopeStyle { style, score: best } } } impl FromStr for Theme { type Err = Error; /// Parses and compiles a theme from JSON. fn from_str(input: &str) -> Result { let raw = RawTheme::from_str(input)?; Ok(Self::compile(&raw)) } } impl ThemeRule { /// Creates a compiled theme rule. fn new(selector: String, style: RuleStyle) -> Self { let parts = selector .split_whitespace() .map(ToOwned::to_owned) .collect::>(); Self { selector, parts, style, } } /// Returns this rule's selector score for a scope stack. fn match_score(&self, scope: &str, parents: &[&str]) -> usize { let Some(current) = self.parts.last() else { return 0; }; if !scope_matches_selector(scope, current) { return 0; } let mut parent = parents.len(); for selector in self.parts[..self.parts.len().saturating_sub(1)] .iter() .rev() { let mut matched = false; while parent > 0 { parent -= 1; if scope_matches_selector(parents[parent], selector) { matched = true; break; } } if !matched { return 0; } } self.selector.len() } } /// Returns whether a single concrete scope matches one selector component. fn scope_matches_selector(scope: &str, selector: &str) -> bool { scope == selector || (scope.len() > selector.len() && scope.starts_with(selector) && scope.as_bytes().get(selector.len()) == Some(&b'.')) } impl StyleScratch { /// Clears per-line scratch storage while retaining allocations. pub(crate) fn clear_line(&mut self) { self.boundaries.clear(); self.segments.clear(); self.covering.clear(); self.stack.clear(); } /// Prepares scratch caches for one immutable theme and grammar pair. fn prepare(&mut self, theme: &Theme, grammar: &Grammar) { let context = StyleScratchContext { theme: theme as *const Theme as usize, grammar: grammar as *const Grammar as usize, }; if self.context == Some(context) { return; } self.context = Some(context); self.styles.clear(); } /// Collects sorted byte boundaries for the style segments in a line. fn collect_boundaries(&mut self, line: &str, scopes: &[ScopeSpan]) { self.boundaries.clear(); self.boundaries.push(0); self.boundaries.push(line.len()); for span in scopes { let start = next_char_boundary(line, span.start); let end = previous_char_boundary(line, span.end); if start < end { self.boundaries.push(start); self.boundaries.push(end); } } self.boundaries.sort_unstable(); self.boundaries.dedup(); self.segments.clear(); self.segments .extend(self.boundaries.windows(2).filter_map(|window| { let [start, end] = *window else { return None; }; (start < end).then_some(Segment { start, end }) })); } /// Returns how many segments are in the current line. fn segment_count(&self) -> usize { self.segments.len() } /// Returns one segment by index. fn segment(&self, index: usize) -> Segment { self.segments[index] } /// Collects ordered scope spans covering a segment. fn collect_covering(&mut self, segment: Segment, spans: &[ScopeSpan]) { self.covering.clear(); self.stack.clear(); self.covering.extend( spans .iter() .copied() .filter(|span| span.start <= segment.start && span.end >= segment.end), ); self.covering .sort_by_key(|span| (Reverse(span.end - span.start), span.start, span.end)); self.stack .extend(self.covering.iter().map(|span| span.scope)); } /// Returns the cached style result for the current scope stack. fn cached_stack(&self) -> Option<&StyleStackEntry> { self.styles .iter() .find(|entry| entry.stack.as_slice() == self.stack.as_slice()) } /// Inserts a style result for the current scope stack. fn insert_cached_stack(&mut self, scope: Option, style: Style) { self.styles.push(StyleStackEntry { stack: self.stack.clone(), scope, style, }); } /// Returns the current segment's ordered covering scopes. fn covering(&self) -> &[ScopeSpan] { &self.covering } } impl Segment { /// Builds a styled span from this segment. fn styled(self, scope: Option, style: Style) -> StyleSpan { StyleSpan { start: self.start, end: self.end, scope, style, } } } /// Returns a theme selector fallback for scopes that Shiki emits as metadata. fn fallback_scope(scope: &str) -> Option<&'static str> { if scope_matches_selector(scope, "meta.attribute") { Some("attribute.name") } else if scope_matches_selector(scope, "meta.interpolation") { Some("variable.other.readwrite") } else { None } } impl FromStr for Rgb { type Err = ParseRgbError; /// Parses a hex color of the form `#rrggbb` or `#rrggbbaa`. fn from_str(input: &str) -> Result { let hex = input.strip_prefix('#').ok_or(ParseRgbError)?; if hex.len() != 6 && hex.len() != 8 { return Err(ParseRgbError); } let mut r = u8::from_str_radix(&hex[0..2], 16).map_err(|_| ParseRgbError)?; let mut g = u8::from_str_radix(&hex[2..4], 16).map_err(|_| ParseRgbError)?; let mut b = u8::from_str_radix(&hex[4..6], 16).map_err(|_| ParseRgbError)?; if hex.len() == 8 { let alpha = u8::from_str_radix(&hex[6..8], 16).map_err(|_| ParseRgbError)?; r = blend_alpha(r, alpha); g = blend_alpha(g, alpha); b = blend_alpha(b, alpha); } Ok(Self { r, g, b }) } } /// Blends one foreground channel with alpha over a black background. fn blend_alpha(channel: u8, alpha: u8) -> u8 { ((u16::from(channel) * u16::from(alpha) + 127) / 255) as u8 } impl FontStyle { /// Bold text. pub const BOLD: Self = Self(1 << 0); /// Italic text. pub const ITALIC: Self = Self(1 << 1); /// Underlined text. pub const UNDERLINE: Self = Self(1 << 2); /// Strikethrough text. pub const STRIKETHROUGH: Self = Self(1 << 3); /// Returns an empty font-style set. pub const fn empty() -> Self { Self(0) } /// Returns true when all flags in `other` are set. pub const fn contains(self, other: Self) -> bool { (self.0 & other.0) == other.0 } /// Adds all flags from `other`. pub fn insert(&mut self, other: Self) { self.0 |= other.0; } } impl RuleStyle { /// Empty theme-rule style with no settings. const NONE: Self = Self { foreground: None, font_style: None, }; /// Builds a theme-rule style from raw TextMate settings. fn from_raw(raw: &RawStyle) -> Self { Self { foreground: raw .foreground .as_ref() .and_then(|foreground| foreground.parse().ok()), font_style: raw .font_style .as_ref() .map(|flags| flags.parse().unwrap_or_else(|error| match error {})), } } /// Returns `self` overlaid on another theme-rule style. fn merge(self, base: Self) -> Self { Self { foreground: self.foreground.or(base.foreground), font_style: self.font_style.or(base.font_style), } } /// Applies this theme-rule style over a fully resolved style. fn apply_to(self, base: Style) -> Style { Style { foreground: self.foreground.or(base.foreground), font_style: self.font_style.unwrap_or(base.font_style), } } } impl FromStr for FontStyle { type Err = Infallible; /// Parses a space-separated list of TextMate font-style flags. fn from_str(input: &str) -> Result { let mut style = Self::empty(); for flag in input.split_whitespace() { match flag { "bold" => style.insert(Self::BOLD), "italic" => style.insert(Self::ITALIC), "underline" => style.insert(Self::UNDERLINE), "strikethrough" => style.insert(Self::STRIKETHROUGH), _ => {} } } Ok(style) } } impl Style { /// Empty style with no foreground color or font flags. pub const NONE: Self = Self { foreground: None, font_style: FontStyle::empty(), }; /// Returns this style with a foreground color. pub const fn fg(mut self, color: Rgb) -> Self { self.foreground = Some(color); self } /// Returns this style with bold enabled. pub fn bold(mut self) -> Self { self.font_style.insert(FontStyle::BOLD); self } /// Returns this style with italic enabled. pub fn italic(mut self) -> Self { self.font_style.insert(FontStyle::ITALIC); self } /// Returns this style with underline enabled. pub fn underline(mut self) -> Self { self.font_style.insert(FontStyle::UNDERLINE); self } /// Returns this style with strikethrough enabled. pub fn strikethrough(mut self) -> Self { self.font_style.insert(FontStyle::STRIKETHROUGH); self } }