Skip to main content

smart_markdown/
highlight.rs

1//! Syntax highlighting for fenced code blocks.
2//!
3//! This module provides syntect-based syntax highlighting, theme management,
4//! and terminal background detection. It is gated behind the `syntax-highlight`
5//! feature (enabled by default).
6//!
7//! # Built-in themes
8//!
9//! Seven themes are bundled with the crate:
10//!
11//! - `base16-eighties.dark` (default for dark mode)
12//! - `base16-ocean.dark`
13//! - `base16-mocha.dark`
14//! - `base16-ocean.light`
15//! - `InspiredGitHub`
16//! - `Solarized (dark)`
17//! - `Solarized (light)` (default for light mode)
18
19use std::sync::OnceLock;
20use syntect::highlighting::{Theme, ThemeSet};
21use syntect::parsing::SyntaxSet;
22
23static SYNTAX_SET: OnceLock<SyntaxSet> = OnceLock::new();
24static THEME_SET: OnceLock<ThemeSet> = OnceLock::new();
25
26/// Controls which syntax highlighting theme is applied to code blocks.
27#[derive(Debug, Clone, Copy, PartialEq, Eq)]
28pub enum ThemeMode {
29    /// Dark background. Uses "Base16 Eighties Dark".
30    Dark,
31    /// Light background. Uses "Solarized (light)".
32    Light,
33    /// Detects terminal background color at render time using `terminal-colorsaurus`.
34    Auto,
35}
36
37impl ThemeMode {
38    /// Detect the terminal background color using `terminal-colorsaurus`.
39    ///
40    /// Falls back to `ThemeMode::Dark` if detection fails.
41    pub fn detect() -> Self {
42        use terminal_colorsaurus::{theme_mode, QueryOptions};
43        match theme_mode(QueryOptions::default()) {
44            Ok(terminal_colorsaurus::ThemeMode::Dark) => ThemeMode::Dark,
45            Ok(terminal_colorsaurus::ThemeMode::Light) => ThemeMode::Light,
46            Err(_) => ThemeMode::Dark,
47        }
48    }
49}
50
51/// Returns the global syntax set (lazy-initialized).
52///
53/// Contains syntax definitions for all languages supported by syntect.
54pub fn syntax_set() -> &'static SyntaxSet {
55    SYNTAX_SET.get_or_init(SyntaxSet::load_defaults_newlines)
56}
57
58/// Returns the global theme set (lazy-initialized).
59///
60/// Contains the seven bundled color themes.
61pub fn themes() -> &'static ThemeSet {
62    THEME_SET.get_or_init(ThemeSet::load_defaults)
63}
64
65/// Lists the names of all available syntax highlighting themes.
66///
67/// ```rust
68/// # #[cfg(feature = "syntax-highlight")] {
69/// let themes = smart_markdown::highlight::list_themes();
70/// assert!(themes.contains(&"Solarized (dark)"));
71/// # }
72/// ```
73pub fn list_themes() -> Vec<&'static str> {
74    themes().themes.keys().map(|k| k.as_str()).collect()
75}
76
77fn resolve_theme(theme_mode: ThemeMode, custom: Option<&str>) -> &Theme {
78    if let Some(name) = custom
79        && let Some(theme) = themes().themes.get(name) {
80            return theme;
81        }
82    let resolved = match theme_mode {
83        ThemeMode::Auto => ThemeMode::detect(),
84        other => other,
85    };
86    match resolved {
87        ThemeMode::Dark => &themes().themes["base16-eighties.dark"],
88        ThemeMode::Light => &themes().themes["Solarized (light)"],
89        ThemeMode::Auto => unreachable!(),
90    }
91}
92
93/// Highlight source code lines using syntect.
94///
95/// Returns `None` if the language is not recognized. On success, returns
96/// ANSI-escaped lines including a header bar and footer.
97///
98/// - `lang` — syntect language token (e.g. `"rust"`, `"python"`, `"bash"`)
99/// - `lines` — source lines to highlight
100/// - `theme_mode` — dark/light/auto theme selection
101/// - `custom_theme` — optional theme name override (see [`list_themes`])
102pub fn highlight_lines(
103    lang: &str,
104    lines: &[String],
105    theme_mode: ThemeMode,
106    custom_theme: Option<&str>,
107) -> Option<Vec<String>> {
108    use syntect::easy::HighlightLines;
109    use syntect::highlighting::FontStyle;
110
111    let syntax = syntax_set().find_syntax_by_token(lang)?;
112    let theme = resolve_theme(theme_mode, custom_theme);
113    let mut highlighter = HighlightLines::new(syntax, theme);
114
115    let mut out = Vec::new();
116    out.push(format!("\x1b[1m┌ \x1b[34m{lang}\x1b[0m"));
117
118    for line in lines {
119        let ranges = highlighter.highlight_line(line, syntax_set()).ok()?;
120        let mut rendered = String::new();
121        for (style, text) in &ranges {
122            let mut codes: Vec<String> = Vec::new();
123
124            if style.font_style.contains(FontStyle::BOLD) {
125                codes.push("1".into());
126            }
127            if style.font_style.contains(FontStyle::ITALIC) {
128                codes.push("3".into());
129            }
130            if style.font_style.contains(FontStyle::UNDERLINE) {
131                codes.push("4".into());
132            }
133
134            let color = style.foreground;
135            let (r, g, b) = boost_rgb(color.r, color.g, color.b);
136            codes.push(format!("38;2;{r};{g};{b}"));
137
138            if !codes.is_empty() {
139                let escape = codes.join(";");
140                rendered.push_str(&format!("\x1b[{escape}m"));
141            }
142            rendered.push_str(text);
143        }
144        rendered.push_str("\x1b[0m");
145        out.push(format!("\x1b[1m│\x1b[0m {rendered}"));
146    }
147
148    out.push("\x1b[1m└─\x1b[0m".to_string());
149    out.push("\x1b[0m".to_string());
150    Some(out)
151}
152
153fn boost_rgb(r: u8, g: u8, b: u8) -> (u8, u8, u8) {
154    let max_ch = r.max(g).max(b);
155    if max_ch < 10 {
156        return (r, g, b);
157    }
158    (
159        ((r as u16 * 255 + max_ch as u16 / 2) / max_ch as u16).min(255) as u8,
160        ((g as u16 * 255 + max_ch as u16 / 2) / max_ch as u16).min(255) as u8,
161        ((b as u16 * 255 + max_ch as u16 / 2) / max_ch as u16).min(255) as u8,
162    )
163}
164
165#[cfg(test)]
166mod tests {
167    use super::*;
168
169    #[test]
170    fn boost_rgb_full_saturation() {
171        let (_, _, b) = boost_rgb(100, 50, 200);
172        assert_eq!(b, 255, "brightest channel should be 255");
173    }
174
175    #[test]
176    fn boost_rgb_preserves_ratio() {
177        let (r, g, b) = boost_rgb(50, 100, 0);
178        assert_eq!(g, 255);
179        assert!((126..=129).contains(&r), "red should be ~127, got {r}");
180        assert_eq!(b, 0);
181    }
182
183    #[test]
184    fn boost_rgb_near_black_unchanged() {
185        assert_eq!(boost_rgb(5, 5, 5), (5, 5, 5));
186    }
187
188    #[test]
189    fn boost_rgb_already_bright() {
190        assert_eq!(boost_rgb(255, 128, 64), (255, 128, 64));
191    }
192
193    #[test]
194    fn syntax_set_initializes() {
195        let ss = syntax_set();
196        assert!(ss.find_syntax_by_token("rust").is_some());
197    }
198
199    #[test]
200    fn themes_loads_all_seven() {
201        let names = list_themes();
202        assert_eq!(names.len(), 7, "expected 7 bundled themes");
203    }
204
205    #[test]
206    fn themes_have_expected_keys() {
207        let names = list_themes();
208        assert!(names.contains(&"base16-eighties.dark"));
209        assert!(names.contains(&"base16-ocean.dark"));
210        assert!(names.contains(&"base16-mocha.dark"));
211        assert!(names.contains(&"base16-ocean.light"));
212        assert!(names.contains(&"InspiredGitHub"));
213        assert!(names.contains(&"Solarized (dark)"));
214        assert!(names.contains(&"Solarized (light)"));
215    }
216
217    #[test]
218    fn resolve_theme_dark_explicit() {
219        let theme = resolve_theme(ThemeMode::Dark, None);
220        assert_eq!(theme.name.as_deref(), Some("Base16 Eighties Dark"));
221    }
222
223    #[test]
224    fn resolve_theme_light_explicit() {
225        let theme = resolve_theme(ThemeMode::Light, None);
226        assert_eq!(theme.name.as_deref(), Some("Solarized (light)"));
227    }
228
229    #[test]
230    fn resolve_theme_custom_name() {
231        let theme = resolve_theme(ThemeMode::Dark, Some("InspiredGitHub"));
232        assert_eq!(theme.name.as_deref(), Some("GitHub"));
233    }
234
235    #[test]
236    fn resolve_theme_custom_invalid_falls_back() {
237        let theme = resolve_theme(ThemeMode::Dark, Some("doesnotexist"));
238        assert_eq!(theme.name.as_deref(), Some("Base16 Eighties Dark"));
239    }
240
241    #[test]
242    fn highlight_lines_rust() {
243        let lines: Vec<String> = vec!["fn main() {".into(), "    let x = 42;".into(), "}".into()];
244        let result = highlight_lines("rust", &lines, ThemeMode::Dark, None).unwrap();
245        assert!(result.len() > 3);
246        assert!(result[0].contains("rust"));
247        assert!(result[1].contains("fn"));
248        assert!(result.iter().any(|l| l.contains("38;2;")));
249    }
250
251    #[test]
252    fn highlight_lines_python() {
253        let lines: Vec<String> = vec!["def hello():".into(), "    return 1".into()];
254        let result = highlight_lines("python", &lines, ThemeMode::Dark, None).unwrap();
255        assert!(result[0].contains("python"));
256        assert!(result.iter().any(|l| l.contains("def")));
257    }
258
259    #[test]
260    fn highlight_lines_unknown_lang() {
261        let lines: Vec<String> = vec!["some code".into()];
262        assert!(highlight_lines("zzz", &lines, ThemeMode::Dark, None).is_none());
263    }
264
265    #[test]
266    fn highlight_lines_custom_theme() {
267        let lines: Vec<String> = vec!["let x = 1;".into()];
268        let result = highlight_lines("rust", &lines, ThemeMode::Dark, Some("base16-ocean.dark")).unwrap();
269        assert!(!result.is_empty());
270    }
271
272    #[test]
273    fn highlight_lines_empty_code() {
274        let lines: Vec<String> = vec![];
275        let result = highlight_lines("rust", &lines, ThemeMode::Dark, None).unwrap();
276        assert!(result[0].contains("rust"));
277        assert!(result.contains(&"\x1b[1m└─\x1b[0m".to_string()));
278    }
279
280    #[test]
281    fn theme_mode_detect_returns_dark_or_light() {
282        let mode = ThemeMode::detect();
283        assert!(matches!(mode, ThemeMode::Dark | ThemeMode::Light));
284    }
285}