only load syntaxes and themes once
Some checks failed
Build CI / pre-build-checks (push) Failing after 3s
Build CI / build (amd64) (push) Has been skipped
Build CI / build (arm64) (push) Has been skipped

This commit is contained in:
Robin Appelman 2026-08-13 02:18:10 +02:00
commit 8b216bc3c4

View file

@ -1,7 +1,9 @@
use std::fs;
use std::io::Cursor;
use std::path::Path;
use std::sync::LazyLock;
use syntect::highlighting::ThemeSet;
use syntect::highlighting::{Theme, ThemeSet};
use syntect::html::highlighted_html_for_string;
use syntect::parsing::SyntaxSet;
@ -10,17 +12,22 @@ static SYNTAXES: &[u8] =
static THEMES: &[u8] =
include_bytes!("../../resources/themes/ayu_dark.tmTheme");
static SS: LazyLock<SyntaxSet> = LazyLock::new(|| {
syntect::dumps::from_uncompressed_data(SYNTAXES)
.expect("invalid syntax dump")
});
static THEME: LazyLock<Theme> = LazyLock::new(|| {
ThemeSet::load_from_reader(&mut Cursor::new(THEMES))
.expect("invalid theme")
});
pub fn get_pretty_body(path: &Path, ext: &str) -> std::io::Result<String> {
let ss: SyntaxSet = syntect::dumps::from_binary(SYNTAXES);
let mut theme_cursor = std::io::Cursor::new(THEMES);
let theme = ThemeSet::load_from_reader(&mut theme_cursor).unwrap();
let content = fs::read_to_string(path)?;
let syntax = ss
let syntax = SS
.find_syntax_by_token(ext)
.unwrap_or_else(|| ss.find_syntax_plain_text());
.unwrap_or_else(|| SS.find_syntax_plain_text());
highlighted_html_for_string(&content, &ss, syntax, &theme)
highlighted_html_for_string(&content, &SS, syntax, &THEME)
.map_err(std::io::Error::other)
}