//! highlight — syntax highlighting via syntect, in the active theme's colors. //! //! syntect parses; it does not choose the colors. The theme it highlights against is a table of //! [`Role`]s, each a placeholder color, and `paint` swaps every role for the theme's own style //! when a line is drawn. So a code block, a tool card, a diff and the preview all wear the palette //! everything else wears, a custom theme or Omarchy's included, and switching themes recolors code //! at once: the memo holds roles, not colors, so it never goes stale. //! //! [`highlight_code`] is memoized: the transcript re-lays out every block on every frame, so an //! answer with a few fenced blocks, or a handful of `write` cards, would otherwise spend more of //! each frame here than in the rest of the render path put together. //! //! syntect runs on **`fancy-regex`**, not its default Oniguruma binding. Oniguruma is roughly 3.5× //! faster with identical output, but it is C, and a C toolchain in the dependency graph is a tax on //! every `cargo install`, every cross-build, and every CI runner. The memo is what makes that trade //! cheap: the cost is paid once per distinct line, not per frame, and highlighting is per line //! rather than per file. use crate::theme::styles::ThemeStyles; use ratatui::style::{Modifier, Style}; use ratatui::text::{Line, Span}; use std::collections::HashMap; use std::hash::{Hash, Hasher}; use std::str::FromStr; use std::sync::{Arc, LazyLock, Mutex, MutexGuard, OnceLock}; static SYNTAX_SET: OnceLock = OnceLock::new(); static ROLE_THEME: OnceLock = OnceLock::new(); fn get_syntax_set() -> &'static syntect::parsing::SyntaxSet { SYNTAX_SET.get_or_init(syntect::parsing::SyntaxSet::load_defaults_newlines) } /// What a stretch of code is, as far as its color goes. /// /// Few on purpose: a theme has about seven hues, and a role only earns its place by landing on a /// different one, or by meaning something the markdown renderer already draws its own way. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] #[repr(u8)] pub enum Role { Text, Punctuation, Comment, Keyword, String, Escape, Constant, Function, Type, Tag, Heading, Link, LinkUrl, Quote, Code, Strong, Emphasis, ListMarker, Inserted, Deleted, Invalid, } impl Role { const ALL: [Role; 21] = [ Role::Text, Role::Punctuation, Role::Comment, Role::Keyword, Role::String, Role::Escape, Role::Constant, Role::Function, Role::Type, Role::Tag, Role::Heading, Role::Link, Role::LinkUrl, Role::Quote, Role::Code, Role::Strong, Role::Emphasis, Role::ListMarker, Role::Inserted, Role::Deleted, Role::Invalid, ]; /// The theme token this role is drawn in, and how. /// /// The tokens spend the palette on meaning: the accent goes on what you scan a file for, the /// functions; types take the cool hue so they separate from calls; keywords take /// `accentSecondary`, the violet most syntax themes give them; punctuation recedes into /// `muted`. `dim` is never used, since it is a rule color, not a text color. Markdown takes the /// `md*` tokens, so the preview of a `.md` file wears the colors the rendered answer does. pub fn token(self) -> (&'static str, Modifier) { match self { Role::Text | Role::Strong | Role::Emphasis => ( "text", match self { Role::Strong => Modifier::BOLD, Role::Emphasis => Modifier::ITALIC, _ => Modifier::empty(), }, ), Role::Punctuation => ("muted", Modifier::empty()), Role::Comment => ("muted", Modifier::ITALIC), Role::Keyword => ("accentSecondary", Modifier::empty()), Role::String | Role::Inserted => ("success", Modifier::empty()), Role::Escape | Role::Type => ("info", Modifier::empty()), Role::Constant => ("warning", Modifier::empty()), Role::Function | Role::ListMarker => ("accent", Modifier::empty()), // the palette's berry, which a resolved theme carries only as `thinkingUltra` Role::Tag => ("thinkingUltra", Modifier::empty()), Role::Heading => ("mdHeading", Modifier::BOLD), Role::Link => ("mdLink", Modifier::empty()), Role::LinkUrl => ("mdLinkUrl", Modifier::empty()), Role::Quote => ("mdQuote", Modifier::ITALIC), Role::Code => ("mdCode", Modifier::empty()), Role::Deleted | Role::Invalid => ("error", Modifier::empty()), } } /// The theme's style for this role: only the foreground and the modifier, so a diff's or a /// card's background shows through. pub fn style(self, styles: &ThemeStyles) -> Style { let (token, modifier) = self.token(); let source = token_style(styles, token).unwrap_or(styles.text); Style { fg: source.fg, ..Style::default() }.add_modifier(modifier) } /// The placeholder color that stands for this role inside syntect. fn marker(self) -> syntect::highlighting::Color { syntect::highlighting::Color { r: self as u8, g: 0x1c, b: 0x5e, a: 0xff } } fn from_marker(color: syntect::highlighting::Color) -> Role { Role::ALL.get(usize::from(color.r)).copied().unwrap_or(Role::Text) } } /// The resolved style a theme token names, for the tokens [`Role::token`] uses. fn token_style(styles: &ThemeStyles, token: &str) -> Option