forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.09.7 MiB37e985dTahinli3 hours ago363 commits

highlight.rs259 lines, 8.3 KiBHistoryRawDownload
1use std::sync::LazyLock;
2
3use syntect::highlighting::ThemeSet;
4use syntect::html::{ClassStyle, css_for_theme_with_class_style, line_tokens_to_classed_spans};
5use syntect::parsing::{ParseState, ScopeStack, SyntaxReference, SyntaxSet};
6use syntect::util::LinesWithEndings;
7
8const MAX_BYTES: usize = 512 * 1024;
9const MAX_LINES: usize = 20_000;
10const CLASS_PREFIX: &str = "hl-";
11const LIGHT_THEME: &str = "InspiredGitHub";
12const DARK_THEME: &str = "base16-ocean.dark";
13const LIGHT_WHEN_AUTO: &str = ":root:not([data-theme=\"dark\"])";
14const LIGHT_WHEN_FORCED: &str = ":root[data-theme=\"light\"]";
15const DARK_WHEN_AUTO: &str = ":root:not([data-theme=\"light\"])";
16const DARK_WHEN_FORCED: &str = ":root[data-theme=\"dark\"]";
17
18static SYNTAX_SET: LazyLock<SyntaxSet> = LazyLock::new(SyntaxSet::load_defaults_newlines);
19static CSS: LazyLock<String> = LazyLock::new(build_css);
20
21fn class_style() -> ClassStyle {
22 ClassStyle::SpacedPrefixed {
23 prefix: CLASS_PREFIX,
24 }
25}
26
27fn find_syntax(file_name: &str, first_line: &str) -> Option<&'static SyntaxReference> {
28 let ss: &'static SyntaxSet = &SYNTAX_SET;
29 file_name
30 .rsplit_once('.')
31 .and_then(|(_, ext)| ss.find_syntax_by_extension(ext))
32 .or_else(|| ss.find_syntax_by_extension(file_name))
33 .or_else(|| ss.find_syntax_by_first_line(first_line))
34}
35
36pub fn highlight_lines(file_name: &str, text: &str) -> Option<Vec<String>> {
37 if text.len() > MAX_BYTES {
38 return None;
39 }
40 let line_count = text.lines().count();
41 if line_count > MAX_LINES {
42 return None;
43 }
44 let first_line = text.lines().next().unwrap_or("");
45 let syntax = find_syntax(file_name, first_line)?;
46 if syntax.name == "Plain Text" {
47 return None;
48 }
49
50 let ss: &SyntaxSet = &SYNTAX_SET;
51 let style = class_style();
52 let mut parse_state = ParseState::new(syntax);
53 let mut stack = ScopeStack::new();
54 let mut out = Vec::with_capacity(line_count);
55
56 for line in LinesWithEndings::from(text) {
57 let ops = parse_state.parse_line(line, ss).ok()?;
58 let mut html = String::with_capacity(line.len() * 2);
59
60 for scope in stack.as_slice() {
61 html.push_str("<span class=\"");
62 let name = scope.build_string();
63 let classes: Vec<String> = name
64 .split('.')
65 .map(|atom| format!("{CLASS_PREFIX}{atom}"))
66 .collect();
67 html.push_str(&classes.join(" "));
68 html.push_str("\">");
69 }
70
71 let (body, _) = line_tokens_to_classed_spans(line, &ops, style, &mut stack).ok()?;
72 html.push_str(&body);
73
74 for _ in 0..stack.len() {
75 html.push_str("</span>");
76 }
77
78 if let Some(pos) = html.rfind('\n') {
79 html.remove(pos);
80 if pos > 0 && html.as_bytes()[pos - 1] == b'\r' {
81 html.remove(pos - 1);
82 }
83 }
84 out.push(html);
85 }
86 Some(out)
87}
88
89fn build_css() -> String {
90 let theme_set = ThemeSet::load_defaults();
91 let light = theme_set
92 .themes
93 .get(LIGHT_THEME)
94 .expect("syntect default theme InspiredGitHub is present");
95 let dark = theme_set
96 .themes
97 .get(DARK_THEME)
98 .expect("syntect default theme base16-ocean.dark is present");
99 let light_css = readable_on_light(
100 &css_for_theme_with_class_style(light, class_style())
101 .expect("generating CSS for the light theme"),
102 );
103 let dark_css = css_for_theme_with_class_style(dark, class_style())
104 .expect("generating CSS for the dark theme");
105 format!(
106 "@media (prefers-color-scheme: light) {{
107{}}}
108{}
109@media (prefers-color-scheme: dark) {{
110{}}}
111{}",
112 scope_css(&light_css, LIGHT_WHEN_AUTO),
113 scope_css(&light_css, LIGHT_WHEN_FORCED),
114 scope_css(&dark_css, DARK_WHEN_AUTO),
115 scope_css(&dark_css, DARK_WHEN_FORCED),
116 )
117}
118
119fn readable_on_light(css: &str) -> String {
120 const BACKGROUND_LUMINANCE: f32 = 0.875;
121 let luminance = |rgb: [u8; 3]| {
122 let [r, g, b] = rgb.map(|channel| {
123 let c = f32::from(channel) / 255.0;
124 if c <= 0.04045 {
125 c / 12.92
126 } else {
127 ((c + 0.055) / 1.055).powf(2.4)
128 }
129 });
130 0.2126 * r + 0.7152 * g + 0.0722 * b
131 };
132 let mut out = String::with_capacity(css.len());
133 for line in css.lines() {
134 let hex = line
135 .trim()
136 .strip_prefix("color: #")
137 .and_then(|rest| rest.strip_suffix(';'));
138 let rgb = hex
139 .filter(|hex| hex.len() == 6)
140 .and_then(|hex| u32::from_str_radix(hex, 16).ok())
141 .map(|value| value.to_be_bytes())
142 .map(|[_, r, g, b]| [r, g, b]);
143 match rgb {
144 Some(mut rgb) => {
145 while (BACKGROUND_LUMINANCE + 0.05) / (luminance(rgb) + 0.05) < 4.5 {
146 rgb = rgb.map(|channel| (f32::from(channel) * 0.95) as u8);
147 }
148 let [r, g, b] = rgb;
149 out.push_str(&format!(" color: #{r:02x}{g:02x}{b:02x};\n"));
150 }
151 None => {
152 out.push_str(line);
153 out.push('\n');
154 }
155 }
156 }
157 out
158}
159
160fn scope_css(css: &str, scope: &str) -> String {
161 let mut out = String::with_capacity(css.len() * 2);
162 for line in css.lines() {
163 match line.strip_suffix('{') {
164 Some(selectors) => {
165 let scoped: Vec<String> = selectors
166 .split(',')
167 .map(|selector| format!("{scope} {}", selector.trim()))
168 .collect();
169 out.push_str(&scoped.join(", "));
170 out.push_str(" {\n");
171 }
172 None => {
173 out.push_str(line);
174 out.push('\n');
175 }
176 }
177 }
178 out
179}
180
181pub fn highlight_css() -> &'static str {
182 CSS.as_str()
183}
184
185#[cfg(test)]
186mod tests {
187 use super::*;
188
189 fn balanced(fragment: &str) -> bool {
190 fragment.matches("<span").count() == fragment.matches("</span>").count()
191 }
192
193 #[test]
194 fn rust_line_count_matches_input() {
195 let src = "fn main() {\n println!(\"hi\");\n}\n";
196 let lines = highlight_lines("main.rs", src).expect("rust is known");
197 assert_eq!(lines.len(), src.lines().count());
198 assert_eq!(lines.len(), 3);
199 assert!(lines.iter().all(|l| !l.contains('\n')));
200 }
201
202 #[test]
203 fn multiline_constructs_stay_balanced_per_line() {
204 let src = "/* a\n b */ let x = \"multi\nline\";\nfn f() {}\n";
205 let lines = highlight_lines("lib.rs", src).expect("rust is known");
206 assert_eq!(lines.len(), 4);
207 for line in &lines {
208 assert!(balanced(line), "unbalanced fragment: {line}");
209 }
210 }
211
212 #[test]
213 fn script_in_string_is_escaped() {
214 let src = "let s = \"<script>alert(1)</script>\";\n";
215 let lines = highlight_lines("page.rs", src).expect("rust is known");
216 let joined = lines.join("\n");
217 assert!(
218 !joined.contains("<script"),
219 "raw script tag leaked: {joined}"
220 );
221 assert!(joined.contains("&lt;script&gt;"), "not escaped: {joined}");
222 assert!(!joined.contains("style="), "inline style emitted: {joined}");
223 }
224
225 #[test]
226 fn unknown_or_plain_names_return_none() {
227 for name in ["data.unknownext", "notes.txt"] {
228 assert!(highlight_lines(name, "hello\n").is_none(), "case {name}");
229 }
230 }
231
232 #[test]
233 fn shebang_is_detected() {
234 let src = "#!/bin/sh\necho hi\n";
235 let lines = highlight_lines("run", src).expect("shebang is detected");
236 assert_eq!(lines.len(), 2);
237 assert!(lines.iter().all(|l| balanced(l)));
238 }
239
240 #[test]
241 fn full_file_name_is_detected() {
242 let src = "all:\n\techo hi\n";
243 assert!(highlight_lines("Makefile", src).is_some());
244 }
245
246 #[test]
247 fn size_limits_return_none() {
248 let many_lines = "x\n".repeat(MAX_LINES + 1);
249 assert!(highlight_lines("a.rs", &many_lines).is_none());
250 let too_big = "a".repeat(MAX_BYTES + 1);
251 assert!(highlight_lines("a.rs", &too_big).is_none());
252 }
253
254 #[test]
255 fn dark_rules_are_scoped_to_their_selectors() {
256 let scoped = scope_css(".hl-a,.hl-b {\n color: #fff;\n}\n", "S");
257 assert_eq!(scoped, "S .hl-a, S .hl-b {\n color: #fff;\n}\n");
258 }
259}