use ratatui::style::{Color, Modifier, Style};
use std::collections::HashMap;
use std::sync::{Arc, Mutex, OnceLock, RwLock};
use tree_sitter_highlight::{HighlightConfiguration, HighlightEvent, Highlighter};
use crate::theme::SyntaxPalette;
pub const HIGHLIGHT_NAMES: &[&str] = &[
"attribute",
"boolean",
"comment",
"constant",
"constant.builtin",
"constructor",
"function",
"function.builtin",
"function.macro",
"function.method",
"keyword",
"label",
"module",
"number",
"operator",
"property",
"punctuation",
"punctuation.bracket",
"punctuation.delimiter",
"punctuation.special",
"string",
"string.escape",
"string.special",
"tag",
"type",
"type.builtin",
"variable",
"variable.builtin",
"variable.parameter",
];
const fn rgb(r: u8, g: u8, b: u8) -> Color {
Color::Rgb(r, g, b)
}
const TSX_JSX_OVERLAY_QUERY: &str = r#"
(jsx_opening_element name: (_) @tag)
(jsx_closing_element name: (_) @tag)
(jsx_self_closing_element name: (_) @tag)
(jsx_attribute (property_identifier) @attribute)
"#;
const PYTHON_PARAM_OVERLAY_QUERY: &str = r#"
(parameters (identifier) @variable.parameter)
(lambda_parameters (identifier) @variable.parameter)
(typed_parameter (identifier) @variable.parameter)
(default_parameter name: (identifier) @variable.parameter)
(typed_default_parameter name: (identifier) @variable.parameter)
(parameters (list_splat_pattern (identifier) @variable.parameter))
(parameters (dictionary_splat_pattern (identifier) @variable.parameter))
(lambda_parameters (list_splat_pattern (identifier) @variable.parameter))
(lambda_parameters (dictionary_splat_pattern (identifier) @variable.parameter))
(typed_parameter (list_splat_pattern (identifier) @variable.parameter))
(typed_parameter (dictionary_splat_pattern (identifier) @variable.parameter))
"#;
const PYTHON_NAMESPACE_TYPE_OVERLAY_QUERY: &str = r#"
(import_statement name: (dotted_name (identifier) @module))
(import_statement name: (aliased_import (dotted_name (identifier) @module)))
(import_from_statement module_name: (dotted_name (identifier) @module))
(import_from_statement module_name: (relative_import (dotted_name (identifier) @module)))
((identifier) @type
(#match? @type "^[A-Z].*[a-z]"))
"#;
const PYTHON_LOCALS_QUERY: &str = r#"
[
(module)
(function_definition)
(lambda)
(class_definition)
(list_comprehension)
(set_comprehension)
(dictionary_comprehension)
(generator_expression)
] @local.scope
(parameters (identifier) @local.definition)
(lambda_parameters (identifier) @local.definition)
(typed_parameter (identifier) @local.definition)
(default_parameter name: (identifier) @local.definition)
(typed_default_parameter name: (identifier) @local.definition)
(parameters (list_splat_pattern (identifier) @local.definition))
(parameters (dictionary_splat_pattern (identifier) @local.definition))
(lambda_parameters (list_splat_pattern (identifier) @local.definition))
(lambda_parameters (dictionary_splat_pattern (identifier) @local.definition))
(assignment left: (identifier) @local.definition)
(assignment left: (pattern_list (identifier) @local.definition))
(assignment left: (tuple_pattern (identifier) @local.definition))
(for_statement left: (identifier) @local.definition)
(for_statement left: (pattern_list (identifier) @local.definition))
(for_statement left: (tuple_pattern (identifier) @local.definition))
(for_in_clause left: (identifier) @local.definition)
(for_in_clause left: (pattern_list (identifier) @local.definition))
(for_in_clause left: (tuple_pattern (identifier) @local.definition))
(named_expression (identifier) @local.definition)
(as_pattern alias: (as_pattern_target) @local.definition)
; Imported module names bind a name in scope, so body references to them
; (`pydantic` in `pydantic.BaseModel`) resolve here and inherit the def's
; `@module` colour instantly, the same way parameters do. The `.` anchor binds
; only the first segment of a dotted import (`import a.b.c` binds `a`); an
; aliased import binds its alias.
(import_statement name: (dotted_name . (identifier) @local.definition))
(import_statement name: (aliased_import alias: (identifier) @local.definition))
(identifier) @local.reference
"#;
const TS_LOCALS_OVERLAY_QUERY: &str = r#"
[
(statement_block)
(function_declaration)
(function_expression)
(arrow_function)
(method_definition)
] @local.scope
(arrow_function parameter: (identifier) @local.definition)
(variable_declarator name: (identifier) @local.definition)
(identifier) @local.reference
"#;
const JS_PARAM_LOCALS_OVERLAY_QUERY: &str = r#"
(formal_parameters (identifier) @local.definition)
(arrow_function parameter: (identifier) @local.definition)
(rest_pattern (identifier) @local.definition)
"#;
const JS_PARAM_HIGHLIGHTS_OVERLAY_QUERY: &str = r#"
(formal_parameters (identifier) @variable.parameter)
(arrow_function parameter: (identifier) @variable.parameter)
(rest_pattern (identifier) @variable.parameter)
"#;
const RUST_IDENTIFIER_OVERLAY_QUERY: &str = r#"(identifier) @variable"#;
const RUST_MODULE_OVERLAY_QUERY: &str = r#"
((scoped_identifier path: (identifier) @module)
(#match? @module "^[a-z]"))
((scoped_identifier path: (scoped_identifier name: (identifier) @module))
(#match? @module "^[a-z]"))
((scoped_type_identifier path: (identifier) @module)
(#match? @module "^[a-z]"))
((scoped_type_identifier path: (scoped_identifier name: (identifier) @module))
(#match? @module "^[a-z]"))
(enum_variant name: (identifier) @constant)
"#;
const RUST_USE_OVERLAY_QUERY: &str = r#"
((use_declaration argument: (scoped_identifier name: (identifier) @type))
(#match? @type "^[A-Z].*[a-z]"))
((use_list (identifier) @type)
(#match? @type "^[A-Z].*[a-z]"))
((use_as_clause alias: (identifier) @type)
(#match? @type "^[A-Z].*[a-z]"))
((scoped_use_list path: (identifier) @module)
(#match? @module "^[a-z]"))
((scoped_use_list path: (scoped_identifier name: (identifier) @module))
(#match? @module "^[a-z]"))
"#;
const RUST_LOCALS_QUERY: &str = r#"
[
(source_file)
(function_item)
(closure_expression)
(block)
] @local.scope
(parameter (identifier) @local.definition)
(closure_parameters (identifier) @local.definition)
(let_declaration pattern: (identifier) @local.definition)
(for_expression pattern: (identifier) @local.definition)
(identifier) @local.reference
"#;
static SYNTAX: RwLock<SyntaxPalette> = RwLock::new(SyntaxPalette::BASE16);
pub fn set_syntax_palette(palette: SyntaxPalette) {
*SYNTAX.write().unwrap() = palette;
}
fn style_for_name(name: &str) -> Style {
palette_style_for_name(&SYNTAX.read().unwrap(), name)
}
fn palette_style_for_name(p: &SyntaxPalette, name: &str) -> Style {
let fg = |c: (u8, u8, u8)| Style::default().fg(rgb(c.0, c.1, c.2));
match name {
"comment" => fg(p.comment).add_modifier(Modifier::ITALIC),
"keyword" | "label" => fg(p.keyword).add_modifier(Modifier::BOLD),
"string" | "string.escape" | "string.special" => fg(p.string),
"number" | "boolean" | "constant" | "constant.builtin" | "variable.parameter" => {
fg(p.constant)
}
"function" | "function.builtin" | "function.macro" | "function.method" | "constructor"
| "property" => fg(p.function),
"type" | "type.builtin" | "module" => fg(p.type_),
"attribute" | "tag" | "variable.builtin" => fg(p.tag),
"operator"
| "punctuation"
| "punctuation.bracket"
| "punctuation.delimiter"
| "punctuation.special"
| "variable" => fg(p.fg),
_ => fg(p.fg),
}
}
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub enum LangKind {
Rust,
Python,
JavaScript,
TypeScript,
Tsx,
Json,
Toml,
Yaml,
Markdown,
Go,
Html,
Css,
Bash,
C,
Cpp,
}
pub fn lang_for_extension(ext: &str) -> Option<LangKind> {
Some(match ext {
"rs" => LangKind::Rust,
"py" | "pyi" | "pyw" => LangKind::Python,
"js" | "mjs" | "cjs" | "jsx" => LangKind::JavaScript,
"ts" => LangKind::TypeScript,
"tsx" => LangKind::Tsx,
"json" | "jsonc" => LangKind::Json,
"toml" => LangKind::Toml,
"yaml" | "yml" => LangKind::Yaml,
"md" | "markdown" => LangKind::Markdown,
"go" => LangKind::Go,
"html" | "htm" => LangKind::Html,
"css" | "scss" | "sass" => LangKind::Css,
"sh" | "bash" | "zsh" => LangKind::Bash,
"c" | "h" => LangKind::C,
"cpp" | "cc" | "cxx" | "c++" | "C" | "hpp" | "hxx" | "h++" => LangKind::Cpp,
_ => return None,
})
}
fn build_config(kind: LangKind) -> Option<HighlightConfiguration> {
let mut cfg = match kind {
LangKind::Rust => {
let highlights = format!(
"{}\n{}\n{}\n{}",
RUST_IDENTIFIER_OVERLAY_QUERY,
tree_sitter_rust::HIGHLIGHTS_QUERY,
RUST_MODULE_OVERLAY_QUERY,
RUST_USE_OVERLAY_QUERY,
);
HighlightConfiguration::new(
tree_sitter_rust::LANGUAGE.into(),
"rust",
&highlights,
tree_sitter_rust::INJECTIONS_QUERY,
RUST_LOCALS_QUERY,
)
.ok()?
}
LangKind::Python => {
let combined = format!(
"{}\n{}\n{}",
tree_sitter_python::HIGHLIGHTS_QUERY,
PYTHON_PARAM_OVERLAY_QUERY,
PYTHON_NAMESPACE_TYPE_OVERLAY_QUERY,
);
HighlightConfiguration::new(
tree_sitter_python::LANGUAGE.into(),
"python",
&combined,
"",
PYTHON_LOCALS_QUERY,
)
.ok()?
}
LangKind::JavaScript => {
let locals = format!(
"{}\n{}",
JS_PARAM_LOCALS_OVERLAY_QUERY,
tree_sitter_javascript::LOCALS_QUERY,
);
let highlights = format!(
"{}\n{}",
tree_sitter_javascript::HIGHLIGHT_QUERY,
JS_PARAM_HIGHLIGHTS_OVERLAY_QUERY,
);
HighlightConfiguration::new(
tree_sitter_javascript::LANGUAGE.into(),
"javascript",
&highlights,
tree_sitter_javascript::INJECTIONS_QUERY,
&locals,
)
.ok()?
}
LangKind::TypeScript => {
let combined = format!(
"{}\n{}",
tree_sitter_javascript::HIGHLIGHT_QUERY,
tree_sitter_typescript::HIGHLIGHTS_QUERY,
);
let locals = format!(
"{}\n{}",
tree_sitter_typescript::LOCALS_QUERY,
TS_LOCALS_OVERLAY_QUERY,
);
HighlightConfiguration::new(
tree_sitter_typescript::LANGUAGE_TYPESCRIPT.into(),
"typescript",
&combined,
"",
&locals,
)
.ok()?
}
LangKind::Tsx => {
let combined = format!(
"{}\n{}\n{}",
tree_sitter_javascript::HIGHLIGHT_QUERY,
tree_sitter_typescript::HIGHLIGHTS_QUERY,
TSX_JSX_OVERLAY_QUERY,
);
let locals = format!(
"{}\n{}",
tree_sitter_typescript::LOCALS_QUERY,
TS_LOCALS_OVERLAY_QUERY,
);
HighlightConfiguration::new(
tree_sitter_typescript::LANGUAGE_TSX.into(),
"tsx",
&combined,
"",
&locals,
)
.ok()?
}
LangKind::Json => HighlightConfiguration::new(
tree_sitter_json::LANGUAGE.into(),
"json",
tree_sitter_json::HIGHLIGHTS_QUERY,
"",
"",
)
.ok()?,
LangKind::Toml => HighlightConfiguration::new(
tree_sitter_toml_ng::LANGUAGE.into(),
"toml",
tree_sitter_toml_ng::HIGHLIGHTS_QUERY,
"",
"",
)
.ok()?,
LangKind::Yaml => HighlightConfiguration::new(
tree_sitter_yaml::LANGUAGE.into(),
"yaml",
tree_sitter_yaml::HIGHLIGHTS_QUERY,
"",
"",
)
.ok()?,
LangKind::Markdown => HighlightConfiguration::new(
tree_sitter_md::LANGUAGE.into(),
"markdown",
tree_sitter_md::HIGHLIGHT_QUERY_BLOCK,
tree_sitter_md::INJECTION_QUERY_BLOCK,
"",
)
.ok()?,
LangKind::Go => HighlightConfiguration::new(
tree_sitter_go::LANGUAGE.into(),
"go",
tree_sitter_go::HIGHLIGHTS_QUERY,
"",
"",
)
.ok()?,
LangKind::Html => HighlightConfiguration::new(
tree_sitter_html::LANGUAGE.into(),
"html",
tree_sitter_html::HIGHLIGHTS_QUERY,
tree_sitter_html::INJECTIONS_QUERY,
"",
)
.ok()?,
LangKind::Css => HighlightConfiguration::new(
tree_sitter_css::LANGUAGE.into(),
"css",
tree_sitter_css::HIGHLIGHTS_QUERY,
"",
"",
)
.ok()?,
LangKind::Bash => HighlightConfiguration::new(
tree_sitter_bash::LANGUAGE.into(),
"bash",
tree_sitter_bash::HIGHLIGHT_QUERY,
"",
"",
)
.ok()?,
LangKind::C => HighlightConfiguration::new(
tree_sitter_c::LANGUAGE.into(),
"c",
tree_sitter_c::HIGHLIGHT_QUERY,
"",
"",
)
.ok()?,
LangKind::Cpp => HighlightConfiguration::new(
tree_sitter_cpp::LANGUAGE.into(),
"cpp",
tree_sitter_cpp::HIGHLIGHT_QUERY,
"",
"",
)
.ok()?,
};
cfg.configure(HIGHLIGHT_NAMES);
Some(cfg)
}
#[derive(Clone, Copy, Debug)]
pub struct HiSpan {
pub start: usize,
pub end: usize,
pub style: Style,
}
static SHARED_CONFIGS: OnceLock<Mutex<HashMap<LangKind, Arc<HighlightConfiguration>>>> =
OnceLock::new();
fn shared_config(kind: LangKind) -> Option<Arc<HighlightConfiguration>> {
let cache = SHARED_CONFIGS.get_or_init(|| Mutex::new(HashMap::new()));
if let Some(cfg) = cache.lock().unwrap().get(&kind) {
return Some(Arc::clone(cfg));
}
let built = Arc::new(build_config(kind)?);
let mut guard = cache.lock().unwrap();
Some(Arc::clone(guard.entry(kind).or_insert(built)))
}
pub fn prewarm_configs() {
for kind in [
LangKind::Rust,
LangKind::Python,
LangKind::TypeScript,
LangKind::Tsx,
LangKind::JavaScript,
] {
let _ = shared_config(kind);
}
}
pub struct LangRegistry {
_private: (),
}
impl Default for LangRegistry {
fn default() -> Self {
Self::new()
}
}
impl LangRegistry {
pub fn new() -> Self {
Self { _private: () }
}
pub fn get(&mut self, kind: LangKind) -> Option<Arc<HighlightConfiguration>> {
shared_config(kind)
}
}
pub fn highlight_text(
registry: &mut LangRegistry,
kind: LangKind,
text: &[u8],
line_starts: &[usize],
) -> Vec<Vec<HiSpan>> {
highlight_text_with_protected(registry, kind, text, line_starts).0
}
pub fn highlight_text_with_protected(
registry: &mut LangRegistry,
kind: LangKind,
text: &[u8],
line_starts: &[usize],
) -> (Vec<Vec<HiSpan>>, Vec<(usize, usize)>) {
let palette = *SYNTAX.read().unwrap();
highlight_text_with_palette(registry, kind, text, line_starts, &palette)
}
fn highlight_text_with_palette(
registry: &mut LangRegistry,
kind: LangKind,
text: &[u8],
line_starts: &[usize],
palette: &SyntaxPalette,
) -> (Vec<Vec<HiSpan>>, Vec<(usize, usize)>) {
let mut per_line: Vec<Vec<HiSpan>> = vec![Vec::new(); line_starts.len()];
let mut protected: Vec<(usize, usize)> = Vec::new();
let cfg = match registry.get(kind) {
Some(c) => c,
None => return (per_line, protected),
};
let mut hl = Highlighter::new();
let events = match hl.highlight(cfg.as_ref(), text, None, |_| None) {
Ok(e) => e,
Err(_) => return (per_line, protected),
};
let mut stack: Vec<usize> = Vec::new();
for ev in events {
match ev {
Ok(HighlightEvent::HighlightStart(h)) => stack.push(h.0),
Ok(HighlightEvent::HighlightEnd) => {
stack.pop();
}
Ok(HighlightEvent::Source { start, end }) => {
let name = match stack.last() {
Some(idx) => HIGHLIGHT_NAMES.get(*idx).copied().unwrap_or(""),
None => "",
};
if name.starts_with("string") || name.starts_with("comment") {
match protected.last_mut() {
Some(last) if last.1 >= start => last.1 = last.1.max(end),
_ => protected.push((start, end)),
}
}
let style = match stack.last() {
Some(_) => palette_style_for_name(palette, name),
None => palette_style_for_name(palette, ""),
};
project_range(start, end, style, line_starts, &mut per_line);
}
Err(_) => {}
}
}
(per_line, protected)
}
fn project_range(
mut start: usize,
end: usize,
style: Style,
line_starts: &[usize],
per_line: &mut [Vec<HiSpan>],
) {
if start >= end || line_starts.is_empty() {
return;
}
let mut line_idx = match line_starts.binary_search(&start) {
Ok(i) => i,
Err(i) => i.saturating_sub(1),
};
while start < end && line_idx < line_starts.len() {
let line_start = line_starts[line_idx];
let next_line_start = line_starts.get(line_idx + 1).copied().unwrap_or(usize::MAX);
let chunk_end = end.min(next_line_start);
let on_boundary = chunk_end == next_line_start && line_idx + 1 < line_starts.len();
let span_end_abs = if on_boundary && chunk_end > line_start {
chunk_end - 1
} else {
chunk_end
};
if span_end_abs > start {
per_line[line_idx].push(HiSpan {
start: start - line_start,
end: span_end_abs - line_start,
style,
});
}
start = chunk_end;
line_idx += 1;
}
}
fn semantic_style_for(token_type: &str) -> Option<Style> {
let capture = match token_type {
"parameter" | "selfParameter" | "clsParameter" => "variable.parameter",
"variable" => "variable",
"property" => "property",
"function" | "method" => "function",
"macro" => "function.macro",
"namespace" => "module",
"type" | "class" | "enum" | "interface" | "struct" | "typeParameter" => "type",
"enumMember" | "builtinConstant" => "constant",
"keyword" | "modifier" => "keyword",
"comment" => "comment",
"string" => "string",
"number" => "number",
"regexp" => "string.special",
"operator" => "operator",
"decorator" => "attribute",
"event" | "label" => "label",
_ => return None,
};
Some(style_for_name(capture))
}
pub fn decode_semantic_tokens(
data: &[u32],
token_type_names: &[String],
text: &[u8],
line_starts: &[usize],
) -> Vec<Vec<HiSpan>> {
let mut per_line: Vec<Vec<HiSpan>> = vec![Vec::new(); line_starts.len()];
let src = match std::str::from_utf8(text) {
Ok(s) => s,
Err(_) => return per_line,
};
let mut line: usize = 0;
let mut col_u16: u32 = 0;
for group in data.chunks_exact(5) {
let (delta_line, delta_start, length, ttype) = (group[0], group[1], group[2], group[3]);
if delta_line > 0 {
line += delta_line as usize;
col_u16 = delta_start;
} else {
col_u16 += delta_start;
}
if line >= line_starts.len() {
continue;
}
let name = match token_type_names.get(ttype as usize) {
Some(n) => n.as_str(),
None => continue,
};
let style = match semantic_style_for(name) {
Some(s) => s,
None => continue,
};
let line_start = line_starts[line];
let content_end = match line_starts.get(line + 1) {
Some(&next) => next.saturating_sub(1).max(line_start),
None => src.len(),
};
let line_str = &src[line_start..content_end];
if let Some((b0, b1)) = utf16_span_to_bytes(line_str, col_u16, length)
&& b1 > b0
{
per_line[line].push(HiSpan {
start: b0,
end: b1,
style,
});
}
}
per_line
}
fn utf16_span_to_bytes(line: &str, start_u16: u32, len_u16: u32) -> Option<(usize, usize)> {
let end_u16 = start_u16.checked_add(len_u16)?;
let mut u16_count: u32 = 0;
let mut byte = 0usize;
let mut b_start: Option<usize> = None;
let mut b_end: Option<usize> = None;
for ch in line.chars() {
if u16_count == start_u16 {
b_start = Some(byte);
}
if u16_count == end_u16 {
b_end = Some(byte);
break;
}
u16_count += ch.len_utf16() as u32;
byte += ch.len_utf8();
}
if u16_count == start_u16 {
b_start.get_or_insert(byte);
}
if u16_count == end_u16 {
b_end.get_or_insert(byte);
}
Some((b_start?, b_end?))
}
pub fn compute_line_starts(text: &[u8]) -> Vec<usize> {
let mut out = vec![0usize];
for (i, &b) in text.iter().enumerate() {
if b == b'\n' {
out.push(i + 1);
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn palette_style_resolves_each_role_against_the_theme() {
let one_dark = crate::theme::Theme::from_id("one-dark-pro").syntax();
assert_eq!(
palette_style_for_name(&one_dark, "keyword").fg,
Some(rgb(0xc6, 0x78, 0xdd))
);
assert!(
palette_style_for_name(&one_dark, "keyword")
.add_modifier
.contains(Modifier::BOLD)
);
assert_eq!(
palette_style_for_name(&one_dark, "string").fg,
Some(rgb(0x98, 0xc3, 0x79))
);
assert_eq!(
palette_style_for_name(&one_dark, "comment").fg,
Some(rgb(0x7f, 0x84, 0x8e))
);
assert!(
palette_style_for_name(&one_dark, "comment")
.add_modifier
.contains(Modifier::ITALIC)
);
assert_eq!(
palette_style_for_name(&one_dark, "variable.parameter").fg,
palette_style_for_name(&one_dark, "number").fg
);
assert_eq!(
palette_style_for_name(&SyntaxPalette::BASE16, "type").fg,
Some(rgb(0xeb, 0xcb, 0x8b))
);
}
fn py_color(src: &str, row: usize, needle: &str) -> Option<Color> {
let mut reg = LangRegistry::new();
let ls = compute_line_starts(src.as_bytes());
let h = highlight_text(&mut reg, LangKind::Python, src.as_bytes(), &ls);
let line = src.split('\n').nth(row)?;
let col = line.find(needle)?;
h[row]
.iter()
.find(|s| s.start <= col && col < s.end)
.and_then(|s| s.style.fg)
}
#[test]
fn highlight_python_colors_imported_classes_and_modules_to_match_ty() {
let yellow = rgb(0xeb, 0xcb, 0x8b);
let src = "import pydantic\n\
from anterior.lib_tasks.schema import Config\n\
\n\
def f() -> Config:\n\
return pydantic.BaseModel()\n";
assert_eq!(
py_color(src, 0, "pydantic"),
Some(yellow),
"import module name"
);
assert_eq!(
py_color(src, 1, "anterior"),
Some(yellow),
"from-import module head"
);
assert_eq!(
py_color(src, 1, "schema"),
Some(yellow),
"from-import module tail"
);
assert_eq!(
py_color(src, 1, "Config"),
Some(yellow),
"imported class name"
);
assert_eq!(
py_color(src, 3, "Config"),
Some(yellow),
"class as annotation"
);
assert_eq!(
py_color(src, 4, "pydantic"),
Some(yellow),
"module base in body"
);
assert_eq!(
py_color(src, 4, "BaseModel"),
Some(yellow),
"CamelCase attr ref"
);
}
#[test]
fn highlight_python_camelcase_overlay_excludes_all_caps_constants() {
let orange = rgb(0xd0, 0x87, 0x70);
let src = "MAX_SIZE = 300\n";
assert_eq!(py_color(src, 0, "MAX_SIZE"), Some(orange));
}
#[test]
fn highlight_c_produces_spans() {
let mut reg = LangRegistry::new();
let src = "int main() {\n return 0;\n}\n";
let line_starts = compute_line_starts(src.as_bytes());
let h = highlight_text(&mut reg, LangKind::C, src.as_bytes(), &line_starts);
assert!(
!h[0].is_empty(),
"line 0 of C source should have highlight spans"
);
}
#[test]
fn highlight_cpp_produces_spans() {
let mut reg = LangRegistry::new();
let src = "int main() {\n return 0;\n}\n";
let line_starts = compute_line_starts(src.as_bytes());
let h = highlight_text(&mut reg, LangKind::Cpp, src.as_bytes(), &line_starts);
assert!(
!h[0].is_empty(),
"line 0 of C++ source should have highlight spans"
);
}
#[test]
fn lang_for_extension_known() {
assert_eq!(lang_for_extension("rs"), Some(LangKind::Rust));
assert_eq!(lang_for_extension("py"), Some(LangKind::Python));
assert_eq!(lang_for_extension("ts"), Some(LangKind::TypeScript));
assert_eq!(lang_for_extension("tsx"), Some(LangKind::Tsx));
assert_eq!(lang_for_extension("js"), Some(LangKind::JavaScript));
assert_eq!(lang_for_extension("jsx"), Some(LangKind::JavaScript));
assert_eq!(lang_for_extension("json"), Some(LangKind::Json));
assert_eq!(lang_for_extension("toml"), Some(LangKind::Toml));
assert_eq!(lang_for_extension("yaml"), Some(LangKind::Yaml));
assert_eq!(lang_for_extension("yml"), Some(LangKind::Yaml));
assert_eq!(lang_for_extension("md"), Some(LangKind::Markdown));
assert_eq!(lang_for_extension("go"), Some(LangKind::Go));
assert_eq!(lang_for_extension("html"), Some(LangKind::Html));
assert_eq!(lang_for_extension("htm"), Some(LangKind::Html));
assert_eq!(lang_for_extension("css"), Some(LangKind::Css));
assert_eq!(lang_for_extension("scss"), Some(LangKind::Css));
assert_eq!(lang_for_extension("sh"), Some(LangKind::Bash));
assert_eq!(lang_for_extension("c"), Some(LangKind::C));
assert_eq!(lang_for_extension("h"), Some(LangKind::C));
assert_eq!(lang_for_extension("cpp"), Some(LangKind::Cpp));
assert_eq!(lang_for_extension("cc"), Some(LangKind::Cpp));
assert_eq!(lang_for_extension("cxx"), Some(LangKind::Cpp));
assert_eq!(lang_for_extension("hpp"), Some(LangKind::Cpp));
assert_eq!(lang_for_extension("hxx"), Some(LangKind::Cpp));
}
#[test]
fn lang_for_extension_unknown() {
assert_eq!(lang_for_extension("xyz"), None);
assert_eq!(lang_for_extension(""), None);
}
#[test]
fn line_starts_empty_input() {
assert_eq!(compute_line_starts(b""), vec![0]);
}
#[test]
fn line_starts_single_line_no_newline() {
assert_eq!(compute_line_starts(b"hello"), vec![0]);
}
#[test]
fn line_starts_multiple_lines() {
assert_eq!(compute_line_starts(b"a\nbb\nccc"), vec![0, 2, 5]);
}
#[test]
fn line_starts_trailing_newline() {
assert_eq!(compute_line_starts(b"a\nb\n"), vec![0, 2, 4]);
}
#[test]
fn line_starts_only_newlines() {
assert_eq!(compute_line_starts(b"\n\n\n"), vec![0, 1, 2, 3]);
}
#[test]
fn registry_caches_configs() {
let mut reg = LangRegistry::new();
assert!(reg.get(LangKind::Rust).is_some());
assert!(reg.get(LangKind::Rust).is_some());
}
#[test]
fn highlight_configs_are_shared_across_editors() {
prewarm_configs();
let mut a = LangRegistry::new();
let mut b = LangRegistry::new();
let ca = a.get(LangKind::Rust).expect("rust config");
let cb = b.get(LangKind::Rust).expect("rust config");
assert!(
Arc::ptr_eq(&ca, &cb),
"every editor must share one built highlight config"
);
}
#[test]
fn highlight_rust_produces_per_line_spans() {
let mut reg = LangRegistry::new();
let src = "fn main() {\n let x = 1;\n}\n";
let line_starts = compute_line_starts(src.as_bytes());
let highlights = highlight_text(&mut reg, LangKind::Rust, src.as_bytes(), &line_starts);
assert_eq!(highlights.len(), 4);
assert!(!highlights[0].is_empty(), "line 0 should have spans");
let line0_len = "fn main() {".len();
for sp in &highlights[0] {
assert!(
sp.start <= line0_len,
"span start {} > line len {}",
sp.start,
line0_len
);
assert!(
sp.end <= line0_len,
"span end {} > line len {}",
sp.end,
line0_len
);
assert!(sp.start <= sp.end);
}
}
#[test]
fn semantic_tokens_color_parameter_in_body() {
let src = "def f(x):\n return x\n";
let line_starts = compute_line_starts(src.as_bytes());
let legend = vec!["parameter".to_string(), "variable".to_string()];
let data: Vec<u32> = vec![
0, 6, 1, 0, 0, 1, 11, 1, 0, 0, ];
let spans = decode_semantic_tokens(&data, &legend, src.as_bytes(), &line_starts);
let param_fg = Some(rgb(0xd0, 0x87, 0x70));
let body = " return x";
let col = body.rfind('x').unwrap();
let span = spans[1]
.iter()
.find(|s| s.start <= col && col < s.end)
.expect("a semantic span should cover the body parameter `x`");
assert_eq!(
span.style.fg, param_fg,
"parameter referenced in the body should carry the parameter color"
);
}
#[test]
fn semantic_tokens_skip_unmapped_and_handle_unicode() {
let src = "x = \"é\" + ab\n"; let line_starts = compute_line_starts(src.as_bytes());
let legend = vec!["bogusType".to_string(), "variable".to_string()];
let data: Vec<u32> = vec![
0, 0, 1, 0, 0, 0, 10, 2, 1, 0, ];
let spans = decode_semantic_tokens(&data, &legend, src.as_bytes(), &line_starts);
assert_eq!(spans[0].len(), 1, "only the mapped token survives");
let byte_col = src.find("ab").unwrap();
let s = &spans[0][0];
assert_eq!(s.start, byte_col, "UTF-16 col converted to the right byte");
assert_eq!(s.end, byte_col + 2);
}
#[test]
fn highlight_python_colors_parameters() {
let mut reg = LangRegistry::new();
let src = "def f(text, n=1, *args, **kw):\n return text\n";
let line_starts = compute_line_starts(src.as_bytes());
let h = highlight_text(&mut reg, LangKind::Python, src.as_bytes(), &line_starts);
let param_fg = Some(rgb(0xd0, 0x87, 0x70));
let default_fg = Some(rgb(0xc0, 0xc5, 0xce));
let line0 = "def f(text, n=1, *args, **kw):";
for name in ["text", "n", "args", "kw"] {
let col = line0.find(name).expect("param in source");
let span = h[0]
.iter()
.find(|s| s.start <= col && col < s.end)
.unwrap_or_else(|| panic!("no span covers parameter `{name}`"));
assert_eq!(
span.style.fg, param_fg,
"parameter `{name}` should use the parameter color, not {:?}",
span.style.fg
);
assert_ne!(span.style.fg, default_fg);
}
}
#[test]
fn highlight_python_colors_parameter_references_in_body_via_locals() {
let mut reg = LangRegistry::new();
let src = "def f(text):\n return text + text\n";
let line_starts = compute_line_starts(src.as_bytes());
let h = highlight_text(&mut reg, LangKind::Python, src.as_bytes(), &line_starts);
let param_fg = Some(rgb(0xd0, 0x87, 0x70));
let default_fg = Some(rgb(0xc0, 0xc5, 0xce));
let line1 = " return text + text";
let first = line1.find("text").expect("first body ref");
let second = line1[first + 4..].find("text").expect("second body ref") + first + 4;
for col in [first, second] {
let span = h[1]
.iter()
.find(|s| s.start <= col && col < s.end)
.unwrap_or_else(|| panic!("no span covers body reference at col {col}"));
assert_eq!(
span.style.fg, param_fg,
"body parameter reference at col {col} should use the parameter colour, not {:?}",
span.style.fg
);
assert_ne!(span.style.fg, default_fg);
}
}
fn assert_body_param_ref_is_param_colored(lang: LangKind, src: &str, line1: &str) {
let mut reg = LangRegistry::new();
let line_starts = compute_line_starts(src.as_bytes());
let h = highlight_text(&mut reg, lang, src.as_bytes(), &line_starts);
let param_fg = Some(rgb(0xd0, 0x87, 0x70));
let default_fg = Some(rgb(0xc0, 0xc5, 0xce));
let first = line1.find("text").expect("first body ref");
let second = line1[first + 4..].find("text").expect("second body ref") + first + 4;
for col in [first, second] {
let span = h[1]
.iter()
.find(|s| s.start <= col && col < s.end)
.unwrap_or_else(|| panic!("{lang:?}: no span covers body reference at col {col}"));
assert_eq!(
span.style.fg, param_fg,
"{lang:?}: body parameter reference at col {col} should use the parameter colour, not {:?}",
span.style.fg
);
assert_ne!(span.style.fg, default_fg);
}
}
#[test]
fn highlight_typescript_colors_parameter_references_in_body_via_locals() {
assert_body_param_ref_is_param_colored(
LangKind::TypeScript,
"function f(text: string) {\n return text + text;\n}\n",
" return text + text;",
);
}
#[test]
fn highlight_tsx_colors_parameter_references_in_body_via_locals() {
assert_body_param_ref_is_param_colored(
LangKind::Tsx,
"function f(text: string) {\n return text + text;\n}\n",
" return text + text;",
);
}
#[test]
fn highlight_javascript_colors_parameter_references_in_body_via_locals() {
assert_body_param_ref_is_param_colored(
LangKind::JavaScript,
"function f(text) {\n return text + text;\n}\n",
" return text + text;",
);
}
#[test]
fn highlight_rust_colors_parameter_references_in_body_via_locals() {
assert_body_param_ref_is_param_colored(
LangKind::Rust,
"fn f(text: i32) -> i32 {\n text + text\n}\n",
" text + text",
);
}
#[test]
fn highlight_rust_keeps_specific_captures_over_broad_identifier_overlay() {
let mut reg = LangRegistry::new();
let src = "fn run() {\n let v = compute(x);\n let p: Parser = v;\n}\n";
let line_starts = compute_line_starts(src.as_bytes());
let h = highlight_text(&mut reg, LangKind::Rust, src.as_bytes(), &line_starts);
let function = Some(rgb(0x8f, 0xa1, 0xb3));
let type_c = Some(rgb(0xeb, 0xcb, 0x8b));
let default_fg = Some(rgb(0xc0, 0xc5, 0xce));
let line1 = " let v = compute(x);";
let call = span_at(&h[1], line1, "compute").expect("call name span");
assert_eq!(
call.style.fg, function,
"call name must keep @function colour"
);
assert_ne!(call.style.fg, default_fg);
let line2 = " let p: Parser = v;";
let ty = span_at(&h[2], line2, "Parser").expect("type name span");
assert_eq!(ty.style.fg, type_c, "type name must keep @type colour");
assert_ne!(ty.style.fg, default_fg);
}
#[test]
fn highlight_rust_colors_module_paths_and_enum_variant_defs_to_match_lsp() {
let mut reg = LangRegistry::new();
let src = "use std::collections::HashMap;\nenum Shade { Light, Dark }\n";
let line_starts = compute_line_starts(src.as_bytes());
let h = highlight_text(&mut reg, LangKind::Rust, src.as_bytes(), &line_starts);
let module_c = Some(rgb(0xeb, 0xcb, 0x8b)); let constant_c = Some(rgb(0xd0, 0x87, 0x70));
let l0 = "use std::collections::HashMap;";
let std_span = span_at(&h[0], l0, "std").expect("std path span");
assert_eq!(std_span.style.fg, module_c, "`std` must be module-coloured");
let coll_span = span_at(&h[0], l0, "collections").expect("collections span");
assert_eq!(
coll_span.style.fg, module_c,
"`collections` must be module-coloured"
);
let l1 = "enum Shade { Light, Dark }";
let light = span_at(&h[1], l1, "Light").expect("Light variant span");
assert_eq!(
light.style.fg, constant_c,
"enum variant declaration must be constant-coloured"
);
let dark = span_at(&h[1], l1, "Dark").expect("Dark variant span");
assert_eq!(dark.style.fg, constant_c);
}
#[test]
fn highlight_rust_colors_use_imports_to_match_lsp() {
let mut reg = LangRegistry::new();
let src = "use std::collections::BTreeSet;\nuse anyhow::{Context, Result};\n";
let ls = compute_line_starts(src.as_bytes());
let h = highlight_text(&mut reg, LangKind::Rust, src.as_bytes(), &ls);
let yellow = Some(rgb(0xeb, 0xcb, 0x8b));
let l0 = "use std::collections::BTreeSet;";
for (needle, label) in [
("std", "module head `std`"),
("collections", "module segment `collections`"),
("BTreeSet", "imported struct `BTreeSet`"),
] {
let sp = span_at(&h[0], l0, needle).unwrap_or_else(|| panic!("no span: {label}"));
assert_eq!(sp.style.fg, yellow, "{label}");
}
let l1 = "use anyhow::{Context, Result};";
for (needle, label) in [
("anyhow", "brace-list module head `anyhow`"),
("Context", "imported trait `Context` in list"),
("Result", "imported type alias `Result` in list"),
] {
let sp = span_at(&h[1], l1, needle).unwrap_or_else(|| panic!("no span: {label}"));
assert_eq!(sp.style.fg, yellow, "{label}");
}
}
#[test]
fn highlight_rust_colors_capitalized_scoped_path_heads_as_types() {
let mut reg = LangRegistry::new();
let src = "fn g() {\n let _ = String::from(\"x\");\n let _ = Command::new(\"y\");\n let _ = Shade::Dark;\n}\n";
let ls = compute_line_starts(src.as_bytes());
let h = highlight_text(&mut reg, LangKind::Rust, src.as_bytes(), &ls);
let yellow = Some(rgb(0xeb, 0xcb, 0x8b));
for (row, line, head) in [
(1usize, " let _ = String::from(\"x\");", "String"),
(2, " let _ = Command::new(\"y\");", "Command"),
(3, " let _ = Shade::Dark;", "Shade"),
] {
let sp = span_at(&h[row], line, head).unwrap_or_else(|| panic!("no span: {head}"));
assert_eq!(
sp.style.fg, yellow,
"scoped path head `{head}` must be type-yellow"
);
}
}
#[test]
fn highlight_rust_use_overlay_does_not_yellow_enum_variants_in_body() {
let mut reg = LangRegistry::new();
let src = "fn f() {\n let _ = Some(1);\n}\n";
let ls = compute_line_starts(src.as_bytes());
let h = highlight_text(&mut reg, LangKind::Rust, src.as_bytes(), &ls);
let yellow = Some(rgb(0xeb, 0xcb, 0x8b));
let l1 = " let _ = Some(1);";
let some = span_at(&h[1], l1, "Some").expect("a span covers `Some`");
assert_ne!(
some.style.fg, yellow,
"an enum variant in expression position must not be coloured type-yellow"
);
}
#[test]
fn project_range_splits_across_lines() {
let line_starts = vec![0usize, 4];
let mut per_line: Vec<Vec<HiSpan>> = vec![Vec::new(); 2];
let style = Style::default();
project_range(1, 6, style, &line_starts, &mut per_line);
assert_eq!(per_line[0].len(), 1);
assert_eq!(per_line[0][0].start, 1);
assert_eq!(per_line[0][0].end, 3);
assert_eq!(per_line[1].len(), 1);
assert_eq!(per_line[1][0].start, 0);
assert_eq!(per_line[1][0].end, 2);
}
#[test]
fn project_range_excludes_newline_at_end_of_line() {
let line_starts = vec![0usize, 4];
let mut per_line: Vec<Vec<HiSpan>> = vec![Vec::new(); 2];
project_range(0, 4, Style::default(), &line_starts, &mut per_line);
assert_eq!(per_line[0].len(), 1);
assert_eq!(per_line[0][0].end, 3);
}
#[test]
fn project_range_within_single_line() {
let line_starts = vec![0usize, 5];
let mut per_line: Vec<Vec<HiSpan>> = vec![Vec::new(); 2];
project_range(1, 4, Style::default(), &line_starts, &mut per_line);
assert_eq!(per_line[0].len(), 1);
assert_eq!(per_line[0][0].start, 1);
assert_eq!(per_line[0][0].end, 4);
assert!(per_line[1].is_empty());
}
fn span_at<'a>(spans: &'a [HiSpan], line: &str, needle: &str) -> Option<&'a HiSpan> {
let off = line.find(needle)?;
let end = off + needle.len();
spans.iter().find(|sp| sp.start <= off && sp.end >= end)
}
const TAG_COLOR: Color = Color::Rgb(0xbf, 0x61, 0x6a);
const ATTRIBUTE_COLOR: Color = Color::Rgb(0xbf, 0x61, 0x6a);
const FUNCTION_COLOR: Color = Color::Rgb(0x8f, 0xa1, 0xb3);
const PROPERTY_COLOR: Color = Color::Rgb(0x8f, 0xa1, 0xb3);
#[test]
fn tsx_jsx_opening_tag_identifier_gets_tag_color() {
let mut reg = LangRegistry::new();
let src = "const x = <div className=\"y\">hi</div>;\n";
let line_starts = compute_line_starts(src.as_bytes());
let h = highlight_text(&mut reg, LangKind::Tsx, src.as_bytes(), &line_starts);
let line0 = src.lines().next().unwrap();
let div_span = span_at(&h[0], line0, "div").expect(
"the 'div' tag identifier in <div ...> must produce at least one highlight span",
);
assert_eq!(
div_span.style.fg,
Some(TAG_COLOR),
"JSX opening-tag identifier must render in the @tag colour ({TAG_COLOR:?}); a missing or default-foreground span means the TSX query has no jsx_opening_element capture"
);
}
#[test]
fn tsx_jsx_closing_tag_identifier_gets_tag_color() {
let mut reg = LangRegistry::new();
let src = "const x = <div>hi</div>;\n";
let line_starts = compute_line_starts(src.as_bytes());
let h = highlight_text(&mut reg, LangKind::Tsx, src.as_bytes(), &line_starts);
let line0 = src.lines().next().unwrap();
let first = line0.find("div").unwrap();
let second_off = line0[first + 3..].find("div").unwrap() + first + 3;
let span = h[0]
.iter()
.find(|sp| sp.start <= second_off && sp.end >= second_off + 3)
.expect("the closing-tag 'div' in </div> must produce a highlight span");
assert_eq!(span.style.fg, Some(TAG_COLOR));
}
#[test]
fn tsx_jsx_self_closing_tag_identifier_gets_tag_color() {
let mut reg = LangRegistry::new();
let src = "const x = <Icon name=\"plus\" />;\n";
let line_starts = compute_line_starts(src.as_bytes());
let h = highlight_text(&mut reg, LangKind::Tsx, src.as_bytes(), &line_starts);
let line0 = src.lines().next().unwrap();
let span = span_at(&h[0], line0, "Icon")
.expect("self-closing <Icon ... /> must produce a tag-name highlight span");
assert_eq!(span.style.fg, Some(TAG_COLOR));
}
#[test]
fn tsx_jsx_attribute_name_gets_attribute_color() {
let mut reg = LangRegistry::new();
let src = "const x = <div className=\"y\" onClick={f}>hi</div>;\n";
let line_starts = compute_line_starts(src.as_bytes());
let h = highlight_text(&mut reg, LangKind::Tsx, src.as_bytes(), &line_starts);
let line0 = src.lines().next().unwrap();
for name in ["className", "onClick"] {
let span = span_at(&h[0], line0, name)
.unwrap_or_else(|| panic!("JSX attribute '{name}' must produce a highlight span"));
assert_eq!(
span.style.fg,
Some(ATTRIBUTE_COLOR),
"JSX attribute name '{name}' must render in the @attribute colour"
);
}
}
#[test]
fn typescript_call_expression_function_name_gets_function_color() {
let mut reg = LangRegistry::new();
let src = "const x = useMemo(() => 1);\n";
let line_starts = compute_line_starts(src.as_bytes());
let h = highlight_text(&mut reg, LangKind::TypeScript, src.as_bytes(), &line_starts);
let line0 = src.lines().next().unwrap();
let span = span_at(&h[0], line0, "useMemo")
.expect("call_expression function name 'useMemo' must produce a highlight span");
assert_eq!(
span.style.fg,
Some(FUNCTION_COLOR),
"the bundled TS highlights.scm has no @function capture; without concatenating the JS query, call sites like 'useMemo(...)' render in default foreground"
);
}
#[test]
fn typescript_member_expression_property_gets_property_color() {
let mut reg = LangRegistry::new();
let src = "const x = styles.sectionHeader;\n";
let line_starts = compute_line_starts(src.as_bytes());
let h = highlight_text(&mut reg, LangKind::TypeScript, src.as_bytes(), &line_starts);
let line0 = src.lines().next().unwrap();
let span = span_at(&h[0], line0, "sectionHeader")
.expect("property_identifier in member_expression must produce a highlight span");
assert_eq!(span.style.fg, Some(PROPERTY_COLOR));
}
#[test]
fn typescript_method_call_property_gets_function_method_color() {
let mut reg = LangRegistry::new();
let src = "const x = arr.map(f);\n";
let line_starts = compute_line_starts(src.as_bytes());
let h = highlight_text(&mut reg, LangKind::TypeScript, src.as_bytes(), &line_starts);
let line0 = src.lines().next().unwrap();
let span = span_at(&h[0], line0, "map")
.expect("method call 'arr.map' must produce a highlight span on 'map'");
assert_eq!(
span.style.fg,
Some(FUNCTION_COLOR),
"method-call property must take @function.method (which shares the function colour), not the bare @property colour"
);
}
#[test]
fn tsx_call_expression_function_name_gets_function_color() {
let mut reg = LangRegistry::new();
let src = "const x = useMemo(() => 1);\n";
let line_starts = compute_line_starts(src.as_bytes());
let h = highlight_text(&mut reg, LangKind::Tsx, src.as_bytes(), &line_starts);
let line0 = src.lines().next().unwrap();
let span = span_at(&h[0], line0, "useMemo")
.expect("TSX call_expression function name 'useMemo' must produce a highlight span");
assert_eq!(span.style.fg, Some(FUNCTION_COLOR));
}
#[test]
fn tsx_member_expression_property_gets_property_color() {
let mut reg = LangRegistry::new();
let src = "const x = styles.sectionHeader;\n";
let line_starts = compute_line_starts(src.as_bytes());
let h = highlight_text(&mut reg, LangKind::Tsx, src.as_bytes(), &line_starts);
let line0 = src.lines().next().unwrap();
let span = span_at(&h[0], line0, "sectionHeader")
.expect("TSX property_identifier in member_expression must produce a highlight span");
assert_eq!(span.style.fg, Some(PROPERTY_COLOR));
}
#[test]
fn tsx_jsx_attribute_capture_still_wins_over_generic_property_capture() {
let mut reg = LangRegistry::new();
let src = "const x = <div className=\"y\" />;\n";
let line_starts = compute_line_starts(src.as_bytes());
let h = highlight_text(&mut reg, LangKind::Tsx, src.as_bytes(), &line_starts);
let line0 = src.lines().next().unwrap();
let span = span_at(&h[0], line0, "className")
.expect("'className' must still produce a highlight span");
assert_eq!(
span.style.fg,
Some(ATTRIBUTE_COLOR),
"JSX attribute name must keep the @attribute colour; if it renders in @property colour, the overlay is ordered before the JS query and needs to move after"
);
}
#[test]
fn project_range_zero_length_noop() {
let line_starts = vec![0usize];
let mut per_line: Vec<Vec<HiSpan>> = vec![Vec::new(); 1];
project_range(3, 3, Style::default(), &line_starts, &mut per_line);
assert!(per_line[0].is_empty());
}
#[test]
fn uncaptured_source_follows_the_active_palette_not_base16() {
let gruvbox_ish = SyntaxPalette {
fg: (0xeb, 0xdb, 0xb2),
..SyntaxPalette::BASE16
};
let mut reg = LangRegistry::new();
let src = "let x = 1;\n";
let ls = compute_line_starts(src.as_bytes());
let h = highlight_text_with_palette(
&mut reg,
LangKind::Rust,
src.as_bytes(),
&ls,
&gruvbox_ish,
)
.0;
let slate = Some(rgb(0xc0, 0xc5, 0xce));
let cream = Some(rgb(0xeb, 0xdb, 0xb2));
assert!(
h[0].iter().all(|s| s.style.fg != slate),
"no span may keep the Base16 default when the palette differs: {:?}",
h[0]
);
assert!(
h[0].iter().any(|s| s.style.fg == cream),
"default-foreground spans must use the palette fg: {:?}",
h[0]
);
}
}