1use std::ops::Range;
7
8use tree_sitter_highlight::{HighlightEvent, Highlighter as TsHighlighter};
9
10use crate::syntax::{HIGHLIGHT_NAMES, LanguageRegistry};
11
12pub struct Highlighter {
13 registry: LanguageRegistry,
14 theme: SyntaxTheme,
15}
16
17#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
21pub enum SyntaxTheme {
22 #[default]
23 OneHalfDark,
24 OneHalfLight,
25 Dracula,
26}
27
28#[derive(Debug, Clone, PartialEq, Eq)]
30pub struct StyledRange {
31 pub range: Range<usize>,
32 pub fg: (u8, u8, u8),
33 pub bold: bool,
34 pub italic: bool,
35}
36
37impl Default for Highlighter {
38 fn default() -> Self {
39 Self::new(SyntaxTheme::default())
40 }
41}
42
43impl Highlighter {
44 pub fn new(syntax: SyntaxTheme) -> Self {
46 Self {
47 registry: LanguageRegistry::build(),
48 theme: syntax,
49 }
50 }
51
52 pub fn highlight(&self, path: &str, content: &str) -> Vec<Vec<StyledRange>> {
56 let bounds = crate::syntax::line_bounds(content);
57 let mut out: Vec<Vec<StyledRange>> = vec![Vec::new(); bounds.len()];
58
59 let Some(entry) = self.registry.for_path(path) else {
60 return out;
61 };
62 let Some(config) = entry.config.as_ref() else {
63 return out;
64 };
65
66 let mut ts = TsHighlighter::new();
67 let Ok(events) = ts.highlight(config, content.as_bytes(), None, |_| None) else {
68 return out;
69 };
70
71 let starts: Vec<usize> = bounds.iter().map(|&(s, _)| s).collect();
72 let mut stack: Vec<usize> = Vec::new();
73 for event in events {
74 let Ok(event) = event else {
75 return out;
76 };
77 match event {
78 HighlightEvent::HighlightStart(h) => stack.push(h.0),
79 HighlightEvent::HighlightEnd => {
80 stack.pop();
81 }
82 HighlightEvent::Source { start, end } => {
83 if let Some(&name_idx) = stack.last()
84 && let Some(name) = HIGHLIGHT_NAMES.get(name_idx)
85 && let Some(style) = self.theme.style(name)
86 {
87 crate::syntax::split_range_by_line(
88 &bounds,
89 &starts,
90 &(start..end),
91 |li, r| {
92 if let Some(line) = out.get_mut(li) {
93 line.push(StyledRange {
94 range: r,
95 fg: style.fg,
96 bold: style.bold,
97 italic: style.italic,
98 });
99 }
100 },
101 );
102 }
103 }
104 }
105 }
106 out
107 }
108
109 pub fn scope_index(&self, path: &str, content: &str) -> crate::syntax::ScopeIndex {
112 self.registry.scope_index(path, content)
113 }
114
115 pub fn syntactic_emphasis(&self, file: &mut crate::model::FileDiff) -> bool {
118 self.registry.syntactic_emphasis(file)
119 }
120}
121
122struct StyleSpec {
123 fg: (u8, u8, u8),
124 bold: bool,
125 italic: bool,
126}
127
128impl SyntaxTheme {
129 fn style(self, name: &str) -> Option<StyleSpec> {
132 let category = name.split('.').next().unwrap_or(name);
133 let italic = category == "comment";
134 let fg = self.color(category)?;
135 Some(StyleSpec {
136 fg,
137 bold: false,
138 italic,
139 })
140 }
141
142 fn color(self, category: &str) -> Option<(u8, u8, u8)> {
143 let c = match self {
144 SyntaxTheme::OneHalfDark => match category {
145 "keyword" | "label" => (198, 120, 221),
146 "function" => (97, 175, 239),
147 "type" | "constructor" => (229, 192, 123),
148 "string" => (152, 195, 121),
149 "comment" => (126, 134, 145),
152 "constant" | "number" | "attribute" => (209, 154, 102),
153 "operator" | "escape" => (86, 182, 194),
154 "property" | "tag" => (224, 108, 117),
155 "variable" | "punctuation" => (171, 178, 191),
156 _ => return None,
157 },
158 SyntaxTheme::OneHalfLight => match category {
159 "keyword" | "label" => (166, 38, 164),
160 "function" => (64, 120, 242),
161 "type" | "constructor" => (193, 132, 1),
162 "string" => (80, 161, 79),
163 "comment" => (160, 161, 167),
164 "constant" | "number" | "attribute" => (152, 104, 1),
165 "operator" | "escape" => (1, 132, 188),
166 "property" | "tag" => (228, 86, 73),
167 "variable" | "punctuation" => (56, 58, 66),
168 _ => return None,
169 },
170 SyntaxTheme::Dracula => match category {
171 "keyword" | "label" | "tag" | "operator" => (255, 121, 198),
172 "function" | "property" => (80, 250, 123),
173 "type" | "constructor" => (139, 233, 253),
174 "string" => (241, 250, 140),
175 "comment" => (98, 114, 164),
176 "constant" | "number" => (189, 147, 249),
177 "escape" | "attribute" => (255, 184, 108),
178 "variable" | "punctuation" => (248, 248, 242),
179 _ => return None,
180 },
181 };
182 Some(c)
183 }
184}
185
186#[cfg(test)]
187mod tests {
188 use super::*;
189
190 #[test]
191 fn python_keywords_get_distinct_color() {
192 let hl = Highlighter::default();
193 let lines = hl.highlight("a.py", "def f():\n return 1\n");
194 assert_eq!(lines.len(), 2);
195 let colors: std::collections::HashSet<(u8, u8, u8)> =
196 lines[0].iter().map(|r| r.fg).collect();
197 assert!(colors.len() > 1, "expected multiple colors, got {colors:?}");
198 }
199
200 #[test]
201 fn ranges_cover_within_line_bounds() {
202 let hl = Highlighter::default();
203 let src = "fn main() { let x = \"hi\"; }\n";
204 let lines = hl.highlight("a.rs", src);
205 let visible = src.trim_end();
206 for r in &lines[0] {
207 assert!(r.range.end <= visible.len());
208 assert!(r.range.start < r.range.end);
209 }
210 }
211
212 #[test]
213 fn multiline_string_state_carries_across_lines() {
214 let hl = Highlighter::default();
215 let src = "s = \"\"\"first\nsecond\nthird\"\"\"\nx = 1\n";
216 let lines = hl.highlight("a.py", src);
217 let string_color = lines[0].iter().last().map(|r| r.fg).expect("line 0 styled");
218 assert!(
219 lines[1].iter().all(|r| r.fg == string_color),
220 "inside-string line must keep string color"
221 );
222 }
223
224 #[test]
225 fn unknown_extension_yields_plain_lines() {
226 let hl = Highlighter::default();
227 let lines = hl.highlight("file.zzz-unknown", "a\nb\n");
228 assert_eq!(lines, vec![Vec::new(), Vec::new()]);
229 }
230
231 #[test]
232 fn syntax_theme_changes_the_foreground_palette() {
233 let src = "fn main() { let x = 1; }\n";
234 let dark = Highlighter::new(SyntaxTheme::OneHalfDark).highlight("a.rs", src);
235 let light = Highlighter::new(SyntaxTheme::OneHalfLight).highlight("a.rs", src);
236 assert_ne!(dark, light, "a different syntax theme recolors the line");
237 }
238}