//! Syntax highlighting engine for the TUI. //! //! Wraps [syntect] with the [two_face] grammar and theme bundles to provide //! ~250-language syntax highlighting and bundled color themes. The module //! owns five process-global singletons: //! //! | Singleton | Type | Purpose | //! |---|---|---| //! | `SYNTAX_SET` | `OnceLock` | Grammar database, immutable after init | //! | `THEME` | `OnceLock>` | Active color theme, swappable at runtime | //! | `THEME_REVISION` | `AtomicU64` | Invalidates rendered-content caches after theme swaps | //! | `THEME_OVERRIDE` | `OnceLock>` | Persisted user preference (write-once) | //! | `CODEX_HOME` | `OnceLock>` | Root for custom `.tmTheme` discovery | //! //! **Lifecycle:** call [`set_theme_override`] once at startup (after the final //! config is resolved) to persist the user preference and seed the `THEME` //! lock. After that, [`set_syntax_theme`] and [`current_syntax_theme`] can //! swap/snapshot the theme for live preview. All highlighting functions read //! the theme via `theme_lock()`. Unit tests isolate the active theme and its //! revision per thread so parallel tests cannot change each other’s rendering. //! Generic renderers preserve configured theme foregrounds because callers may paint them on //! shaded surfaces. Diff rendering separately resolves contrast against its actual row fills. //! ANSI colors remain owned by the terminal palette. //! //! **Guardrails:** inputs exceeding 512 KB or 10 000 lines, or containing an //! individual line longer than 4 KiB, are rejected early (returns `None`) to //! prevent pathological CPU/memory usage. Callers must fall back to plain //! unstyled text. use super::model_themes; use ratatui::style::Color as RtColor; use ratatui::style::Modifier; use ratatui::style::Style; use ratatui::text::Line; use ratatui::text::Span; use std::path::Path; use std::path::PathBuf; use std::sync::OnceLock; use std::sync::RwLock; #[cfg(not(test))] use std::sync::atomic::AtomicU64; #[cfg(not(test))] use std::sync::atomic::Ordering; use syntect::easy::HighlightLines; use syntect::highlighting::Color as SyntectColor; use syntect::highlighting::FontStyle; use syntect::highlighting::Highlighter; use syntect::highlighting::Style as SyntectStyle; use syntect::highlighting::Theme; use syntect::highlighting::ThemeSet; use syntect::parsing::Scope; use syntect::parsing::SyntaxReference; use syntect::parsing::SyntaxSet; use syntect::util::LinesWithEndings; use two_face::theme::EmbeddedThemeName; #[path = "highlight_streaming.rs"] mod streaming; pub(crate) use streaming::StreamingCodeHighlighter; // -- Global singletons ------------------------------------------------------- static SYNTAX_SET: OnceLock = OnceLock::new(); #[cfg(not(test))] static THEME: OnceLock> = OnceLock::new(); #[cfg(not(test))] static THEME_REVISION: AtomicU64 = AtomicU64::new(0); static THEME_OVERRIDE: OnceLock> = OnceLock::new(); static CODEX_HOME: OnceLock> = OnceLock::new(); #[cfg(test)] thread_local! { static TEST_THEME: std::cell::OnceCell>> = const { std::cell::OnceCell::new() }; static TEST_THEME_REVISION: std::cell::Cell = const { std::cell::Cell::new(0) }; } // Syntect/bat encode ANSI palette semantics in alpha: // `a=0` => indexed ANSI palette via RGB payload, `a=1` => terminal default. const ANSI_ALPHA_INDEX: u8 = 0x00; const ANSI_ALPHA_DEFAULT: u8 = 0x01; const OPAQUE_ALPHA: u8 = 0xFF; fn syntax_set() -> &'static SyntaxSet { SYNTAX_SET.get_or_init(two_face::syntax::extra_newlines) } // NOTE: We intentionally do NOT emit a runtime diagnostic when an ANSI-family // theme (ansi, base16, base16-256) lacks the expected alpha-channel marker // encoding. If the upstream two_face/syntect theme format changes, the // `ansi_themes_use_only_ansi_palette_colors` test will catch it at build // time — long before it reaches users. A runtime warning would be // unactionable noise since users can't fix upstream themes. /// Set the user-configured syntax theme override and codex home path. /// /// Call this with the **final resolved config** (after onboarding, resume, and /// fork reloads complete). The first call persists `name` and `codex_home` in /// `OnceLock`s used by startup/default theme resolution. /// /// Subsequent calls cannot change the persisted `OnceLock` values, but they /// still update the runtime theme immediately for live preview flows. /// /// Returns user-facing warnings for actionable configuration issues, such as /// unknown/invalid theme names or duplicate override persistence. pub(crate) fn set_theme_override( name: Option, codex_home: Option, ) -> Option { let warning = validate_theme_name(name.as_deref(), codex_home.as_deref()); let override_set_ok = THEME_OVERRIDE.set(name.clone()).is_ok(); let codex_home_set_ok = CODEX_HOME.set(codex_home.clone()).is_ok(); #[cfg(not(test))] let initialized = THEME.get().is_some(); #[cfg(test)] let initialized = TEST_THEME.with(|theme| theme.get().is_some()); if initialized { set_syntax_theme(resolve_theme_with_override( name.as_deref(), codex_home.as_deref(), )); } if !override_set_ok || !codex_home_set_ok { // This should never happen in practice — set_theme_override is only // called once at startup. Keep as a debug breadcrumb in case a second // call site is added in the future. tracing::debug!("set_theme_override called more than once; OnceLock values unchanged"); } warning } /// Check whether a theme name resolves to a bundled theme or a custom /// `.tmTheme` file. Returns a user-facing warning when it does not. pub(crate) fn validate_theme_name(name: Option<&str>, codex_home: Option<&Path>) -> Option { let name = name?; let custom_theme_path_display = codex_home .map(|home| custom_theme_path(name, home).display().to_string()) .unwrap_or_else(|| format!("$CODEX_HOME/themes/{name}.tmTheme")); if resolve_theme_by_name(name, codex_home).is_some() { return None; } // Custom themes must parse successfully; an unreadable/invalid file should // still surface a startup warning so users can diagnose configuration issues. if let Some(home) = codex_home { let custom_path = custom_theme_path(name, home); if custom_path.try_exists().unwrap_or(/*default*/ true) { return Some(format!( "Custom theme \"{name}\" at {custom_theme_path_display} could not \ be loaded (invalid .tmTheme format). Falling back to the default theme." )); } } Some(format!( "Theme \"{name}\" not found. Using the default theme. \ To use a custom theme, place a .tmTheme file at \ {custom_theme_path_display}." )) } /// Map a kebab-case theme name to the corresponding `EmbeddedThemeName`. fn parse_theme_name(name: &str) -> Option { match name { "ansi" => Some(EmbeddedThemeName::Ansi), "base16" => Some(EmbeddedThemeName::Base16), "base16-eighties-dark" => Some(EmbeddedThemeName::Base16EightiesDark), "base16-mocha-dark" => Some(EmbeddedThemeName::Base16MochaDark), "base16-ocean-dark" => Some(EmbeddedThemeName::Base16OceanDark), "base16-ocean-light" => Some(EmbeddedThemeName::Base16OceanLight), "base16-256" => Some(EmbeddedThemeName::Base16_256), "catppuccin-frappe" => Some(EmbeddedThemeName::CatppuccinFrappe), "catppuccin-latte" => Some(EmbeddedThemeName::CatppuccinLatte), "catppuccin-macchiato" => Some(EmbeddedThemeName::CatppuccinMacchiato), "catppuccin-mocha" => Some(EmbeddedThemeName::CatppuccinMocha), "coldark-cold" => Some(EmbeddedThemeName::ColdarkCold), "coldark-dark" => Some(EmbeddedThemeName::ColdarkDark), "dark-neon" => Some(EmbeddedThemeName::DarkNeon), "dracula" => Some(EmbeddedThemeName::Dracula), "github" => Some(EmbeddedThemeName::Github), "gruvbox-dark" => Some(EmbeddedThemeName::GruvboxDark), "gruvbox-light" => Some(EmbeddedThemeName::GruvboxLight), "inspired-github" => Some(EmbeddedThemeName::InspiredGithub), "1337" => Some(EmbeddedThemeName::Leet), "monokai-extended" => Some(EmbeddedThemeName::MonokaiExtended), "monokai-extended-bright" => Some(EmbeddedThemeName::MonokaiExtendedBright), "monokai-extended-light" => Some(EmbeddedThemeName::MonokaiExtendedLight), "monokai-extended-origin" => Some(EmbeddedThemeName::MonokaiExtendedOrigin), "nord" => Some(EmbeddedThemeName::Nord), "one-half-dark" => Some(EmbeddedThemeName::OneHalfDark), "one-half-light" => Some(EmbeddedThemeName::OneHalfLight), "solarized-dark" => Some(EmbeddedThemeName::SolarizedDark), "solarized-light" => Some(EmbeddedThemeName::SolarizedLight), "sublime-snazzy" => Some(EmbeddedThemeName::SublimeSnazzy), "two-dark" => Some(EmbeddedThemeName::TwoDark), "zenburn" => Some(EmbeddedThemeName::Zenburn), _ => None, } } /// Build the expected path for a custom theme file. fn custom_theme_path(name: &str, codex_home: &Path) -> PathBuf { codex_home.join("themes").join(format!("{name}.tmTheme")) } /// Try to load a custom `.tmTheme` file from `{codex_home}/themes/{name}.tmTheme`. fn load_custom_theme(name: &str, codex_home: &Path) -> Option { ThemeSet::get_theme(custom_theme_path(name, codex_home)).ok() } fn adaptive_default_theme_selection() -> (EmbeddedThemeName, &'static str) { match crate::terminal_palette::default_bg() { Some(bg) if crate::color::is_light(bg) => { (EmbeddedThemeName::CatppuccinLatte, "catppuccin-latte") } _ => (EmbeddedThemeName::CatppuccinMocha, "catppuccin-mocha"), } } fn adaptive_default_embedded_theme_name() -> EmbeddedThemeName { adaptive_default_theme_selection().0 } /// Return the kebab-case name of the adaptive default syntax theme selected /// from terminal background lightness. pub(crate) fn adaptive_default_theme_name() -> &'static str { adaptive_default_theme_selection().1 } /// Build the theme from current override/default-theme settings. /// Extracted from the old `theme()` init closure so it can be reused. fn resolve_theme_with_override(name: Option<&str>, codex_home: Option<&Path>) -> Theme { let ts = two_face::theme::extra(); // Honor user-configured theme if valid. if let Some(name) = name { if let Some(theme) = resolve_theme_by_name(name, codex_home) { return theme; } tracing::debug!("Theme \"{name}\" not recognized; using default theme"); } ts.get(adaptive_default_embedded_theme_name()).clone() } /// Build the theme from current override/default-theme settings. /// Extracted from the old `theme()` init closure so it can be reused. fn build_default_theme() -> Theme { let name = THEME_OVERRIDE.get().and_then(|name| name.as_deref()); let codex_home = CODEX_HOME .get() .and_then(|codex_home| codex_home.as_deref()); resolve_theme_with_override(name, codex_home) } fn theme_lock() -> impl std::ops::Deref> { #[cfg(not(test))] { THEME.get_or_init(|| RwLock::new(build_default_theme())) } #[cfg(test)] TEST_THEME.with(|theme| { theme .get_or_init(|| std::sync::Arc::new(RwLock::new(build_default_theme()))) .clone() }) } /// Swap the active syntax theme at runtime and invalidate rendered-content caches. pub(crate) fn set_syntax_theme(theme: Theme) { let active_theme = theme_lock(); let mut guard = match active_theme.write() { Ok(guard) => guard, Err(poisoned) => poisoned.into_inner(), }; *guard = theme; #[cfg(not(test))] THEME_REVISION.fetch_add(1, Ordering::Release); #[cfg(test)] TEST_THEME_REVISION.with(|revision| revision.set(revision.get().wrapping_add(1))); } /// Return the revision of the active syntax theme for rendered-content caches. pub(crate) fn syntax_theme_revision() -> u64 { #[cfg(not(test))] { THEME_REVISION.load(Ordering::Acquire) } #[cfg(test)] TEST_THEME_REVISION.with(std::cell::Cell::get) } /// Clone the current syntax theme (e.g. to save for cancel-restore). pub(crate) fn current_syntax_theme() -> Theme { with_syntax_theme(Theme::clone) } /// Borrow the active theme for one synchronous render operation. pub(crate) fn with_syntax_theme(f: impl FnOnce(&Theme) -> T) -> T { let active_theme = theme_lock(); let theme = active_theme .read() .unwrap_or_else(std::sync::PoisonError::into_inner); f(&theme) } /// An explicit diff background, including the ANSI terminal-default marker. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub(crate) enum DiffScopeBackground { Rgb((u8, u8, u8)), TerminalDefault, } /// Background colors extracted from syntax theme diff/markup scopes. /// /// These are theme-provided colors, not yet adapted for any particular color /// depth. [`diff_render`](crate::diff_render) converts them to ratatui /// `Color` values via `color_from_rgb_for_level` after deciding whether to /// emit truecolor or quantized ANSI-256. /// /// Both fields are `None` when the active theme defines no relevant scope /// backgrounds, in which case the diff renderer falls back to its hardcoded /// palette. #[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] pub(crate) struct DiffScopeBackgrounds { pub inserted: Option, pub deleted: Option, } /// Query the active syntax theme for diff-scope background colors. /// /// Prefers `markup.inserted` / `markup.deleted` (the TextMate convention used /// by most VS Code themes) and falls back to `diff.inserted` / `diff.deleted` /// (used by some older `.tmTheme` files). pub(crate) fn diff_scope_backgrounds() -> DiffScopeBackgrounds { let theme = current_syntax_theme(); diff_scope_backgrounds_for_theme(&theme) } /// Pure extraction helper, separated from the global theme singleton so tests /// can pass arbitrary themes. fn diff_scope_backgrounds_for_theme(theme: &Theme) -> DiffScopeBackgrounds { let highlighter = Highlighter::new(theme); let inserted = scope_background(&highlighter, "markup.inserted") .or_else(|| scope_background(&highlighter, "diff.inserted")); let deleted = scope_background(&highlighter, "markup.deleted") .or_else(|| scope_background(&highlighter, "diff.deleted")); DiffScopeBackgrounds { inserted, deleted } } /// Extract the background color for a single TextMate scope, if defined. fn scope_background( highlighter: &Highlighter<'_>, scope_name: &str, ) -> Option { let scope = Scope::new(scope_name).ok()?; let bg = highlighter.style_mod_for_stack(&[scope]).background?; Some(if bg.a == ANSI_ALPHA_DEFAULT { DiffScopeBackground::TerminalDefault } else { DiffScopeBackground::Rgb((bg.r, bg.g, bg.b)) }) } pub(crate) const INLINE_CODE_SCOPES: &[&str] = &[ "markup.inline.raw.string.markdown", "markup.raw.inline.markdown", ]; /// Query the active syntax theme for the first foreground style provided by the /// supplied TextMate scopes. pub(crate) fn foreground_style_for_scopes(scope_names: &[&str]) -> Option