use std::collections::BTreeMap;
use std::fmt;
use std::sync::Arc;
use crate::attr::{AttrSet, AttrValue, StyleAttr};
use crate::{ColorDepth, TokenId, tokens};
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum AnsiColor {
Black,
Red,
Green,
Yellow,
Blue,
Magenta,
Cyan,
White,
BrightBlack,
BrightRed,
BrightGreen,
BrightYellow,
BrightBlue,
BrightMagenta,
BrightCyan,
BrightWhite,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Color {
Ansi(AnsiColor),
Rgb {
red: u8,
green: u8,
blue: u8,
fallback: AnsiColor,
},
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ResolvedColor {
Ansi(AnsiColor),
Indexed(u8),
Rgb { red: u8, green: u8, blue: u8 },
}
impl Color {
#[must_use]
pub fn resolve(self, depth: ColorDepth) -> ResolvedColor {
match (self, depth) {
(Self::Ansi(color), _) => ResolvedColor::Ansi(color),
(
Self::Rgb {
red, green, blue, ..
},
ColorDepth::TrueColor,
) => ResolvedColor::Rgb { red, green, blue },
(
Self::Rgb {
red, green, blue, ..
},
ColorDepth::Ansi256,
) => ResolvedColor::Indexed(quantize_ansi256(red, green, blue)),
(Self::Rgb { fallback, .. }, ColorDepth::Ansi16) => ResolvedColor::Ansi(fallback),
}
}
}
pub(crate) fn quantize_ansi256(red: u8, green: u8, blue: u8) -> u8 {
const CUBE: [u8; 6] = [0, 95, 135, 175, 215, 255];
let mut best_index = 16u8;
let mut best_distance = u64::MAX;
for (r_index, &candidate_red) in CUBE.iter().enumerate() {
for (g_index, &candidate_green) in CUBE.iter().enumerate() {
for (b_index, &candidate_blue) in CUBE.iter().enumerate() {
let index = 16 + 36 * r_index as u8 + 6 * g_index as u8 + b_index as u8;
choose_color_candidate(
red,
green,
blue,
candidate_red,
candidate_green,
candidate_blue,
index,
&mut best_index,
&mut best_distance,
);
}
}
}
for gray_index in 0u8..=23 {
let value = 8 + 10 * gray_index;
choose_color_candidate(
red,
green,
blue,
value,
value,
value,
232 + gray_index,
&mut best_index,
&mut best_distance,
);
}
best_index
}
#[allow(clippy::too_many_arguments)]
fn choose_color_candidate(
red: u8,
green: u8,
blue: u8,
candidate_red: u8,
candidate_green: u8,
candidate_blue: u8,
candidate_index: u8,
best_index: &mut u8,
best_distance: &mut u64,
) {
let distance = red_mean_distance(
red,
green,
blue,
candidate_red,
candidate_green,
candidate_blue,
);
if distance < *best_distance || (distance == *best_distance && candidate_index < *best_index) {
*best_distance = distance;
*best_index = candidate_index;
}
}
fn red_mean_distance(
red: u8,
green: u8,
blue: u8,
candidate_red: u8,
candidate_green: u8,
candidate_blue: u8,
) -> u64 {
let red_mean = (u64::from(red) + u64::from(candidate_red)) / 2;
let delta_red = i64::from(red) - i64::from(candidate_red);
let delta_green = i64::from(green) - i64::from(candidate_green);
let delta_blue = i64::from(blue) - i64::from(candidate_blue);
let red_squared = delta_red.unsigned_abs().pow(2);
let green_squared = delta_green.unsigned_abs().pow(2);
let blue_squared = delta_blue.unsigned_abs().pow(2);
(((512 + red_mean) * red_squared) >> 8)
+ 4 * green_squared
+ (((767 - red_mean) * blue_squared) >> 8)
}
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct TokenStyle {
pub foreground: Option<Color>,
pub background: Option<Color>,
pub bold: bool,
pub dim: bool,
pub underline: bool,
pub attrs: AttrSet,
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
struct CoreTokenStyle {
foreground: Option<Color>,
bold: bool,
dim: bool,
underline: bool,
}
impl CoreTokenStyle {
const fn from_style(style: &TokenStyle) -> Self {
Self {
foreground: style.foreground,
bold: style.bold,
dim: style.dim,
underline: style.underline,
}
}
fn with_extensions(self, background: Option<Color>, attrs: AttrSet) -> TokenStyle {
TokenStyle {
foreground: self.foreground,
background,
bold: self.bold,
dim: self.dim,
underline: self.underline,
attrs,
}
}
}
impl TokenStyle {
pub const fn foreground(color: Color) -> Self {
Self {
foreground: Some(color),
background: None,
bold: false,
dim: false,
underline: false,
attrs: AttrSet::new(),
}
}
pub const fn background(color: Color) -> Self {
Self {
foreground: None,
background: Some(color),
bold: false,
dim: false,
underline: false,
attrs: AttrSet::new(),
}
}
pub const fn on(foreground: Color, background: Color) -> Self {
Self {
foreground: Some(foreground),
background: Some(background),
bold: false,
dim: false,
underline: false,
attrs: AttrSet::new(),
}
}
pub const fn with_background(mut self, color: Color) -> Self {
self.background = Some(color);
self
}
pub fn with_attr(mut self, attr: StyleAttr, value: AttrValue) -> Self {
self.attrs = self.attrs.set(attr, value);
self
}
pub const fn bold(color: Color) -> Self {
Self {
foreground: Some(color),
background: None,
bold: true,
dim: false,
underline: false,
attrs: AttrSet::new(),
}
}
pub const fn emphasized() -> Self {
Self {
foreground: None,
background: None,
bold: true,
dim: false,
underline: false,
attrs: AttrSet::new(),
}
}
pub const fn dimmed() -> Self {
Self {
foreground: None,
background: None,
bold: false,
dim: true,
underline: false,
attrs: AttrSet::new(),
}
}
pub const fn underlined(color: Color) -> Self {
Self {
foreground: Some(color),
background: None,
bold: false,
dim: false,
underline: true,
attrs: AttrSet::new(),
}
}
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum StyleValue<T> {
#[default]
Inherit,
Set(T),
Clear,
}
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct ThemeRule {
foreground: StyleValue<Color>,
background: StyleValue<Color>,
bold: Option<bool>,
dim: Option<bool>,
underline: Option<bool>,
attrs: AttrPatch,
}
impl ThemeRule {
pub const fn new() -> Self {
Self {
foreground: StyleValue::Inherit,
background: StyleValue::Inherit,
bold: None,
dim: None,
underline: None,
attrs: AttrPatch::new(),
}
}
pub const fn with_foreground(mut self, color: Color) -> Self {
self.foreground = StyleValue::Set(color);
self
}
pub const fn with_background(mut self, color: Color) -> Self {
self.background = StyleValue::Set(color);
self
}
pub const fn clear_background(mut self) -> Self {
self.background = StyleValue::Clear;
self
}
pub fn with_attr(mut self, attr: StyleAttr, value: AttrValue) -> Self {
self.attrs = self.attrs.set(attr, value);
self
}
pub fn clear_attr(mut self, attr: StyleAttr) -> Self {
self.attrs = self.attrs.clear(attr);
self
}
pub const fn clear_foreground(mut self) -> Self {
self.foreground = StyleValue::Clear;
self
}
pub const fn with_bold(mut self, value: bool) -> Self {
self.bold = Some(value);
self
}
pub const fn with_dim(mut self, value: bool) -> Self {
self.dim = Some(value);
self
}
pub const fn with_underline(mut self, value: bool) -> Self {
self.underline = Some(value);
self
}
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
struct CoreThemeRule {
foreground: StyleValue<Color>,
bold: Option<bool>,
dim: Option<bool>,
underline: Option<bool>,
}
impl CoreThemeRule {
const fn from_rule(rule: &ThemeRule) -> Self {
Self {
foreground: rule.foreground,
bold: rule.bold,
dim: rule.dim,
underline: rule.underline,
}
}
fn apply(self, mut style: CoreTokenStyle) -> CoreTokenStyle {
match self.foreground {
StyleValue::Inherit => {}
StyleValue::Set(color) => style.foreground = Some(color),
StyleValue::Clear => style.foreground = None,
}
if let Some(value) = self.bold {
style.bold = value;
}
if let Some(value) = self.dim {
style.dim = value;
}
if let Some(value) = self.underline {
style.underline = value;
}
style
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum AttrChange {
Set(StyleAttr, AttrValue),
Clear(StyleAttr),
}
impl AttrChange {
const fn attr(self) -> StyleAttr {
match self {
Self::Set(attr, _) | Self::Clear(attr) => attr,
}
}
}
#[derive(Clone, Debug, Default, Eq, PartialEq)]
struct AttrPatch {
changes: Option<Arc<Vec<AttrChange>>>,
}
impl AttrPatch {
const fn new() -> Self {
Self { changes: None }
}
fn set(self, attr: StyleAttr, value: AttrValue) -> Self {
self.with_change(AttrChange::Set(attr, value))
}
fn clear(self, attr: StyleAttr) -> Self {
self.with_change(AttrChange::Clear(attr))
}
fn with_change(self, change: AttrChange) -> Self {
let mut changes = self.changes.as_deref().cloned().unwrap_or_default();
if let Some(existing) = changes
.iter_mut()
.find(|existing| existing.attr() == change.attr())
{
*existing = change;
} else {
changes.push(change);
}
Self {
changes: Some(Arc::new(changes)),
}
}
fn apply(&self, mut attrs: AttrSet) -> AttrSet {
for change in self.changes.as_deref().into_iter().flatten() {
match *change {
AttrChange::Set(attr, value) => attrs = attrs.set(attr, value),
AttrChange::Clear(attr) => {
attrs.remove(attr);
}
}
}
attrs
}
fn is_empty(&self) -> bool {
self.changes.is_none()
}
}
#[derive(Clone, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct ThemeName(String);
impl ThemeName {
pub fn parse(value: impl Into<String>) -> Result<Self, ThemeError> {
let value = value.into();
if valid_theme_name(&value) {
Ok(Self(value))
} else {
Err(ThemeError::InvalidName { value })
}
}
pub fn as_str(&self) -> &str {
&self.0
}
}
impl fmt::Debug for ThemeName {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_tuple("ThemeName")
.field(&self.as_str())
.finish()
}
}
impl fmt::Display for ThemeName {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(self.as_str())
}
}
fn valid_theme_name(value: &str) -> bool {
let bytes = value.as_bytes();
if bytes.is_empty() || bytes.len() > 64 || !bytes[0].is_ascii_lowercase() {
return false;
}
if bytes.last() == Some(&b'-') {
return false;
}
bytes
.iter()
.all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || *byte == b'-')
}
#[cfg(feature = "serde")]
impl serde::Serialize for ThemeName {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
serializer.serialize_str(self.as_str())
}
}
#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for ThemeName {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let value = <String as serde::Deserialize>::deserialize(deserializer)?;
Self::parse(value).map_err(serde::de::Error::custom)
}
}
#[derive(Clone)]
pub struct Theme(Arc<ThemeData>);
struct ThemeData {
name: ThemeName,
rules: BTreeMap<TokenId, ThemeEntry>,
background_rules: BTreeMap<TokenId, BackgroundThemeEntry>,
attr_rules: BTreeMap<TokenId, AttrThemeEntry>,
}
#[derive(Clone, Copy, Debug)]
enum ThemeEntry {
Replace(CoreTokenStyle),
Patch(CoreThemeRule),
}
impl ThemeEntry {
fn apply(self, style: CoreTokenStyle) -> CoreTokenStyle {
match self {
Self::Replace(replacement) => replacement,
Self::Patch(rule) => rule.apply(style),
}
}
const fn replaces(self) -> bool {
matches!(self, Self::Replace(_))
}
}
#[derive(Clone, Copy, Debug)]
enum BackgroundThemeEntry {
Replace(Color),
Patch(StyleValue<Color>),
}
impl BackgroundThemeEntry {
fn apply(self, background: &mut Option<Color>) {
match self {
Self::Replace(color) | Self::Patch(StyleValue::Set(color)) => {
*background = Some(color);
}
Self::Patch(StyleValue::Clear) => *background = None,
Self::Patch(StyleValue::Inherit) => {}
}
}
}
#[derive(Clone, Debug)]
enum AttrThemeEntry {
Replace(AttrSet),
Patch(AttrPatch),
}
impl AttrThemeEntry {
fn apply(&self, attrs: AttrSet) -> AttrSet {
match self {
Self::Replace(replacement) => replacement.clone(),
Self::Patch(patch) => patch.apply(attrs),
}
}
}
impl fmt::Debug for Theme {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("Theme")
.field("name", &self.0.name)
.field("rules", &self.0.rules)
.field("background_rules", &self.0.background_rules)
.field("attr_rules", &self.0.attr_rules)
.finish()
}
}
impl Theme {
pub fn builder(name: impl Into<String>) -> ThemeBuilder {
ThemeBuilder {
name: name.into(),
rules: BTreeMap::new(),
background_rules: BTreeMap::new(),
attr_rules: BTreeMap::new(),
}
}
pub fn inheriting(name: impl Into<String>, base: &Theme) -> ThemeBuilder {
ThemeBuilder {
name: name.into(),
rules: base.0.rules.clone(),
background_rules: base.0.background_rules.clone(),
attr_rules: base.0.attr_rules.clone(),
}
}
pub fn name(&self) -> &ThemeName {
&self.0.name
}
pub fn resolve(&self, token: &TokenId) -> TokenStyle {
self.resolve_stack([token])
}
pub fn resolve_stack<'a>(&self, tokens: impl IntoIterator<Item = &'a TokenId>) -> TokenStyle {
let mut style = CoreTokenStyle::default();
let mut background = None;
let mut attrs = AttrSet::new();
self.apply_key(
tokens::TEXT.as_str(),
&mut style,
&mut background,
&mut attrs,
);
for token in tokens {
let value = token.as_str();
for (index, byte) in value.bytes().enumerate() {
if byte == b'.' {
self.apply_key(&value[..index], &mut style, &mut background, &mut attrs);
}
}
self.apply_key(value, &mut style, &mut background, &mut attrs);
}
style.with_extensions(background, attrs)
}
fn apply_key(
&self,
token: &str,
style: &mut CoreTokenStyle,
background: &mut Option<Color>,
attrs: &mut AttrSet,
) {
if let Some(rule) = self.0.rules.get(token) {
if rule.replaces() {
*background = None;
*attrs = AttrSet::new();
}
*style = (*rule).apply(*style);
}
if !self.0.background_rules.is_empty()
&& let Some(rule) = self.0.background_rules.get(token)
{
rule.apply(background);
}
if !self.0.attr_rules.is_empty()
&& let Some(rule) = self.0.attr_rules.get(token)
{
*attrs = rule.apply(std::mem::take(attrs));
}
}
}
pub struct ThemeBuilder {
name: String,
rules: BTreeMap<TokenId, ThemeEntry>,
background_rules: BTreeMap<TokenId, BackgroundThemeEntry>,
attr_rules: BTreeMap<TokenId, AttrThemeEntry>,
}
impl ThemeBuilder {
pub fn rule(mut self, token: TokenId, style: TokenStyle) -> Result<Self, ThemeError> {
if self.rules.contains_key(&token) {
return Err(ThemeError::DuplicateRule { token });
}
let core = CoreTokenStyle::from_style(&style);
if let Some(background) = style.background {
self.background_rules
.insert(token.clone(), BackgroundThemeEntry::Replace(background));
}
if !style.attrs.is_empty() {
self.attr_rules
.insert(token.clone(), AttrThemeEntry::Replace(style.attrs));
}
self.rules.insert(token, ThemeEntry::Replace(core));
Ok(self)
}
pub fn patch(mut self, token: TokenId, rule: ThemeRule) -> Result<Self, ThemeError> {
if self.rules.contains_key(&token) {
return Err(ThemeError::DuplicateRule { token });
}
let core = CoreThemeRule::from_rule(&rule);
if rule.background != StyleValue::Inherit {
self.background_rules
.insert(token.clone(), BackgroundThemeEntry::Patch(rule.background));
}
if !rule.attrs.is_empty() {
self.attr_rules
.insert(token.clone(), AttrThemeEntry::Patch(rule.attrs));
}
self.rules.insert(token, ThemeEntry::Patch(core));
Ok(self)
}
pub fn override_rule(mut self, token: TokenId, style: TokenStyle) -> Result<Self, ThemeError> {
let Some(existing) = self.rules.get_mut(&token) else {
return Err(ThemeError::MissingOverrideTarget { token });
};
*existing = ThemeEntry::Replace(CoreTokenStyle::from_style(&style));
if let Some(background) = style.background {
self.background_rules
.insert(token.clone(), BackgroundThemeEntry::Replace(background));
} else {
self.background_rules.remove(&token);
}
if style.attrs.is_empty() {
self.attr_rules.remove(&token);
} else {
self.attr_rules
.insert(token, AttrThemeEntry::Replace(style.attrs));
}
Ok(self)
}
pub fn override_patch(mut self, token: TokenId, rule: ThemeRule) -> Result<Self, ThemeError> {
let Some(existing) = self.rules.get_mut(&token) else {
return Err(ThemeError::MissingOverrideTarget { token });
};
*existing = ThemeEntry::Patch(CoreThemeRule::from_rule(&rule));
if rule.background == StyleValue::Inherit {
self.background_rules.remove(&token);
} else {
self.background_rules
.insert(token.clone(), BackgroundThemeEntry::Patch(rule.background));
}
if rule.attrs.is_empty() {
self.attr_rules.remove(&token);
} else {
self.attr_rules
.insert(token, AttrThemeEntry::Patch(rule.attrs));
}
Ok(self)
}
pub fn build(self) -> Result<Theme, ThemeError> {
let name = ThemeName::parse(self.name)?;
Ok(Theme(Arc::new(ThemeData {
name,
rules: self.rules,
background_rules: self.background_rules,
attr_rules: self.attr_rules,
})))
}
}
#[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)]
pub enum ThemeError {
#[error("invalid theme name {value:?}")]
InvalidName { value: String },
#[error("theme already defines token {token}")]
DuplicateRule { token: TokenId },
#[error("theme cannot override absent token {token}")]
MissingOverrideTarget { token: TokenId },
}
#[derive(Clone, Default)]
pub struct ThemeCatalog {
themes: BTreeMap<ThemeName, Theme>,
}
impl ThemeCatalog {
pub fn builder() -> ThemeCatalogBuilder {
ThemeCatalogBuilder {
themes: BTreeMap::new(),
}
}
pub fn get(&self, name: &ThemeName) -> Result<Theme, ThemeCatalogError> {
self.themes
.get(name)
.cloned()
.ok_or_else(|| ThemeCatalogError::ThemeNotFound { name: name.clone() })
}
}
pub struct ThemeCatalogBuilder {
themes: BTreeMap<ThemeName, Theme>,
}
impl ThemeCatalogBuilder {
pub fn theme(mut self, theme: Theme) -> Result<Self, ThemeCatalogError> {
let name = theme.name().clone();
if self.themes.contains_key(&name) {
return Err(ThemeCatalogError::DuplicateTheme { name });
}
self.themes.insert(name, theme);
Ok(self)
}
pub fn build(self) -> ThemeCatalog {
ThemeCatalog {
themes: self.themes,
}
}
}
#[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)]
pub enum ThemeCatalogError {
#[error("theme catalog already contains {name}")]
DuplicateTheme { name: ThemeName },
#[error("theme catalog does not contain {name}")]
ThemeNotFound { name: ThemeName },
}
fn static_theme(name: &'static str, rules: &[(TokenId, TokenStyle)]) -> Theme {
let mut entries = BTreeMap::new();
let mut background_entries = BTreeMap::new();
let mut attr_entries = BTreeMap::new();
for (token, style) in rules {
entries.insert(
token.clone(),
ThemeEntry::Replace(CoreTokenStyle::from_style(style)),
);
if let Some(background) = style.background {
background_entries.insert(token.clone(), BackgroundThemeEntry::Replace(background));
}
if !style.attrs.is_empty() {
attr_entries.insert(token.clone(), AttrThemeEntry::Replace(style.attrs.clone()));
}
}
Theme(Arc::new(ThemeData {
name: ThemeName(name.to_owned()),
rules: entries,
background_rules: background_entries,
attr_rules: attr_entries,
}))
}
const fn ansi(color: AnsiColor) -> Color {
Color::Ansi(color)
}
const fn rgb(red: u8, green: u8, blue: u8, fallback: AnsiColor) -> Color {
Color::Rgb {
red,
green,
blue,
fallback,
}
}
fn semantic_theme(name: &'static str, palette: Palette) -> Theme {
let mut theme = static_theme(
name,
&[
(tokens::TEXT, TokenStyle::default()),
(tokens::TEXT_HEADING, TokenStyle::bold(palette.heading)),
(tokens::TEXT_SUBHEADING, TokenStyle::bold(palette.info)),
(tokens::TEXT_EMPHASIS, TokenStyle::emphasized()),
(tokens::TEXT_LINK, TokenStyle::underlined(palette.link)),
(tokens::TEXT_LABEL, TokenStyle::bold(palette.accent)),
(tokens::TEXT_MUTED, palette.muted.clone()),
(tokens::TEXT_COMMENT, palette.muted.clone()),
(tokens::LIST_MARKER, palette.muted.clone()),
(tokens::TABLE_HEADER, TokenStyle::bold(palette.heading)),
(tokens::SYNTAX_CODE, TokenStyle::foreground(palette.code)),
(tokens::SYNTAX_KEYWORD, TokenStyle::bold(palette.accent)),
(tokens::SYNTAX_COMMENT, palette.muted.clone()),
(tokens::SYNTAX_STRING, TokenStyle::foreground(palette.code)),
(
tokens::SYNTAX_STRING_ESCAPE,
TokenStyle::bold(palette.accent),
),
(tokens::SYNTAX_NUMBER, TokenStyle::foreground(palette.info)),
(tokens::SYNTAX_BOOLEAN, TokenStyle::bold(palette.info)),
(
tokens::SYNTAX_CONSTANT,
TokenStyle::foreground(palette.info),
),
(
tokens::SYNTAX_FUNCTION,
TokenStyle::foreground(palette.entity),
),
(
tokens::SYNTAX_PROPERTY,
TokenStyle::foreground(palette.entity),
),
(tokens::SYNTAX_TYPE, TokenStyle::bold(palette.info)),
(
tokens::SYNTAX_OPERATOR,
TokenStyle::foreground(palette.accent),
),
(tokens::SYNTAX_PUNCTUATION, palette.muted.clone()),
(tokens::PROMPT, TokenStyle::bold(palette.accent)),
(tokens::ENTITY, TokenStyle::foreground(palette.entity)),
(
tokens::ENTITY_IDENTIFIER,
TokenStyle::foreground(palette.entity),
),
(tokens::ENTITY_PATH, TokenStyle::foreground(palette.code)),
(tokens::ENTITY_REVISION, palette.muted.clone()),
(tokens::ENTITY_CAPABILITY, TokenStyle::bold(palette.accent)),
(tokens::ENTITY_RUNTIME, TokenStyle::bold(palette.success)),
(tokens::ENTITY_PROFILE, TokenStyle::bold(palette.info)),
(tokens::DATA_FORMAT, TokenStyle::bold(palette.accent)),
(tokens::DATA_NUMBER, palette.muted.clone()),
(tokens::DATA_COUNT, palette.muted.clone()),
(tokens::DATA_SIZE, palette.muted.clone()),
(tokens::DATA_DURATION, palette.muted.clone()),
(tokens::STATUS, TokenStyle::foreground(palette.info)),
(tokens::STATUS_SUCCESS, TokenStyle::bold(palette.success)),
(tokens::STATUS_INFO, TokenStyle::bold(palette.info)),
(tokens::STATUS_WARNING, TokenStyle::bold(palette.warning)),
(tokens::STATUS_ERROR, TokenStyle::bold(palette.error)),
(tokens::DIAGNOSTIC_NOTE, palette.muted.clone()),
(tokens::DIAGNOSTIC_INFO, TokenStyle::bold(palette.info)),
(
tokens::DIAGNOSTIC_WARNING,
TokenStyle::bold(palette.warning),
),
(tokens::DIAGNOSTIC_ERROR, TokenStyle::bold(palette.error)),
(tokens::PROGRESS, TokenStyle::bold(palette.info)),
],
);
let rules = &mut Arc::get_mut(&mut theme.0)
.expect("new semantic theme is uniquely owned")
.rules;
rules.insert(
tokens::PAIR_KEY,
ThemeEntry::Patch(CoreThemeRule::from_rule(&ThemeRule::new().with_bold(true))),
);
rules.insert(
tokens::PAIR_LABEL,
ThemeEntry::Patch(CoreThemeRule::from_rule(&ThemeRule::new().with_bold(true))),
);
rules.insert(
tokens::DIAGNOSTIC_LABEL,
ThemeEntry::Patch(CoreThemeRule::from_rule(&ThemeRule::new().with_bold(true))),
);
rules.insert(
tokens::DIAGNOSTIC_CODE,
ThemeEntry::Patch(CoreThemeRule::from_rule(&ThemeRule::new().with_bold(true))),
);
rules.insert(
tokens::DIAGNOSTIC_HINT,
ThemeEntry::Patch(CoreThemeRule::from_rule(&ThemeRule::new().with_dim(true))),
);
theme
}
#[derive(Clone)]
struct Palette {
heading: Color,
accent: Color,
entity: Color,
code: Color,
link: Color,
muted: TokenStyle,
success: Color,
info: Color,
warning: Color,
error: Color,
}
pub mod themes {
use super::*;
use crate::background::Background;
pub fn for_background(background: Background) -> Theme {
match background {
Background::Light => light(),
Background::Dark | Background::Unknown => default(),
}
}
pub fn default() -> Theme {
semantic_theme(
"default",
Palette {
heading: ansi(AnsiColor::BrightCyan),
accent: ansi(AnsiColor::BrightBlue),
entity: ansi(AnsiColor::Cyan),
code: ansi(AnsiColor::Cyan),
link: ansi(AnsiColor::BrightBlue),
muted: TokenStyle::dimmed(),
success: ansi(AnsiColor::Green),
info: ansi(AnsiColor::Cyan),
warning: ansi(AnsiColor::Yellow),
error: ansi(AnsiColor::Red),
},
)
}
pub fn light() -> Theme {
semantic_theme(
"light",
Palette {
heading: rgb(38, 139, 210, AnsiColor::Blue),
accent: rgb(211, 54, 130, AnsiColor::Magenta),
entity: rgb(108, 113, 196, AnsiColor::Magenta),
code: rgb(42, 161, 152, AnsiColor::Cyan),
link: rgb(38, 139, 210, AnsiColor::Blue),
muted: TokenStyle::foreground(rgb(88, 110, 117, AnsiColor::Black)),
success: rgb(133, 153, 0, AnsiColor::Green),
info: rgb(38, 139, 210, AnsiColor::Blue),
warning: rgb(181, 137, 0, AnsiColor::Yellow),
error: rgb(220, 50, 47, AnsiColor::Red),
},
)
}
pub fn high_contrast() -> Theme {
semantic_theme(
"high-contrast",
Palette {
heading: ansi(AnsiColor::BrightWhite),
accent: ansi(AnsiColor::BrightCyan),
entity: ansi(AnsiColor::BrightBlue),
code: ansi(AnsiColor::BrightBlue),
link: ansi(AnsiColor::BrightCyan),
muted: TokenStyle::foreground(ansi(AnsiColor::White)),
success: ansi(AnsiColor::BrightGreen),
info: ansi(AnsiColor::BrightMagenta),
warning: ansi(AnsiColor::BrightYellow),
error: ansi(AnsiColor::BrightRed),
},
)
}
pub fn monochrome() -> Theme {
static_theme(
"monochrome",
&[
(tokens::TEXT, TokenStyle::default()),
(tokens::TEXT_HEADING, TokenStyle::emphasized()),
(tokens::TEXT_SUBHEADING, TokenStyle::emphasized()),
(tokens::TEXT_EMPHASIS, TokenStyle::emphasized()),
(tokens::TEXT_LABEL, TokenStyle::emphasized()),
(tokens::TABLE_HEADER, TokenStyle::emphasized()),
(tokens::PROMPT, TokenStyle::emphasized()),
(tokens::STATUS_SUCCESS, TokenStyle::emphasized()),
(tokens::STATUS_WARNING, TokenStyle::emphasized()),
(tokens::STATUS_ERROR, TokenStyle::emphasized()),
(tokens::TEXT_MUTED, TokenStyle::dimmed()),
(tokens::SYNTAX_COMMENT, TokenStyle::dimmed()),
],
)
}
pub fn dracula() -> Theme {
semantic_theme(
"dracula",
Palette {
heading: rgb(139, 233, 253, AnsiColor::BrightCyan),
accent: rgb(255, 121, 198, AnsiColor::BrightMagenta),
entity: rgb(189, 147, 249, AnsiColor::BrightMagenta),
code: rgb(241, 250, 140, AnsiColor::BrightYellow),
link: rgb(139, 233, 253, AnsiColor::BrightCyan),
muted: TokenStyle::foreground(rgb(98, 114, 164, AnsiColor::BrightBlack)),
success: rgb(80, 250, 123, AnsiColor::BrightGreen),
info: rgb(139, 233, 253, AnsiColor::BrightCyan),
warning: rgb(241, 250, 140, AnsiColor::BrightYellow),
error: rgb(255, 85, 85, AnsiColor::BrightRed),
},
)
}
pub fn nord() -> Theme {
semantic_theme(
"nord",
Palette {
heading: rgb(136, 192, 208, AnsiColor::BrightCyan),
accent: rgb(129, 161, 193, AnsiColor::BrightBlue),
entity: rgb(180, 142, 173, AnsiColor::BrightMagenta),
code: rgb(163, 190, 140, AnsiColor::Green),
link: rgb(94, 129, 172, AnsiColor::Blue),
muted: TokenStyle::foreground(rgb(76, 86, 106, AnsiColor::BrightBlack)),
success: rgb(163, 190, 140, AnsiColor::Green),
info: rgb(136, 192, 208, AnsiColor::Cyan),
warning: rgb(235, 203, 139, AnsiColor::Yellow),
error: rgb(191, 97, 106, AnsiColor::Red),
},
)
}
pub fn solarized_dark() -> Theme {
semantic_theme(
"solarized-dark",
Palette {
heading: rgb(42, 161, 152, AnsiColor::Cyan),
accent: rgb(38, 139, 210, AnsiColor::Blue),
entity: rgb(108, 113, 196, AnsiColor::Magenta),
code: rgb(181, 137, 0, AnsiColor::Yellow),
link: rgb(38, 139, 210, AnsiColor::Blue),
muted: TokenStyle::foreground(rgb(88, 110, 117, AnsiColor::BrightBlack)),
success: rgb(133, 153, 0, AnsiColor::Green),
info: rgb(42, 161, 152, AnsiColor::Cyan),
warning: rgb(203, 75, 22, AnsiColor::Yellow),
error: rgb(220, 50, 47, AnsiColor::Red),
},
)
}
pub fn gruvbox_dark() -> Theme {
semantic_theme(
"gruvbox-dark",
Palette {
heading: rgb(131, 165, 152, AnsiColor::Cyan),
accent: rgb(69, 133, 136, AnsiColor::Blue),
entity: rgb(211, 134, 155, AnsiColor::Magenta),
code: rgb(184, 187, 38, AnsiColor::Green),
link: rgb(131, 165, 152, AnsiColor::Cyan),
muted: TokenStyle::foreground(rgb(146, 131, 116, AnsiColor::BrightBlack)),
success: rgb(184, 187, 38, AnsiColor::Green),
info: rgb(131, 165, 152, AnsiColor::Cyan),
warning: rgb(250, 189, 47, AnsiColor::Yellow),
error: rgb(251, 73, 52, AnsiColor::Red),
},
)
}
}