Skip to main content

oxinav_core/
highlight.rs

1//! Syntax highlighting for the viewer, as UI-neutral styled lines.
2//!
3//! Detection and highlighting use `syntect` with bat's syntax and theme
4//! collection from `two-face`. The output is plain data — lines of spans
5//! carrying an `Rgb` colour — so the app maps it to widgets and this crate
6//! never names an Iced type.
7
8use crate::session::ThemeMode;
9use std::path::Path;
10use std::sync::OnceLock;
11use syntect::easy::HighlightLines;
12use syntect::highlighting::{FontStyle, Style, Theme};
13use syntect::parsing::SyntaxSet;
14use syntect::util::LinesWithEndings;
15use two_face::theme::{EmbeddedLazyThemeSet, EmbeddedThemeName};
16
17/// The most bytes highlighted; the rest of the text is shown plain.
18///
19/// syntect's pure-Rust regex backend manages roughly 200 KB/s on ordinary
20/// source in a release build, so this much takes about 0.3 s — which is why
21/// the app highlights off the UI thread. Safe to tune.
22pub const MAX_HIGHLIGHT_BYTES: usize = 64 * 1024;
23
24/// The most lines highlighted, which also bounds how many styled lines the
25/// view lays out. Safe to tune.
26pub const MAX_HIGHLIGHT_LINES: usize = 2_000;
27
28/// Highlighting stops at the first line longer than this. Grammar matching
29/// slows sharply with line length — 64 KiB of 1,000-byte string literals
30/// took over five seconds — and lines that long are minified or generated
31/// code, where colour helps little. Safe to tune.
32pub const MAX_HIGHLIGHT_LINE_BYTES: usize = 1_000;
33
34/// A colour, kept here rather than borrowed from a UI toolkit.
35#[derive(Debug, Clone, Copy, PartialEq, Eq)]
36pub struct Rgb {
37    pub r: u8,
38    pub g: u8,
39    pub b: u8,
40}
41
42/// A run of text in one style.
43#[derive(Debug, Clone, PartialEq, Eq)]
44pub struct Span {
45    pub text: String,
46    pub colour: Rgb,
47    pub bold: bool,
48    pub italic: bool,
49}
50
51/// One line of the file, without its line ending.
52pub type Line = Vec<Span>;
53
54/// A detected language, by its syntax name ("Rust", "TOML").
55#[derive(Debug, Clone, PartialEq, Eq)]
56pub struct Language(String);
57
58impl Language {
59    pub fn name(&self) -> &str {
60        &self.0
61    }
62}
63
64fn syntaxes() -> &'static SyntaxSet {
65    static SYNTAXES: OnceLock<SyntaxSet> = OnceLock::new();
66    SYNTAXES.get_or_init(two_face::syntax::extra_newlines)
67}
68
69fn themes() -> &'static EmbeddedLazyThemeSet {
70    static THEMES: OnceLock<EmbeddedLazyThemeSet> = OnceLock::new();
71    THEMES.get_or_init(two_face::theme::extra)
72}
73
74fn theme(mode: ThemeMode) -> &'static Theme {
75    themes().get(match mode {
76        ThemeMode::Dark => EmbeddedThemeName::MonokaiExtended,
77        ThemeMode::Light => EmbeddedThemeName::MonokaiExtendedLight,
78    })
79}
80
81/// The language of the file `name`, judged by its extension, then its full
82/// name (`Dockerfile`, `Makefile`, `.bashrc`), then its first line (`#!`
83/// lines, `<?xml`, modelines). Plain text counts as no language.
84pub fn detect_language(name: &str, first_line: &str) -> Option<Language> {
85    let set = syntaxes();
86    let extension = Path::new(name).extension().and_then(|ext| ext.to_str());
87    extension
88        .and_then(|ext| set.find_syntax_by_extension(ext))
89        // Sublime syntaxes list well-known file names among their
90        // "extensions", with or without the leading dot.
91        .or_else(|| set.find_syntax_by_extension(name))
92        .or_else(|| set.find_syntax_by_extension(name.trim_start_matches('.')))
93        .or_else(|| set.find_syntax_by_first_line(first_line))
94        .filter(|syntax| syntax.name != "Plain Text")
95        .map(|syntax| Language(syntax.name.clone()))
96}
97
98/// The leading lines of `text`, split as `str::lines` splits them, each made
99/// of styled spans. Highlighting stops at the bounds above, and the lines
100/// after the returned ones are for the caller to show plain: joining the
101/// returned lines with `\n` gives exactly the first `len()` lines of
102/// `str::lines`.
103pub fn highlight(text: &str, language: &Language, mode: ThemeMode) -> Vec<Line> {
104    let set = syntaxes();
105    let Some(syntax) = set.find_syntax_by_name(language.name()) else {
106        return Vec::new();
107    };
108    let mut highlighter = HighlightLines::new(syntax, theme(mode));
109
110    let mut lines = Vec::new();
111    let mut highlighted_bytes = 0;
112    for raw in LinesWithEndings::from(text) {
113        let content = raw
114            .strip_suffix('\n')
115            .map(|line| line.strip_suffix('\r').unwrap_or(line))
116            .unwrap_or(raw);
117        if lines.len() >= MAX_HIGHLIGHT_LINES
118            || highlighted_bytes >= MAX_HIGHLIGHT_BYTES
119            || content.len() > MAX_HIGHLIGHT_LINE_BYTES
120        {
121            break;
122        }
123        // A grammar that fails mid-file leaves the rest plain rather than
124        // losing the view.
125        let Ok(ranges) = highlighter.highlight_line(raw, set) else {
126            break;
127        };
128        highlighted_bytes += raw.len();
129        lines.push(styled_line(&ranges, content.len()));
130    }
131    lines
132}
133
134/// The spans of one highlighted line, cut at `len` so the line ending the
135/// grammar needed to see is not part of the displayed text.
136fn styled_line(ranges: &[(Style, &str)], len: usize) -> Line {
137    let mut line = Vec::new();
138    let mut taken = 0;
139    for (style, piece) in ranges {
140        if taken >= len {
141            break;
142        }
143        let piece = &piece[..piece.len().min(len - taken)];
144        taken += piece.len();
145        if piece.is_empty() {
146            continue;
147        }
148        line.push(Span {
149            text: piece.to_string(),
150            colour: Rgb {
151                r: style.foreground.r,
152                g: style.foreground.g,
153                b: style.foreground.b,
154            },
155            bold: style.font_style.contains(FontStyle::BOLD),
156            italic: style.font_style.contains(FontStyle::ITALIC),
157        });
158    }
159    line
160}
161
162#[cfg(test)]
163mod tests {
164    use super::*;
165
166    fn language(name: &str, first_line: &str) -> Option<String> {
167        detect_language(name, first_line).map(|lang| lang.name().to_string())
168    }
169
170    fn joined(lines: &[Line]) -> String {
171        lines
172            .iter()
173            .map(|line| {
174                line.iter()
175                    .map(|span| span.text.as_str())
176                    .collect::<String>()
177            })
178            .collect::<Vec<_>>()
179            .join("\n")
180    }
181
182    /// The first `count` lines of `text`, as `str::lines` gives them.
183    fn expected(text: &str, count: usize) -> String {
184        text.lines().take(count).collect::<Vec<_>>().join("\n")
185    }
186
187    fn rust() -> Language {
188        detect_language("main.rs", "").unwrap()
189    }
190
191    /// The colour of the first span holding `needle`.
192    fn colour_of(lines: &[Line], needle: &str) -> Option<Rgb> {
193        lines
194            .iter()
195            .flatten()
196            .find(|span| span.text.contains(needle))
197            .map(|span| span.colour)
198    }
199
200    #[test]
201    fn detects_by_extension() {
202        assert_eq!(language("main.rs", "").as_deref(), Some("Rust"));
203        assert_eq!(language("Cargo.toml", "").as_deref(), Some("TOML"));
204    }
205
206    #[test]
207    fn detects_by_well_known_name() {
208        assert_eq!(
209            language("Dockerfile", "FROM rust").as_deref(),
210            Some("Dockerfile")
211        );
212        assert_eq!(language("Makefile", "all:").as_deref(), Some("Makefile"));
213        assert!(language(".bashrc", "alias ll='ls -l'").is_some());
214    }
215
216    #[test]
217    fn detects_by_first_line() {
218        let shell = language("deploy", "#!/usr/bin/env bash").unwrap();
219        assert!(shell.contains("Bash") || shell.contains("Shell"), "{shell}");
220    }
221
222    #[test]
223    fn unknown_text_has_no_language() {
224        assert_eq!(language("notes.xyz", "Just some prose."), None);
225        assert_eq!(language("notes.txt", "Just some prose."), None);
226    }
227
228    #[test]
229    fn highlighting_keeps_the_text_exactly() {
230        let text = "fn main() {\n    // hi\n\n    let s = \"x\";\r\n}\n";
231        let lines = highlight(text, &rust(), ThemeMode::Dark);
232        assert_eq!(lines.len(), text.lines().count());
233        assert_eq!(joined(&lines), expected(text, lines.len()));
234    }
235
236    #[test]
237    fn line_bound_stops_highlighting() {
238        let text: String = (0..MAX_HIGHLIGHT_LINES + 50)
239            .map(|i| format!("let x{i} = {i};\n"))
240            .collect();
241        let lines = highlight(&text, &rust(), ThemeMode::Dark);
242
243        assert_eq!(lines.len(), MAX_HIGHLIGHT_LINES);
244        assert_eq!(joined(&lines), expected(&text, lines.len()));
245    }
246
247    #[test]
248    fn byte_bound_stops_highlighting() {
249        let line = format!("// {}\n", "x".repeat(MAX_HIGHLIGHT_LINE_BYTES - 10));
250        let text = line.repeat(MAX_HIGHLIGHT_BYTES / line.len() + 10);
251        let lines = highlight(&text, &rust(), ThemeMode::Dark);
252
253        assert_eq!(lines.len(), MAX_HIGHLIGHT_BYTES.div_ceil(line.len()));
254        assert_eq!(joined(&lines), expected(&text, lines.len()));
255    }
256
257    #[test]
258    fn an_overlong_line_stops_highlighting() {
259        let text = format!(
260            "fn a() {{}}\nlet s = \"{}\";\nfn b() {{}}\n",
261            "x".repeat(2 * MAX_HIGHLIGHT_LINE_BYTES)
262        );
263        let lines = highlight(&text, &rust(), ThemeMode::Dark);
264        assert_eq!(lines.len(), 1);
265    }
266
267    #[test]
268    fn keywords_and_comments_get_different_colours() {
269        let lines = highlight("fn main() {} // note\n", &rust(), ThemeMode::Dark);
270        let keyword = colour_of(&lines, "fn").unwrap();
271        let comment = colour_of(&lines, "note").unwrap();
272        assert_ne!(keyword, comment);
273    }
274
275    #[test]
276    fn dark_and_light_use_different_colours() {
277        let text = "fn main() {}\n";
278        let dark = highlight(text, &rust(), ThemeMode::Dark);
279        let light = highlight(text, &rust(), ThemeMode::Light);
280        assert_ne!(colour_of(&dark, "fn"), colour_of(&light, "fn"));
281    }
282
283    #[test]
284    fn empty_lines_have_no_spans() {
285        let lines = highlight("a\n\nb\n", &rust(), ThemeMode::Dark);
286        assert_eq!(lines.len(), 3);
287        assert!(lines[1].is_empty());
288    }
289}