1use std::collections::BTreeMap;
3use std::fs::{self, File};
7use syntect::dumps::{dump_to_file, from_binary, from_reader};
8use syntect::highlighting::{Theme, ThemeSet};
9use syntect::parsing::{SyntaxReference, SyntaxSet, SyntaxSetBuilder};
13use crate::assets_metadata::AssetsMetadata;
15use crate::input::{InputReader, OpenedInput, OpenedInputKind};
16use crate::syntax_mapping::{MappingTarget, SyntaxMapping};
19pub struct HighlightingAssets {
20 pub(crate) syntax_set: SyntaxSet,
21 pub(crate) theme_set: ThemeSet,
22 fallback_theme: Option<&'static str>,
25impl HighlightingAssets {
26 pub fn default_theme() -> &'static str {
30 pub fn from_files(source_dir: &Path, include_integrated_assets: bool) -> Result<Self> {
31 let mut theme_set = if include_integrated_assets {
32 Self::get_integrated_themeset()
35 themes: BTreeMap::new(),
39 let theme_dir = source_dir.join("themes");
41 let res = theme_set.add_from_folder(&theme_dir);
44 "No themes were found in '{}', using the default set",
45 theme_dir.to_string_lossy()
49 let mut syntax_set_builder = if !include_integrated_assets {
50 let mut builder = SyntaxSetBuilder::new();
51 builder.add_plain_text_syntax();
54 Self::get_integrated_syntaxset().into_builder()
57 let syntax_dir = source_dir.join("syntaxes");
58 if syntax_dir.exists() {
59 syntax_set_builder.add_from_folder(syntax_dir, true)?;
62 "No syntaxes were found in '{}', using the default set.",
63 syntax_dir.to_string_lossy()
67 Ok(HighlightingAssets {
68 syntax_set: syntax_set_builder.build(),
74 pub fn from_cache(cache_path: &Path) -> Result<Self> {
75 let syntax_set_path = cache_path.join("syntaxes.bin");
76 let theme_set_path = cache_path.join("themes.bin");
78 let syntax_set_file = File::open(&syntax_set_path).chain_err(|| {
80 "Could not load cached syntax set '{}'",
81 syntax_set_path.to_string_lossy()
84 let syntax_set: SyntaxSet = from_reader(BufReader::new(syntax_set_file))
85 .chain_err(|| "Could not parse cached syntax set")?;
87 let theme_set_file = File::open(&theme_set_path).chain_err(|| {
89 "Could not load cached theme set '{}'",
90 theme_set_path.to_string_lossy()
93 let theme_set: ThemeSet = from_reader(BufReader::new(theme_set_file))
94 .chain_err(|| "Could not parse cached theme set")?;
96 Ok(HighlightingAssets {
103 fn get_integrated_syntaxset() -> SyntaxSet {
104 from_binary(include_bytes!("../assets/syntaxes.bin"))
107 fn get_integrated_themeset() -> ThemeSet {
108 from_binary(include_bytes!("../assets/themes.bin"))
111 pub fn from_binary() -> Self {
112 let syntax_set = Self::get_integrated_syntaxset();
113 let theme_set = Self::get_integrated_themeset();
118 fallback_theme: None,
122 pub fn save_to_cache(&self, target_dir: &Path, current_version: &str) -> Result<()> {
123 let _ = fs::create_dir_all(target_dir);
124 let theme_set_path = target_dir.join("themes.bin");
125 let syntax_set_path = target_dir.join("syntaxes.bin");
128 "Writing theme set to {} ... ",
129 theme_set_path.to_string_lossy()
131 dump_to_file(&self.theme_set, &theme_set_path).chain_err(|| {
133 "Could not save theme set to {}",
134 theme_set_path.to_string_lossy()
140 "Writing syntax set to {} ... ",
141 syntax_set_path.to_string_lossy()
143 dump_to_file(&self.syntax_set, &syntax_set_path).chain_err(|| {
145 "Could not save syntax set to {}",
146 syntax_set_path.to_string_lossy()
152 "Writing metadata to folder {} ... ",
153 target_dir.to_string_lossy()
155 AssetsMetadata::new(current_version).save_to_folder(target_dir)?;
161 pub fn set_fallback_theme(&mut self, theme: &'static str) {
162 self.fallback_theme = Some(theme);
165 pub fn syntaxes(&self) -> &[SyntaxReference] {
166 self.syntax_set.syntaxes()
169 pub fn themes(&self) -> impl Iterator<Item = &str> {
170 self.theme_set.themes.keys().map(|s| s.as_ref())
173 pub(crate) fn get_theme(&self, theme: &str) -> &Theme {
174 match self.theme_set.themes.get(theme) {
175 Some(theme) => theme,
178 use ansi_term::Colour::Yellow;
180 "{}: Unknown theme '{}', using default.",
181 Yellow.paint("[bat warning]"),
185 &self.theme_set.themes[self.fallback_theme.unwrap_or_else(|| Self::default_theme())]
190 pub(crate) fn get_syntax(
192 language: Option<&str>,
193 input: &mut OpenedInput,
194 mapping: &SyntaxMapping,
195 ) -> Result<&SyntaxReference> {
196 if let Some(language) = language {
198 .find_syntax_by_token(language)
199 .ok_or_else(|| ErrorKind::UnknownSyntax(language.to_owned()).into())
201 let line_syntax = self.get_first_line_syntax(&mut input.reader);
203 // Get the path of the file:
204 // If this was set by the metadata, that will take priority.
205 // If it wasn't, it will use the real file path (if available).
211 .or_else(|| match input.kind {
212 OpenedInputKind::OrdinaryFile(ref path) => Some(path),
216 if let Some(path_str) = path_str {
217 // If a path was provided, we try and detect the syntax based on extension mappings.
218 let path = Path::new(path_str);
219 let absolute_path = PathAbs::new(path)
221 .map(|p| p.as_path().to_path_buf())
222 .unwrap_or_else(|| path.to_owned());
224 match mapping.get_syntax_for(absolute_path) {
225 Some(MappingTarget::MapToUnknown) => line_syntax.ok_or_else(|| {
226 ErrorKind::UndetectedSyntax(path.to_string_lossy().into()).into()
229 Some(MappingTarget::MapTo(syntax_name)) => self
231 .find_syntax_by_name(syntax_name)
232 .ok_or_else(|| ErrorKind::UnknownSyntax(syntax_name.to_owned()).into()),
235 let file_name = path.file_name().unwrap_or_default();
236 self.get_extension_syntax(file_name)
239 ErrorKind::UndetectedSyntax(path.to_string_lossy().into()).into()
244 // If a path wasn't provided, we fall back to the detect first-line syntax.
245 line_syntax.ok_or_else(|| ErrorKind::UndetectedSyntax("[unknown]".into()).into())
250 fn get_extension_syntax(&self, file_name: &OsStr) -> Option<&SyntaxReference> {
252 .find_syntax_by_extension(file_name.to_str().unwrap_or_default())
254 self.syntax_set.find_syntax_by_extension(
257 .and_then(|x| x.to_str())
258 .unwrap_or_default(),
263 fn get_first_line_syntax(&self, reader: &mut InputReader) -> Option<&SyntaxReference> {
264 String::from_utf8(reader.first_line.clone())
266 .and_then(|l| self.syntax_set.find_syntax_by_first_line(&l))
278 use tempdir::TempDir;
280 use crate::input::Input;
282 struct SyntaxDetectionTest<'a> {
283 assets: HighlightingAssets,
284 pub syntax_mapping: SyntaxMapping<'a>,
285 pub temp_dir: TempDir,
288 impl<'a> SyntaxDetectionTest<'a> {
290 SyntaxDetectionTest {
291 assets: HighlightingAssets::from_binary(),
292 syntax_mapping: SyntaxMapping::builtin(),
293 temp_dir: TempDir::new("bat_syntax_detection_tests")
294 .expect("creation of temporary directory"),
298 fn syntax_for_real_file_with_content_os(
303 let file_path = self.temp_dir.path().join(file_name);
305 let mut temp_file = File::create(&file_path).unwrap();
306 writeln!(temp_file, "{}", first_line).unwrap();
309 let input = Input::ordinary_file(file_path.as_os_str());
310 let dummy_stdin: &[u8] = &[];
311 let mut opened_input = input.open(dummy_stdin).unwrap();
314 .get_syntax(None, &mut opened_input, &self.syntax_mapping)
315 .unwrap_or_else(|_| self.assets.syntax_set.find_syntax_plain_text())
320 fn syntax_for_file_with_content_os(&self, file_name: &OsStr, first_line: &str) -> String {
321 let file_path = self.temp_dir.path().join(file_name);
322 let input = Input::from_reader(Box::new(BufReader::new(first_line.as_bytes())))
323 .with_name(Some(file_path.as_os_str()));
324 let dummy_stdin: &[u8] = &[];
325 let mut opened_input = input.open(dummy_stdin).unwrap();
328 .get_syntax(None, &mut opened_input, &self.syntax_mapping)
329 .unwrap_or_else(|_| self.assets.syntax_set.find_syntax_plain_text())
334 fn syntax_for_file_os(&self, file_name: &OsStr) -> String {
335 self.syntax_for_file_with_content_os(file_name, "")
338 fn syntax_for_file_with_content(&self, file_name: &str, first_line: &str) -> String {
339 self.syntax_for_file_with_content_os(OsStr::new(file_name), first_line)
342 fn syntax_for_file(&self, file_name: &str) -> String {
343 self.syntax_for_file_with_content(file_name, "")
346 fn syntax_for_stdin_with_content(&self, file_name: &str, content: &[u8]) -> String {
347 let input = Input::stdin().with_name(Some(OsStr::new(file_name)));
348 let mut opened_input = input.open(content).unwrap();
351 .get_syntax(None, &mut opened_input, &self.syntax_mapping)
352 .unwrap_or_else(|_| self.assets.syntax_set.find_syntax_plain_text())
357 fn syntax_is_same_for_inputkinds(&self, file_name: &str, content: &str) -> bool {
358 let as_file = self.syntax_for_real_file_with_content_os(file_name.as_ref(), content);
359 let as_reader = self.syntax_for_file_with_content_os(file_name.as_ref(), content);
360 let consistent = as_file == as_reader;
361 // TODO: Compare StdIn somehow?
365 "Inconsistent syntax detection:\nFor File: {}\nFor Reader: {}",
375 fn syntax_detection_basic() {
376 let test = SyntaxDetectionTest::new();
378 assert_eq!(test.syntax_for_file("test.rs"), "Rust");
379 assert_eq!(test.syntax_for_file("test.cpp"), "C++");
380 assert_eq!(test.syntax_for_file("test.build"), "NAnt Build File");
382 test.syntax_for_file("PKGBUILD"),
383 "Bourne Again Shell (bash)"
385 assert_eq!(test.syntax_for_file(".bashrc"), "Bourne Again Shell (bash)");
386 assert_eq!(test.syntax_for_file("Makefile"), "Makefile");
391 fn syntax_detection_invalid_utf8() {
392 use std::os::unix::ffi::OsStrExt;
394 let test = SyntaxDetectionTest::new();
397 test.syntax_for_file_os(OsStr::from_bytes(b"invalid_\xFEutf8_filename.rs")),
403 fn syntax_detection_same_for_inputkinds() {
404 let mut test = SyntaxDetectionTest::new();
407 .insert("*.myext", MappingTarget::MapTo("C"))
410 .insert("MY_FILE", MappingTarget::MapTo("Markdown"))
413 assert!(test.syntax_is_same_for_inputkinds("Test.md", ""));
414 assert!(test.syntax_is_same_for_inputkinds("Test.txt", "#!/bin/bash"));
415 assert!(test.syntax_is_same_for_inputkinds(".bashrc", ""));
416 assert!(test.syntax_is_same_for_inputkinds("test.h", ""));
417 assert!(test.syntax_is_same_for_inputkinds("test.js", "#!/bin/bash"));
418 assert!(test.syntax_is_same_for_inputkinds("test.myext", ""));
419 assert!(test.syntax_is_same_for_inputkinds("MY_FILE", ""));
420 assert!(test.syntax_is_same_for_inputkinds("MY_FILE", "<?php"));
424 fn syntax_detection_well_defined_mapping_for_duplicate_extensions() {
425 let test = SyntaxDetectionTest::new();
427 assert_eq!(test.syntax_for_file("test.h"), "C++");
428 assert_eq!(test.syntax_for_file("test.sass"), "Sass");
429 assert_eq!(test.syntax_for_file("test.js"), "JavaScript (Babel)");
433 fn syntax_detection_first_line() {
434 let test = SyntaxDetectionTest::new();
437 test.syntax_for_file_with_content("my_script", "#!/bin/bash"),
438 "Bourne Again Shell (bash)"
441 test.syntax_for_file_with_content("build", "#!/bin/bash"),
442 "Bourne Again Shell (bash)"
445 test.syntax_for_file_with_content("my_script", "<?php"),
451 fn syntax_detection_with_custom_mapping() {
452 let mut test = SyntaxDetectionTest::new();
454 assert_eq!(test.syntax_for_file("test.h"), "C++");
456 .insert("*.h", MappingTarget::MapTo("C"))
458 assert_eq!(test.syntax_for_file("test.h"), "C");
462 fn syntax_detection_is_case_sensitive() {
463 let mut test = SyntaxDetectionTest::new();
465 assert_ne!(test.syntax_for_file("README.MD"), "Markdown");
467 .insert("*.MD", MappingTarget::MapTo("Markdown"))
469 assert_eq!(test.syntax_for_file("README.MD"), "Markdown");
473 fn syntax_detection_stdin_filename() {
474 let test = SyntaxDetectionTest::new();
476 // from file extension
477 assert_eq!(test.syntax_for_stdin_with_content("test.cpp", b"a"), "C++");
478 // from first line (fallback)
480 test.syntax_for_stdin_with_content("my_script", b"#!/bin/bash"),
481 "Bourne Again Shell (bash)"
487 fn syntax_detection_for_symlinked_file() {
488 use std::os::unix::fs::symlink;
490 let test = SyntaxDetectionTest::new();
491 let file_path = test.temp_dir.path().join("my_ssh_config_filename");
493 File::create(&file_path).unwrap();
495 let file_path_symlink = test.temp_dir.path().join(".ssh").join("config");
497 std::fs::create_dir(test.temp_dir.path().join(".ssh"))
498 .expect("creation of directory succeeds");
499 symlink(&file_path, &file_path_symlink).expect("creation of symbolic link succeeds");
501 let input = Input::ordinary_file(file_path_symlink.as_os_str());
502 let dummy_stdin: &[u8] = &[];
503 let mut opened_input = input.open(dummy_stdin).unwrap();
507 .get_syntax(None, &mut opened_input, &test.syntax_mapping)
508 .unwrap_or_else(|_| test.assets.syntax_set.find_syntax_plain_text())
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