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";
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())
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 {
34 themes: BTreeMap::new(),
37 Self::get_integrated_themeset()
40 let theme_dir = source_dir.join("themes");
42 let res = theme_set.add_from_folder(&theme_dir);
45 "No themes were found in '{}', using the default set",
46 theme_dir.to_string_lossy()
50 let mut syntax_set_builder = if start_empty {
51 let mut builder = SyntaxSetBuilder::new();
52 builder.add_plain_text_syntax();
55 Self::get_integrated_syntaxset().into_builder()
58 let syntax_dir = source_dir.join("syntaxes");
59 if syntax_dir.exists() {
60 syntax_set_builder.add_from_folder(syntax_dir, true)?;
63 "No syntaxes were found in '{}', using the default set.",
64 syntax_dir.to_string_lossy()
68 Ok(HighlightingAssets {
69 syntax_set: syntax_set_builder.build(),
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(|| {
78 "Could not load cached syntax set '{}'",
79 syntax_set_path().to_string_lossy()
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(|| {
87 "Could not load cached theme set '{}'",
88 theme_set_path.to_string_lossy()
91 let theme_set: ThemeSet = from_reader(BufReader::new(theme_set_file))
92 .chain_err(|| "Could not parse cached theme set")?;
94 Ok(HighlightingAssets {
100 fn get_integrated_syntaxset() -> SyntaxSet {
101 from_binary(include_bytes!("../assets/syntaxes.bin"))
104 fn get_integrated_themeset() -> ThemeSet {
105 from_binary(include_bytes!("../assets/themes.bin"))
108 fn from_binary() -> Self {
109 let syntax_set = Self::get_integrated_syntaxset();
110 let theme_set = Self::get_integrated_themeset();
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");
125 "Writing theme set to {} ... ",
126 theme_set_path.to_string_lossy()
128 dump_to_file(&self.theme_set, &theme_set_path).chain_err(|| {
130 "Could not save theme set to {}",
131 theme_set_path.to_string_lossy()
137 "Writing syntax set to {} ... ",
138 syntax_set_path.to_string_lossy()
140 dump_to_file(&self.syntax_set, &syntax_set_path).chain_err(|| {
142 "Could not save syntax set to {}",
143 syntax_set_path.to_string_lossy()
151 pub fn get_theme(&self, theme: &str) -> &Theme {
152 match self.theme_set.themes.get(theme) {
153 Some(theme) => theme,
155 use ansi_term::Colour::Yellow;
157 "{}: Unknown theme '{}', using default.",
158 Yellow.paint("[bat warning]"),
161 &self.theme_set.themes[BAT_THEME_DEFAULT]
168 language: Option<&str>,
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
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())
190 .and_then(|l| self.syntax_set.find_syntax_by_first_line(&l))
195 ext_syntax.or(line_syntax)
197 (None, InputFile::StdIn) => String::from_utf8(reader.first_line.clone())
199 .and_then(|l| self.syntax_set.find_syntax_by_first_line(&l)),
200 (_, InputFile::ThemePreviewFile) => self.syntax_set.find_syntax_by_name("Rust"),
203 syntax.unwrap_or_else(|| self.syntax_set.find_syntax_plain_text())
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();
228 print!("Clearing syntax set cache ... ");
229 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