on cd68509 help sign in
bat/src/assets.rs
231 lines 7.3 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";
19pub struct HighlightingAssets {
20 pub syntax_set: SyntaxSet,
21 pub theme_set: ThemeSet,
24impl HighlightingAssets {
25 pub fn new() -> Self {
26 Self::from_cache().unwrap_or_else(|_| Self::from_binary())
27 }
29 pub fn from_files(dir: Option<&Path>, start_empty: bool) -> Result<Self> {
30 let source_dir = dir.unwrap_or_else(|| PROJECT_DIRS.config_dir());
32 let mut theme_set = if start_empty {
33 ThemeSet {
34 themes: BTreeMap::new(),
35 }
36 } else {
37 Self::get_integrated_themeset()
38 };
40 let theme_dir = source_dir.join("themes");
42 let res = theme_set.add_from_folder(&theme_dir);
43 if res.is_err() {
44 println!(
45 "No themes were found in '{}', using the default set",
46 theme_dir.to_string_lossy()
47 );
48 }
50 let mut syntax_set_builder = if start_empty {
51 let mut builder = SyntaxSetBuilder::new();
52 builder.add_plain_text_syntax();
53 builder
54 } else {
55 Self::get_integrated_syntaxset().into_builder()
56 };
58 let syntax_dir = source_dir.join("syntaxes");
59 if syntax_dir.exists() {
60 syntax_set_builder.add_from_folder(syntax_dir, true)?;
61 } else {
62 println!(
63 "No syntaxes were found in '{}', using the default set.",
64 syntax_dir.to_string_lossy()
65 );
66 }
68 Ok(HighlightingAssets {
69 syntax_set: syntax_set_builder.build(),
70 theme_set,
71 })
72 }
74 fn from_cache() -> Result<Self> {
75 let theme_set_path = theme_set_path();
76 let syntax_set_file = File::open(&syntax_set_path()).chain_err(|| {
77 format!(
78 "Could not load cached syntax set '{}'",
79 syntax_set_path().to_string_lossy()
80 )
81 })?;
82 let syntax_set: SyntaxSet = from_reader(BufReader::new(syntax_set_file))
83 .chain_err(|| "Could not parse cached syntax set")?;
85 let theme_set_file = File::open(&theme_set_path).chain_err(|| {
86 format!(
87 "Could not load cached theme set '{}'",
88 theme_set_path.to_string_lossy()
89 )
90 })?;
91 let theme_set: ThemeSet = from_reader(BufReader::new(theme_set_file))
92 .chain_err(|| "Could not parse cached theme set")?;
94 Ok(HighlightingAssets {
95 syntax_set,
96 theme_set,
97 })
98 }
100 fn get_integrated_syntaxset() -> SyntaxSet {
101 from_binary(include_bytes!("../assets/syntaxes.bin"))
102 }
104 fn get_integrated_themeset() -> ThemeSet {
105 from_binary(include_bytes!("../assets/themes.bin"))
106 }
108 fn from_binary() -> Self {
109 let syntax_set = Self::get_integrated_syntaxset();
110 let theme_set = Self::get_integrated_themeset();
112 HighlightingAssets {
113 syntax_set,
114 theme_set,
115 }
116 }
118 pub fn save(&self, dir: Option<&Path>) -> Result<()> {
119 let target_dir = dir.unwrap_or_else(|| PROJECT_DIRS.cache_dir());
120 let _ = fs::create_dir(target_dir);
121 let theme_set_path = target_dir.join("themes.bin");
122 let syntax_set_path = target_dir.join("syntaxes.bin");
124 print!(
125 "Writing theme set to {} ... ",
126 theme_set_path.to_string_lossy()
127 );
128 dump_to_file(&self.theme_set, &theme_set_path).chain_err(|| {
129 format!(
130 "Could not save theme set to {}",
131 theme_set_path.to_string_lossy()
132 )
133 })?;
134 println!("okay");
136 print!(
137 "Writing syntax set to {} ... ",
138 syntax_set_path.to_string_lossy()
139 );
140 dump_to_file(&self.syntax_set, &syntax_set_path).chain_err(|| {
141 format!(
142 "Could not save syntax set to {}",
143 syntax_set_path.to_string_lossy()
144 )
145 })?;
146 println!("okay");
148 Ok(())
149 }
151 pub fn get_theme(&self, theme: &str) -> &Theme {
152 match self.theme_set.themes.get(theme) {
153 Some(theme) => theme,
154 None => {
155 use ansi_term::Colour::Yellow;
156 eprintln!(
157 "{}: Unknown theme '{}', using default.",
158 Yellow.paint("[bat warning]"),
159 theme
160 );
161 &self.theme_set.themes[BAT_THEME_DEFAULT]
162 }
163 }
164 }
166 pub fn get_syntax(
167 &self,
168 language: Option<&str>,
169 filename: InputFile,
170 reader: &mut InputFileReader,
171 mapping: &SyntaxMapping,
172 ) -> &SyntaxReference {
173 let syntax = match (language, filename) {
174 (Some(language), _) => self.syntax_set.find_syntax_by_token(language),
175 (None, InputFile::Ordinary(filename)) => {
176 let path = Path::new(filename);
177 let file_name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
178 let extension = path.extension().and_then(|x| x.to_str()).unwrap_or("");
180 let file_name = mapping.replace(file_name);
181 let extension = mapping.replace(extension);
183 let ext_syntax = self
184 .syntax_set
185 .find_syntax_by_extension(&file_name)
186 .or_else(|| self.syntax_set.find_syntax_by_extension(&extension));
187 let line_syntax = if ext_syntax.is_none() {
188 String::from_utf8(reader.first_line.clone())
189 .ok()
190 .and_then(|l| self.syntax_set.find_syntax_by_first_line(&l))
191 } else {
192 None
193 };
195 ext_syntax.or(line_syntax)
196 }
197 (None, InputFile::StdIn) => String::from_utf8(reader.first_line.clone())
198 .ok()
199 .and_then(|l| self.syntax_set.find_syntax_by_first_line(&l)),
200 (_, InputFile::ThemePreviewFile) => self.syntax_set.find_syntax_by_name("Rust"),
201 };
203 syntax.unwrap_or_else(|| self.syntax_set.find_syntax_plain_text())
204 }
207fn theme_set_path() -> PathBuf {
208 PROJECT_DIRS.cache_dir().join("themes.bin")
211fn syntax_set_path() -> PathBuf {
212 PROJECT_DIRS.cache_dir().join("syntaxes.bin")
215pub fn config_dir() -> Cow<'static, str> {
216 PROJECT_DIRS.config_dir().to_string_lossy()
219pub fn cache_dir() -> Cow<'static, str> {
220 PROJECT_DIRS.cache_dir().to_string_lossy()
223pub fn clear_assets() {
224 print!("Clearing theme set cache ... ");
225 fs::remove_file(theme_set_path()).ok();
226 println!("okay");
228 print!("Clearing syntax set cache ... ");
229 fs::remove_file(syntax_set_path()).ok();
230 println!("okay");