2use std::collections::BTreeMap;
3use std::fs::{self, File};
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;
14use crate::inputfile::{InputFile, InputFileReader};
15use crate::syntax_mapping::SyntaxMapping;
17pub const BAT_THEME_DEFAULT: &str = "Monokai Extended";
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())
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 {
35 themes: BTreeMap::new(),
38 Self::get_integrated_themeset()
41 let theme_dir = source_dir.join("themes");
43 let res = theme_set.add_from_folder(&theme_dir);
46 "No themes were found in '{}', using the default set",
47 theme_dir.to_string_lossy()
51 let mut syntax_set_builder = if start_empty {
52 let mut builder = SyntaxSetBuilder::new();
53 builder.add_plain_text_syntax();
56 Self::get_integrated_syntaxset().into_builder()
59 let syntax_dir = source_dir.join("syntaxes");
60 if syntax_dir.exists() {
61 syntax_set_builder.add_from_folder(syntax_dir, true)?;
64 "No syntaxes were found in '{}', using the default set.",
65 syntax_dir.to_string_lossy()
69 Ok(HighlightingAssets {
70 syntax_set: syntax_set_builder.build(),
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(|| {
79 "Could not load cached syntax set '{}'",
80 syntax_set_path().to_string_lossy()
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(|| {
88 "Could not load cached theme set '{}'",
89 theme_set_path.to_string_lossy()
92 let theme_set: ThemeSet = from_reader(BufReader::new(theme_set_file))
93 .chain_err(|| "Could not parse cached theme set")?;
95 Ok(HighlightingAssets {
101 fn get_integrated_syntaxset() -> SyntaxSet {
102 from_binary(include_bytes!("../assets/syntaxes.bin"))
105 fn get_integrated_themeset() -> ThemeSet {
106 from_binary(include_bytes!("../assets/themes.bin"))
109 fn from_binary() -> Self {
110 let syntax_set = Self::get_integrated_syntaxset();
111 let theme_set = Self::get_integrated_themeset();
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");
126 "Writing theme set to {} ... ",
127 theme_set_path.to_string_lossy()
129 dump_to_file(&self.theme_set, &theme_set_path).chain_err(|| {
131 "Could not save theme set to {}",
132 theme_set_path.to_string_lossy()
138 "Writing syntax set to {} ... ",
139 syntax_set_path.to_string_lossy()
141 dump_to_file(&self.syntax_set, &syntax_set_path).chain_err(|| {
143 "Could not save syntax set to {}",
144 syntax_set_path.to_string_lossy()
152 pub fn get_theme(&self, theme: &str) -> &Theme {
153 match self.theme_set.themes.get(theme) {
154 Some(theme) => theme,
156 use ansi_term::Colour::Yellow;
158 "{}: Unknown theme '{}', using default.",
159 Yellow.paint("[bat warning]"),
162 &self.theme_set.themes[BAT_THEME_DEFAULT]
169 language: Option<&str>,
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
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())
191 .and_then(|l| self.syntax_set.find_syntax_by_first_line(&l))
196 ext_syntax.or(line_syntax)
198 (None, InputFile::StdIn) => String::from_utf8(reader.first_line.clone())
200 .and_then(|l| self.syntax_set.find_syntax_by_first_line(&l)),
201 (_, InputFile::ThemePreviewFile) => self.syntax_set.find_syntax_by_name("Rust"),
204 syntax.unwrap_or_else(|| self.syntax_set.find_syntax_plain_text())
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();
229 print!("Clearing syntax set cache ... ");
230 fs::remove_file(syntax_set_path()).ok();
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list