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 input.kind.is_theme_preview_file() {
198 .find_syntax_by_name("Rust")
199 .ok_or_else(|| ErrorKind::UnknownSyntax("Rust".to_owned()).into())
200 } else if let Some(language) = language {
202 .find_syntax_by_token(language)
203 .ok_or_else(|| ErrorKind::UnknownSyntax(language.to_owned()).into())
205 let line_syntax = self.get_first_line_syntax(&mut input.reader);
207 // Get the path of the file:
208 // If this was set by the metadata, that will take priority.
209 // If it wasn't, it will use the real file path (if available).
215 .or_else(|| match input.kind {
216 OpenedInputKind::OrdinaryFile(ref path) => Some(path),
220 if let Some(path_str) = path_str {
221 // If a path was provided, we try and detect the syntax based on extension mappings.
222 let path = Path::new(path_str);
223 let absolute_path = PathAbs::new(path)
225 .map(|p| p.as_path().to_path_buf())
226 .unwrap_or_else(|| path.to_owned());
228 match mapping.get_syntax_for(absolute_path) {
229 Some(MappingTarget::MapToUnknown) => line_syntax.ok_or_else(|| {
230 ErrorKind::UndetectedSyntax(path.to_string_lossy().into()).into()
233 Some(MappingTarget::MapTo(syntax_name)) => self
235 .find_syntax_by_name(syntax_name)
236 .ok_or_else(|| ErrorKind::UnknownSyntax(syntax_name.to_owned()).into()),
239 let file_name = path.file_name().unwrap_or_default();
240 self.get_extension_syntax(file_name)
243 ErrorKind::UndetectedSyntax(path.to_string_lossy().into()).into()
248 // If a path wasn't provided, we fall back to the detect first-line syntax.
249 line_syntax.ok_or_else(|| ErrorKind::UndetectedSyntax("[unknown]".into()).into())
254 fn get_extension_syntax(&self, file_name: &OsStr) -> Option<&SyntaxReference> {
256 .find_syntax_by_extension(file_name.to_str().unwrap_or_default())
258 self.syntax_set.find_syntax_by_extension(
261 .and_then(|x| x.to_str())
262 .unwrap_or_default(),
267 fn get_first_line_syntax(&self, reader: &mut InputReader) -> Option<&SyntaxReference> {
268 String::from_utf8(reader.first_line.clone())
270 .and_then(|l| self.syntax_set.find_syntax_by_first_line(&l))
282 use tempdir::TempDir;
284 use crate::input::Input;
286 struct SyntaxDetectionTest<'a> {
287 assets: HighlightingAssets,
288 pub syntax_mapping: SyntaxMapping<'a>,
289 pub temp_dir: TempDir,
292 impl<'a> SyntaxDetectionTest<'a> {
294 SyntaxDetectionTest {
295 assets: HighlightingAssets::from_binary(),
296 syntax_mapping: SyntaxMapping::builtin(),
297 temp_dir: TempDir::new("bat_syntax_detection_tests")
298 .expect("creation of temporary directory"),
302 fn syntax_for_real_file_with_content_os(
307 let file_path = self.temp_dir.path().join(file_name);
309 let mut temp_file = File::create(&file_path).unwrap();
310 writeln!(temp_file, "{}", first_line).unwrap();
313 let input = Input::ordinary_file(file_path.as_os_str());
314 let dummy_stdin: &[u8] = &[];
315 let mut opened_input = input.open(dummy_stdin).unwrap();
318 .get_syntax(None, &mut opened_input, &self.syntax_mapping)
319 .unwrap_or_else(|_| self.assets.syntax_set.find_syntax_plain_text())
324 fn syntax_for_file_with_content_os(&self, file_name: &OsStr, first_line: &str) -> String {
325 let file_path = self.temp_dir.path().join(file_name);
326 let input = Input::from_reader(Box::new(BufReader::new(first_line.as_bytes())))
327 .with_name(Some(file_path.as_os_str()));
328 let dummy_stdin: &[u8] = &[];
329 let mut opened_input = input.open(dummy_stdin).unwrap();
332 .get_syntax(None, &mut opened_input, &self.syntax_mapping)
333 .unwrap_or_else(|_| self.assets.syntax_set.find_syntax_plain_text())
338 fn syntax_for_file_os(&self, file_name: &OsStr) -> String {
339 self.syntax_for_file_with_content_os(file_name, "")
342 fn syntax_for_file_with_content(&self, file_name: &str, first_line: &str) -> String {
343 self.syntax_for_file_with_content_os(OsStr::new(file_name), first_line)
346 fn syntax_for_file(&self, file_name: &str) -> String {
347 self.syntax_for_file_with_content(file_name, "")
350 fn syntax_for_stdin_with_content(&self, file_name: &str, content: &[u8]) -> String {
351 let input = Input::stdin().with_name(Some(OsStr::new(file_name)));
352 let mut opened_input = input.open(content).unwrap();
355 .get_syntax(None, &mut opened_input, &self.syntax_mapping)
356 .unwrap_or_else(|_| self.assets.syntax_set.find_syntax_plain_text())
361 fn syntax_is_same_for_inputkinds(&self, file_name: &str, content: &str) -> bool {
362 let as_file = self.syntax_for_real_file_with_content_os(file_name.as_ref(), content);
363 let as_reader = self.syntax_for_file_with_content_os(file_name.as_ref(), content);
364 let consistent = as_file == as_reader;
365 // TODO: Compare StdIn somehow?
369 "Inconsistent syntax detection:\nFor File: {}\nFor Reader: {}",
379 fn syntax_detection_basic() {
380 let test = SyntaxDetectionTest::new();
382 assert_eq!(test.syntax_for_file("test.rs"), "Rust");
383 assert_eq!(test.syntax_for_file("test.cpp"), "C++");
384 assert_eq!(test.syntax_for_file("test.build"), "NAnt Build File");
386 test.syntax_for_file("PKGBUILD"),
387 "Bourne Again Shell (bash)"
389 assert_eq!(test.syntax_for_file(".bashrc"), "Bourne Again Shell (bash)");
390 assert_eq!(test.syntax_for_file("Makefile"), "Makefile");
395 fn syntax_detection_invalid_utf8() {
396 use std::os::unix::ffi::OsStrExt;
398 let test = SyntaxDetectionTest::new();
401 test.syntax_for_file_os(OsStr::from_bytes(b"invalid_\xFEutf8_filename.rs")),
407 fn syntax_detection_same_for_inputkinds() {
408 let mut test = SyntaxDetectionTest::new();
411 .insert("*.myext", MappingTarget::MapTo("C"))
414 .insert("MY_FILE", MappingTarget::MapTo("Markdown"))
417 assert!(test.syntax_is_same_for_inputkinds("Test.md", ""));
418 assert!(test.syntax_is_same_for_inputkinds("Test.txt", "#!/bin/bash"));
419 assert!(test.syntax_is_same_for_inputkinds(".bashrc", ""));
420 assert!(test.syntax_is_same_for_inputkinds("test.h", ""));
421 assert!(test.syntax_is_same_for_inputkinds("test.js", "#!/bin/bash"));
422 assert!(test.syntax_is_same_for_inputkinds("test.myext", ""));
423 assert!(test.syntax_is_same_for_inputkinds("MY_FILE", ""));
424 assert!(test.syntax_is_same_for_inputkinds("MY_FILE", "<?php"));
428 fn syntax_detection_well_defined_mapping_for_duplicate_extensions() {
429 let test = SyntaxDetectionTest::new();
431 assert_eq!(test.syntax_for_file("test.h"), "C++");
432 assert_eq!(test.syntax_for_file("test.sass"), "Sass");
433 assert_eq!(test.syntax_for_file("test.js"), "JavaScript (Babel)");
437 fn syntax_detection_first_line() {
438 let test = SyntaxDetectionTest::new();
441 test.syntax_for_file_with_content("my_script", "#!/bin/bash"),
442 "Bourne Again Shell (bash)"
445 test.syntax_for_file_with_content("build", "#!/bin/bash"),
446 "Bourne Again Shell (bash)"
449 test.syntax_for_file_with_content("my_script", "<?php"),
455 fn syntax_detection_with_custom_mapping() {
456 let mut test = SyntaxDetectionTest::new();
458 assert_eq!(test.syntax_for_file("test.h"), "C++");
460 .insert("*.h", MappingTarget::MapTo("C"))
462 assert_eq!(test.syntax_for_file("test.h"), "C");
466 fn syntax_detection_is_case_sensitive() {
467 let mut test = SyntaxDetectionTest::new();
469 assert_ne!(test.syntax_for_file("README.MD"), "Markdown");
471 .insert("*.MD", MappingTarget::MapTo("Markdown"))
473 assert_eq!(test.syntax_for_file("README.MD"), "Markdown");
477 fn syntax_detection_stdin_filename() {
478 let test = SyntaxDetectionTest::new();
480 // from file extension
481 assert_eq!(test.syntax_for_stdin_with_content("test.cpp", b"a"), "C++");
482 // from first line (fallback)
484 test.syntax_for_stdin_with_content("my_script", b"#!/bin/bash"),
485 "Bourne Again Shell (bash)"
491 fn syntax_detection_for_symlinked_file() {
492 use std::os::unix::fs::symlink;
494 let test = SyntaxDetectionTest::new();
495 let file_path = test.temp_dir.path().join("my_ssh_config_filename");
497 File::create(&file_path).unwrap();
499 let file_path_symlink = test.temp_dir.path().join(".ssh").join("config");
501 std::fs::create_dir(test.temp_dir.path().join(".ssh"))
502 .expect("creation of directory succeeds");
503 symlink(&file_path, &file_path_symlink).expect("creation of symbolic link succeeds");
505 let input = Input::ordinary_file(file_path_symlink.as_os_str());
506 let dummy_stdin: &[u8] = &[];
507 let mut opened_input = input.open(dummy_stdin).unwrap();
511 .get_syntax(None, &mut opened_input, &test.syntax_mapping)
512 .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