forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.07.1 MiB490f099Tahinli7 hours ago322 commits

highlight.rs318 lines, 11.5 KiBHistoryRawDownload
1//! syntect class-based highlighting.
2//!
3//! Output is class-based (`hl-` prefix) and never carries inline styles, so the
4//! CSP without 'unsafe-inline' is respected. Each source line becomes one HTML
5//! fragment whose spans are balanced: scopes that continue across a line break
6//! are closed at the end of the line and reopened at the start of the next.
7
8// Nothing outside the tests calls this module until the blob view is wired up.
9#![allow(dead_code)]
10
11use std::sync::LazyLock;
12
13use syntect::highlighting::ThemeSet;
14use syntect::html::{ClassStyle, css_for_theme_with_class_style, line_tokens_to_classed_spans};
15use syntect::parsing::{ParseState, ScopeStack, SyntaxReference, SyntaxSet};
16use syntect::util::LinesWithEndings;
17
18/// Inputs above this many bytes are not highlighted.
19const MAX_BYTES: usize = 512 * 1024;
20/// Inputs above this many lines are not highlighted.
21const MAX_LINES: usize = 20_000;
22const CLASS_PREFIX: &str = "hl-";
23const LIGHT_THEME: &str = "InspiredGitHub";
24const DARK_THEME: &str = "base16-ocean.dark";
25/// Scope for the light rules when the page has no explicit theme.
26const LIGHT_WHEN_AUTO: &str = ":root:not([data-theme=\"dark\"])";
27/// Scope for the light rules when the user picked the light theme.
28const LIGHT_WHEN_FORCED: &str = ":root[data-theme=\"light\"]";
29/// Scope for the dark rules when the page has no explicit theme.
30const DARK_WHEN_AUTO: &str = ":root:not([data-theme=\"light\"])";
31/// Scope for the dark rules when the user picked the dark theme.
32const DARK_WHEN_FORCED: &str = ":root[data-theme=\"dark\"]";
33
34// Newline-aware syntaxes are required because input is fed through LinesWithEndings.
35static SYNTAX_SET: LazyLock<SyntaxSet> = LazyLock::new(SyntaxSet::load_defaults_newlines);
36static CSS: LazyLock<String> = LazyLock::new(build_css);
37
38fn class_style() -> ClassStyle {
39 ClassStyle::SpacedPrefixed {
40 prefix: CLASS_PREFIX,
41 }
42}
43
44fn find_syntax(file_name: &str, first_line: &str) -> Option<&'static SyntaxReference> {
45 let ss: &'static SyntaxSet = &SYNTAX_SET;
46 file_name
47 .rsplit_once('.')
48 .and_then(|(_, ext)| ss.find_syntax_by_extension(ext))
49 .or_else(|| ss.find_syntax_by_extension(file_name))
50 .or_else(|| ss.find_syntax_by_first_line(first_line))
51}
52
53/// Highlights `text` as the language implied by `file_name` (extension, then
54/// full file name, then shebang/first line). Returns one HTML fragment per
55/// line without the trailing newline, or `None` when the language is unknown
56/// or plain text, or the input exceeds the size limits.
57pub fn highlight_lines(file_name: &str, text: &str) -> Option<Vec<String>> {
58 if text.len() > MAX_BYTES {
59 return None;
60 }
61 let line_count = text.lines().count();
62 if line_count > MAX_LINES {
63 return None;
64 }
65 let first_line = text.lines().next().unwrap_or("");
66 let syntax = find_syntax(file_name, first_line)?;
67 if syntax.name == "Plain Text" {
68 return None;
69 }
70
71 let ss: &SyntaxSet = &SYNTAX_SET;
72 let style = class_style();
73 let mut parse_state = ParseState::new(syntax);
74 // Holds the scopes that are still open at the start of the next line.
75 let mut stack = ScopeStack::new();
76 let mut out = Vec::with_capacity(line_count);
77
78 for line in LinesWithEndings::from(text) {
79 let ops = parse_state.parse_line(line, ss).ok()?;
80 let mut html = String::with_capacity(line.len() * 2);
81
82 // Reopen spans for scopes carried over from the previous line. Each
83 // scope's classes are its dot-separated atoms, each with the prefix.
84 for scope in stack.as_slice() {
85 html.push_str("<span class=\"");
86 let name = scope.build_string();
87 let classes: Vec<String> = name
88 .split('.')
89 .map(|atom| format!("{CLASS_PREFIX}{atom}"))
90 .collect();
91 html.push_str(&classes.join(" "));
92 html.push_str("\">");
93 }
94
95 let (body, _) = line_tokens_to_classed_spans(line, &ops, style, &mut stack).ok()?;
96 html.push_str(&body);
97
98 // Close every span still open at end of line; the stack persists.
99 for _ in 0..stack.len() {
100 html.push_str("</span>");
101 }
102
103 // The line's trailing newline is the last raw newline in the fragment
104 // (closing tags never contain one). Drop it, and a CR before it.
105 if let Some(pos) = html.rfind('\n') {
106 html.remove(pos);
107 if pos > 0 && html.as_bytes()[pos - 1] == b'\r' {
108 html.remove(pos - 1);
109 }
110 }
111 out.push(html);
112 }
113 Some(out)
114}
115
116fn build_css() -> String {
117 // Local so the theme set is freed once the CSS is built; only the CSS string is kept.
118 let theme_set = ThemeSet::load_defaults();
119 let light = theme_set
120 .themes
121 .get(LIGHT_THEME)
122 .expect("syntect default theme InspiredGitHub is present");
123 let dark = theme_set
124 .themes
125 .get(DARK_THEME)
126 .expect("syntect default theme base16-ocean.dark is present");
127 let light_css = readable_on_light(
128 &css_for_theme_with_class_style(light, class_style())
129 .expect("generating CSS for the light theme"),
130 );
131 let dark_css = css_for_theme_with_class_style(dark, class_style())
132 .expect("generating CSS for the dark theme");
133 // Each theme follows the page theme: the OS preference unless `data-theme` is set, and always
134 // when it is. The light rules are scoped too: a bare light rule with more classes would beat
135 // a dark rule with fewer, and leave light colours on a dark page.
136 format!(
137 "@media (prefers-color-scheme: light) {{
138{}}}
139{}
140@media (prefers-color-scheme: dark) {{
141{}}}
142{}",
143 scope_css(&light_css, LIGHT_WHEN_AUTO),
144 scope_css(&light_css, LIGHT_WHEN_FORCED),
145 scope_css(&dark_css, DARK_WHEN_AUTO),
146 scope_css(&dark_css, DARK_WHEN_FORCED),
147 )
148}
149
150/// Darkens each text colour of the light theme until it reaches 4.5:1 on the light code background,
151/// #EEF2EC. Some of InspiredGitHub's colours are too pale to read there.
152fn readable_on_light(css: &str) -> String {
153 const BACKGROUND_LUMINANCE: f32 = 0.875;
154 let luminance = |rgb: [u8; 3]| {
155 let [r, g, b] = rgb.map(|channel| {
156 let c = f32::from(channel) / 255.0;
157 if c <= 0.04045 {
158 c / 12.92
159 } else {
160 ((c + 0.055) / 1.055).powf(2.4)
161 }
162 });
163 0.2126 * r + 0.7152 * g + 0.0722 * b
164 };
165 let mut out = String::with_capacity(css.len());
166 for line in css.lines() {
167 let hex = line
168 .trim()
169 .strip_prefix("color: #")
170 .and_then(|rest| rest.strip_suffix(';'));
171 let rgb = hex
172 .filter(|hex| hex.len() == 6)
173 .and_then(|hex| u32::from_str_radix(hex, 16).ok())
174 .map(|value| value.to_be_bytes())
175 .map(|[_, r, g, b]| [r, g, b]);
176 match rgb {
177 Some(mut rgb) => {
178 while (BACKGROUND_LUMINANCE + 0.05) / (luminance(rgb) + 0.05) < 4.5 {
179 rgb = rgb.map(|channel| (f32::from(channel) * 0.95) as u8);
180 }
181 let [r, g, b] = rgb;
182 out.push_str(&format!(" color: #{r:02x}{g:02x}{b:02x};\n"));
183 }
184 None => {
185 out.push_str(line);
186 out.push('\n');
187 }
188 }
189 }
190 out
191}
192
193/// Prefixes every selector in a syntect stylesheet with `scope`. syntect writes each rule as a
194/// selector line ending in `{` (selectors separated by commas), then declarations, then `}`.
195fn scope_css(css: &str, scope: &str) -> String {
196 let mut out = String::with_capacity(css.len() * 2);
197 for line in css.lines() {
198 match line.strip_suffix('{') {
199 Some(selectors) => {
200 let scoped: Vec<String> = selectors
201 .split(',')
202 .map(|selector| format!("{scope} {}", selector.trim()))
203 .collect();
204 out.push_str(&scoped.join(", "));
205 out.push_str(" {\n");
206 }
207 None => {
208 out.push_str(line);
209 out.push('\n');
210 }
211 }
212 }
213 out
214}
215
216/// CSS for the `hl-` classes: both themes, each scoped to the page theme it belongs to.
217pub fn highlight_css() -> String {
218 CSS.clone()
219}
220
221#[cfg(test)]
222mod tests {
223 use super::*;
224
225 fn balanced(fragment: &str) -> bool {
226 fragment.matches("<span").count() == fragment.matches("</span>").count()
227 }
228
229 #[test]
230 fn rust_line_count_matches_input() {
231 let src = "fn main() {\n println!(\"hi\");\n}\n";
232 let lines = highlight_lines("main.rs", src).expect("rust is known");
233 assert_eq!(lines.len(), src.lines().count());
234 assert_eq!(lines.len(), 3);
235 assert!(lines.iter().all(|l| !l.contains('\n')));
236 }
237
238 #[test]
239 fn multiline_constructs_stay_balanced_per_line() {
240 let src = "/* a\n b */ let x = \"multi\nline\";\nfn f() {}\n";
241 let lines = highlight_lines("lib.rs", src).expect("rust is known");
242 assert_eq!(lines.len(), 4);
243 for line in &lines {
244 assert!(balanced(line), "unbalanced fragment: {line}");
245 }
246 }
247
248 #[test]
249 fn script_in_string_is_escaped() {
250 let src = "let s = \"<script>alert(1)</script>\";\n";
251 let lines = highlight_lines("page.rs", src).expect("rust is known");
252 let joined = lines.join("\n");
253 assert!(
254 !joined.contains("<script"),
255 "raw script tag leaked: {joined}"
256 );
257 assert!(joined.contains("&lt;script&gt;"), "not escaped: {joined}");
258 assert!(!joined.contains("style="), "inline style emitted: {joined}");
259 }
260
261 #[test]
262 fn unknown_or_plain_names_return_none() {
263 for name in ["data.unknownext", "notes.txt"] {
264 assert!(highlight_lines(name, "hello\n").is_none(), "case {name}");
265 }
266 }
267
268 #[test]
269 fn shebang_is_detected() {
270 let src = "#!/bin/sh\necho hi\n";
271 let lines = highlight_lines("run", src).expect("shebang is detected");
272 assert_eq!(lines.len(), 2);
273 assert!(lines.iter().all(|l| balanced(l)));
274 }
275
276 #[test]
277 fn full_file_name_is_detected() {
278 let src = "all:\n\techo hi\n";
279 assert!(highlight_lines("Makefile", src).is_some());
280 }
281
282 #[test]
283 fn size_limits_return_none() {
284 let many_lines = "x\n".repeat(MAX_LINES + 1);
285 assert!(highlight_lines("a.rs", &many_lines).is_none());
286 let too_big = "a".repeat(MAX_BYTES + 1);
287 assert!(highlight_lines("a.rs", &too_big).is_none());
288 }
289
290 #[test]
291 fn css_has_classes_and_dark_media_query() {
292 let css = highlight_css();
293 assert!(css.contains(".hl-"));
294 assert!(css.contains("@media (prefers-color-scheme: dark)"));
295 assert!(css.contains(DARK_WHEN_AUTO));
296 assert!(css.contains(DARK_WHEN_FORCED));
297 assert!(!css.contains("@media (prefers-color-scheme: dark) {\n.hl-"));
298 }
299
300 #[test]
301 fn dark_rules_are_scoped_to_their_selectors() {
302 let scoped = scope_css(".hl-a,.hl-b {\n color: #fff;\n}\n", "S");
303 assert_eq!(scoped, "S .hl-a, S .hl-b {\n color: #fff;\n}\n");
304 }
305
306 #[test]
307 fn first_call_latency() {
308 let start = std::time::Instant::now();
309 let _ = highlight_lines("first.rs", "fn a() {}\n");
310 let first = start.elapsed();
311 let css_start = std::time::Instant::now();
312 let _ = highlight_css();
313 let css = css_start.elapsed();
314 println!(
315 "highlight first call (LazyLock init + highlight): {first:?}; css first call: {css:?}"
316 );
317 }
318}