oxinav-core 0.5.0

Core logic for OxiNav: file operations, pane state, archives and viewing, with no UI dependency
Documentation
//! Syntax highlighting for the viewer, as UI-neutral styled lines.
//!
//! Detection and highlighting use `syntect` with bat's syntax and theme
//! collection from `two-face`. The output is plain data — lines of spans
//! carrying an `Rgb` colour — so the app maps it to widgets and this crate
//! never names an Iced type.

use crate::session::ThemeMode;
use std::path::Path;
use std::sync::OnceLock;
use syntect::easy::HighlightLines;
use syntect::highlighting::{FontStyle, Style, Theme};
use syntect::parsing::SyntaxSet;
use syntect::util::LinesWithEndings;
use two_face::theme::{EmbeddedLazyThemeSet, EmbeddedThemeName};

/// The most bytes highlighted; the rest of the text is shown plain.
///
/// syntect's pure-Rust regex backend manages roughly 200 KB/s on ordinary
/// source in a release build, so this much takes about 0.3 s — which is why
/// the app highlights off the UI thread. Safe to tune.
pub const MAX_HIGHLIGHT_BYTES: usize = 64 * 1024;

/// The most lines highlighted, which also bounds how many styled lines the
/// view lays out. Safe to tune.
pub const MAX_HIGHLIGHT_LINES: usize = 2_000;

/// Highlighting stops at the first line longer than this. Grammar matching
/// slows sharply with line length — 64 KiB of 1,000-byte string literals
/// took over five seconds — and lines that long are minified or generated
/// code, where colour helps little. Safe to tune.
pub const MAX_HIGHLIGHT_LINE_BYTES: usize = 1_000;

/// A colour, kept here rather than borrowed from a UI toolkit.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Rgb {
    pub r: u8,
    pub g: u8,
    pub b: u8,
}

/// A run of text in one style.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Span {
    pub text: String,
    pub colour: Rgb,
    pub bold: bool,
    pub italic: bool,
}

/// One line of the file, without its line ending.
pub type Line = Vec<Span>;

/// A detected language, by its syntax name ("Rust", "TOML").
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Language(String);

impl Language {
    pub fn name(&self) -> &str {
        &self.0
    }
}

fn syntaxes() -> &'static SyntaxSet {
    static SYNTAXES: OnceLock<SyntaxSet> = OnceLock::new();
    SYNTAXES.get_or_init(two_face::syntax::extra_newlines)
}

fn themes() -> &'static EmbeddedLazyThemeSet {
    static THEMES: OnceLock<EmbeddedLazyThemeSet> = OnceLock::new();
    THEMES.get_or_init(two_face::theme::extra)
}

fn theme(mode: ThemeMode) -> &'static Theme {
    themes().get(match mode {
        ThemeMode::Dark => EmbeddedThemeName::MonokaiExtended,
        ThemeMode::Light => EmbeddedThemeName::MonokaiExtendedLight,
    })
}

/// The language of the file `name`, judged by its extension, then its full
/// name (`Dockerfile`, `Makefile`, `.bashrc`), then its first line (`#!`
/// lines, `<?xml`, modelines). Plain text counts as no language.
pub fn detect_language(name: &str, first_line: &str) -> Option<Language> {
    let set = syntaxes();
    let extension = Path::new(name).extension().and_then(|ext| ext.to_str());
    extension
        .and_then(|ext| set.find_syntax_by_extension(ext))
        // Sublime syntaxes list well-known file names among their
        // "extensions", with or without the leading dot.
        .or_else(|| set.find_syntax_by_extension(name))
        .or_else(|| set.find_syntax_by_extension(name.trim_start_matches('.')))
        .or_else(|| set.find_syntax_by_first_line(first_line))
        .filter(|syntax| syntax.name != "Plain Text")
        .map(|syntax| Language(syntax.name.clone()))
}

/// The leading lines of `text`, split as `str::lines` splits them, each made
/// of styled spans. Highlighting stops at the bounds above, and the lines
/// after the returned ones are for the caller to show plain: joining the
/// returned lines with `\n` gives exactly the first `len()` lines of
/// `str::lines`.
pub fn highlight(text: &str, language: &Language, mode: ThemeMode) -> Vec<Line> {
    let set = syntaxes();
    let Some(syntax) = set.find_syntax_by_name(language.name()) else {
        return Vec::new();
    };
    let mut highlighter = HighlightLines::new(syntax, theme(mode));

    let mut lines = Vec::new();
    let mut highlighted_bytes = 0;
    for raw in LinesWithEndings::from(text) {
        let content = raw
            .strip_suffix('\n')
            .map(|line| line.strip_suffix('\r').unwrap_or(line))
            .unwrap_or(raw);
        if lines.len() >= MAX_HIGHLIGHT_LINES
            || highlighted_bytes >= MAX_HIGHLIGHT_BYTES
            || content.len() > MAX_HIGHLIGHT_LINE_BYTES
        {
            break;
        }
        // A grammar that fails mid-file leaves the rest plain rather than
        // losing the view.
        let Ok(ranges) = highlighter.highlight_line(raw, set) else {
            break;
        };
        highlighted_bytes += raw.len();
        lines.push(styled_line(&ranges, content.len()));
    }
    lines
}

/// The spans of one highlighted line, cut at `len` so the line ending the
/// grammar needed to see is not part of the displayed text.
fn styled_line(ranges: &[(Style, &str)], len: usize) -> Line {
    let mut line = Vec::new();
    let mut taken = 0;
    for (style, piece) in ranges {
        if taken >= len {
            break;
        }
        let piece = &piece[..piece.len().min(len - taken)];
        taken += piece.len();
        if piece.is_empty() {
            continue;
        }
        line.push(Span {
            text: piece.to_string(),
            colour: Rgb {
                r: style.foreground.r,
                g: style.foreground.g,
                b: style.foreground.b,
            },
            bold: style.font_style.contains(FontStyle::BOLD),
            italic: style.font_style.contains(FontStyle::ITALIC),
        });
    }
    line
}

#[cfg(test)]
mod tests {
    use super::*;

    fn language(name: &str, first_line: &str) -> Option<String> {
        detect_language(name, first_line).map(|lang| lang.name().to_string())
    }

    fn joined(lines: &[Line]) -> String {
        lines
            .iter()
            .map(|line| {
                line.iter()
                    .map(|span| span.text.as_str())
                    .collect::<String>()
            })
            .collect::<Vec<_>>()
            .join("\n")
    }

    /// The first `count` lines of `text`, as `str::lines` gives them.
    fn expected(text: &str, count: usize) -> String {
        text.lines().take(count).collect::<Vec<_>>().join("\n")
    }

    fn rust() -> Language {
        detect_language("main.rs", "").unwrap()
    }

    /// The colour of the first span holding `needle`.
    fn colour_of(lines: &[Line], needle: &str) -> Option<Rgb> {
        lines
            .iter()
            .flatten()
            .find(|span| span.text.contains(needle))
            .map(|span| span.colour)
    }

    #[test]
    fn detects_by_extension() {
        assert_eq!(language("main.rs", "").as_deref(), Some("Rust"));
        assert_eq!(language("Cargo.toml", "").as_deref(), Some("TOML"));
    }

    #[test]
    fn detects_by_well_known_name() {
        assert_eq!(
            language("Dockerfile", "FROM rust").as_deref(),
            Some("Dockerfile")
        );
        assert_eq!(language("Makefile", "all:").as_deref(), Some("Makefile"));
        assert!(language(".bashrc", "alias ll='ls -l'").is_some());
    }

    #[test]
    fn detects_by_first_line() {
        let shell = language("deploy", "#!/usr/bin/env bash").unwrap();
        assert!(shell.contains("Bash") || shell.contains("Shell"), "{shell}");
    }

    #[test]
    fn unknown_text_has_no_language() {
        assert_eq!(language("notes.xyz", "Just some prose."), None);
        assert_eq!(language("notes.txt", "Just some prose."), None);
    }

    #[test]
    fn highlighting_keeps_the_text_exactly() {
        let text = "fn main() {\n    // hi\n\n    let s = \"x\";\r\n}\n";
        let lines = highlight(text, &rust(), ThemeMode::Dark);
        assert_eq!(lines.len(), text.lines().count());
        assert_eq!(joined(&lines), expected(text, lines.len()));
    }

    #[test]
    fn line_bound_stops_highlighting() {
        let text: String = (0..MAX_HIGHLIGHT_LINES + 50)
            .map(|i| format!("let x{i} = {i};\n"))
            .collect();
        let lines = highlight(&text, &rust(), ThemeMode::Dark);

        assert_eq!(lines.len(), MAX_HIGHLIGHT_LINES);
        assert_eq!(joined(&lines), expected(&text, lines.len()));
    }

    #[test]
    fn byte_bound_stops_highlighting() {
        let line = format!("// {}\n", "x".repeat(MAX_HIGHLIGHT_LINE_BYTES - 10));
        let text = line.repeat(MAX_HIGHLIGHT_BYTES / line.len() + 10);
        let lines = highlight(&text, &rust(), ThemeMode::Dark);

        assert_eq!(lines.len(), MAX_HIGHLIGHT_BYTES.div_ceil(line.len()));
        assert_eq!(joined(&lines), expected(&text, lines.len()));
    }

    #[test]
    fn an_overlong_line_stops_highlighting() {
        let text = format!(
            "fn a() {{}}\nlet s = \"{}\";\nfn b() {{}}\n",
            "x".repeat(2 * MAX_HIGHLIGHT_LINE_BYTES)
        );
        let lines = highlight(&text, &rust(), ThemeMode::Dark);
        assert_eq!(lines.len(), 1);
    }

    #[test]
    fn keywords_and_comments_get_different_colours() {
        let lines = highlight("fn main() {} // note\n", &rust(), ThemeMode::Dark);
        let keyword = colour_of(&lines, "fn").unwrap();
        let comment = colour_of(&lines, "note").unwrap();
        assert_ne!(keyword, comment);
    }

    #[test]
    fn dark_and_light_use_different_colours() {
        let text = "fn main() {}\n";
        let dark = highlight(text, &rust(), ThemeMode::Dark);
        let light = highlight(text, &rust(), ThemeMode::Light);
        assert_ne!(colour_of(&dark, "fn"), colour_of(&light, "fn"));
    }

    #[test]
    fn empty_lines_have_no_spans() {
        let lines = highlight("a\n\nb\n", &rust(), ThemeMode::Dark);
        assert_eq!(lines.len(), 3);
        assert!(lines[1].is_empty());
    }
}