on 3d23daa help sign in
bat/src/assets.rs
232 lines 7.4 kB history raw
1use std::borrow::Cow;
2use std::collections::BTreeMap;
3use std::fs::{self, File};
4use std::io::BufReader;
5use std::path::{Path, PathBuf};
7use syntect::dumps::{dump_to_file, from_binary, from_reader};
8use syntect::highlighting::{Theme, ThemeSet};
9use syntect::parsing::{SyntaxReference, SyntaxSet, SyntaxSetBuilder};
11use crate::dirs::PROJECT_DIRS;
13use crate::errors::*;
14use crate::inputfile::{InputFile, InputFileReader};
15use crate::syntax_mapping::SyntaxMapping;
17pub const BAT_THEME_DEFAULT: &str = "Monokai Extended";
19#[derive(Debug)]
20pub struct HighlightingAssets {
21 pub syntax_set: SyntaxSet,
22 pub theme_set: ThemeSet,
25impl HighlightingAssets {
26 pub fn new() -> Self {
27 Self::from_cache().unwrap_or_else(|_| Self::from_binary())
28 }
30 pub fn from_files(dir: Option<&Path>, start_empty: bool) -> Result<Self> {
31 let source_dir = dir.unwrap_or_else(|| PROJECT_DIRS.config_dir());
33 let mut theme_set = if start_empty {
34 ThemeSet {
35 themes: BTreeMap::new(),
36 }
37 } else {
38 Self::get_integrated_themeset()
39 };
41 let theme_dir = source_dir.join("themes");
43 let res = theme_set.add_from_folder(&theme_dir);
44 if res.is_err() {
45 println!(
46 "No themes were found in '{}', using the default set",
47 theme_dir.to_string_lossy()
48 );
49 }
51 let mut syntax_set_builder = if start_empty {
52 let mut builder = SyntaxSetBuilder::new();
53 builder.add_plain_text_syntax();
54 builder
55 } else {
56 Self::get_integrated_syntaxset().into_builder()
57 };
59 let syntax_dir = source_dir.join("syntaxes");
60 if syntax_dir.exists() {
61 syntax_set_builder.add_from_folder(syntax_dir, true)?;
62 } else {
63 println!(
64 "No syntaxes were found in '{}', using the default set.",
65 syntax_dir.to_string_lossy()
66 );
67 }
69 Ok(HighlightingAssets {
70 syntax_set: syntax_set_builder.build(),
71 theme_set,
72 })
73 }
75 fn from_cache() -> Result<Self> {
76 let theme_set_path = theme_set_path();
77 let syntax_set_file = File::open(&syntax_set_path()).chain_err(|| {
78 format!(
79 "Could not load cached syntax set '{}'",
80 syntax_set_path().to_string_lossy()
81 )
82 })?;
83 let syntax_set: SyntaxSet = from_reader(BufReader::new(syntax_set_file))
84 .chain_err(|| "Could not parse cached syntax set")?;
86 let theme_set_file = File::open(&theme_set_path).chain_err(|| {
87 format!(
88 "Could not load cached theme set '{}'",
89 theme_set_path.to_string_lossy()
90 )
91 })?;
92 let theme_set: ThemeSet = from_reader(BufReader::new(theme_set_file))
93 .chain_err(|| "Could not parse cached theme set")?;
95 Ok(HighlightingAssets {
96 syntax_set,
97 theme_set,
98 })
99 }
101 fn get_integrated_syntaxset() -> SyntaxSet {
102 from_binary(include_bytes!("../assets/syntaxes.bin"))
103 }
105 fn get_integrated_themeset() -> ThemeSet {
106 from_binary(include_bytes!("../assets/themes.bin"))
107 }
109 fn from_binary() -> Self {
110 let syntax_set = Self::get_integrated_syntaxset();
111 let theme_set = Self::get_integrated_themeset();
113 HighlightingAssets {
114 syntax_set,
115 theme_set,
116 }
117 }
119 pub fn save(&self, dir: Option<&Path>) -> Result<()> {
120 let target_dir = dir.unwrap_or_else(|| PROJECT_DIRS.cache_dir());
121 let _ = fs::create_dir_all(target_dir);
122 let theme_set_path = target_dir.join("themes.bin");
123 let syntax_set_path = target_dir.join("syntaxes.bin");
125 print!(
126 "Writing theme set to {} ... ",
127 theme_set_path.to_string_lossy()
128 );
129 dump_to_file(&self.theme_set, &theme_set_path).chain_err(|| {
130 format!(
131 "Could not save theme set to {}",
132 theme_set_path.to_string_lossy()
133 )
134 })?;
135 println!("okay");
137 print!(
138 "Writing syntax set to {} ... ",
139 syntax_set_path.to_string_lossy()
140 );
141 dump_to_file(&self.syntax_set, &syntax_set_path).chain_err(|| {
142 format!(
143 "Could not save syntax set to {}",
144 syntax_set_path.to_string_lossy()
145 )
146 })?;
147 println!("okay");
149 Ok(())
150 }
152 pub fn get_theme(&self, theme: &str) -> &Theme {
153 match self.theme_set.themes.get(theme) {
154 Some(theme) => theme,
155 None => {
156 use ansi_term::Colour::Yellow;
157 eprintln!(
158 "{}: Unknown theme '{}', using default.",
159 Yellow.paint("[bat warning]"),
160 theme
161 );
162 &self.theme_set.themes[BAT_THEME_DEFAULT]
163 }
164 }
165 }
167 pub fn get_syntax(
168 &self,
169 language: Option<&str>,
170 filename: InputFile,
171 reader: &mut InputFileReader,
172 mapping: &SyntaxMapping,
173 ) -> &SyntaxReference {
174 let syntax = match (language, filename) {
175 (Some(language), _) => self.syntax_set.find_syntax_by_token(language),
176 (None, InputFile::Ordinary(filename)) => {
177 let path = Path::new(filename);
178 let file_name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
179 let extension = path.extension().and_then(|x| x.to_str()).unwrap_or("");
181 let file_name = mapping.replace(file_name);
182 let extension = mapping.replace(extension);
184 let ext_syntax = self
185 .syntax_set
186 .find_syntax_by_extension(&file_name)
187 .or_else(|| self.syntax_set.find_syntax_by_extension(&extension));
188 let line_syntax = if ext_syntax.is_none() {
189 String::from_utf8(reader.first_line.clone())
190 .ok()
191 .and_then(|l| self.syntax_set.find_syntax_by_first_line(&l))
192 } else {
193 None
194 };
196 ext_syntax.or(line_syntax)
197 }
198 (None, InputFile::StdIn) => String::from_utf8(reader.first_line.clone())
199 .ok()
200 .and_then(|l| self.syntax_set.find_syntax_by_first_line(&l)),
201 (_, InputFile::ThemePreviewFile) => self.syntax_set.find_syntax_by_name("Rust"),
202 };
204 syntax.unwrap_or_else(|| self.syntax_set.find_syntax_plain_text())
205 }
208fn theme_set_path() -> PathBuf {
209 PROJECT_DIRS.cache_dir().join("themes.bin")
212fn syntax_set_path() -> PathBuf {
213 PROJECT_DIRS.cache_dir().join("syntaxes.bin")
216pub fn config_dir() -> Cow<'static, str> {
217 PROJECT_DIRS.config_dir().to_string_lossy()
220pub fn cache_dir() -> Cow<'static, str> {
221 PROJECT_DIRS.cache_dir().to_string_lossy()
224pub fn clear_assets() {
225 print!("Clearing theme set cache ... ");
226 fs::remove_file(theme_set_path()).ok();
227 println!("okay");
229 print!("Clearing syntax set cache ... ");
230 fs::remove_file(syntax_set_path()).ok();
231 println!("okay");