1use std::collections::HashSet;
5use atty::{self, Stream};
16use crate::assets::BAT_THEME_DEFAULT;
17use crate::config::{get_args_from_config_file, get_args_from_env_var};
19use crate::inputfile::InputFile;
20use crate::line_range::{LineRange, LineRanges};
21use crate::style::{OutputComponent, OutputComponents, OutputWrap};
22use crate::syntax_mapping::SyntaxMapping;
23use crate::util::transpose;
25#[derive(Debug, Clone, Copy, PartialEq)]
33pub struct Config<'a> {
34 /// List of files to print
35 pub files: Vec<InputFile<'a>>,
37 /// The explicitly configured language, if any
38 pub language: Option<&'a str>,
40 /// Whether or not to show/replace non-printable characters like space, tab and newline.
41 pub show_nonprintable: bool,
43 /// The character width of the terminal
44 pub term_width: usize,
46 /// The width of tab characters.
47 /// Currently, a value of 0 will cause tabs to be passed through without expanding them.
50 /// Whether or not to simply loop through all input (`cat` mode)
51 pub loop_through: bool,
53 /// Whether or not the output should be colorized
54 pub colored_output: bool,
56 /// Whether or not the output terminal supports true color
59 /// Style elements (grid, line numbers, ...)
60 pub output_components: OutputComponents,
62 /// Text wrapping mode
63 pub output_wrap: OutputWrap,
66 pub paging_mode: PagingMode,
68 /// Specifies the lines that should be printed
69 pub line_ranges: LineRanges,
71 /// The syntax highlighting theme
74 /// File extension/name mappings
75 pub syntax_mapping: SyntaxMapping,
77 /// Command to start the pager
78 pub pager: Option<&'a str>,
80 /// Whether or not to use ANSI italics
81 pub use_italic_text: bool,
83 /// Lines to highlight
84 pub highlight_lines: Vec<usize>,
87fn is_truecolor_terminal() -> bool {
89 .map(|colorterm| colorterm == "truecolor" || colorterm == "24bit")
94 pub matches: ArgMatches<'static>,
95 interactive_output: bool,
99 pub fn new() -> Result<Self> {
101 let _ = ansi_term::enable_ansi_support();
103 let interactive_output = atty::is(Stream::Stdout);
106 matches: Self::matches(interactive_output)?,
111 fn matches(interactive_output: bool) -> Result<ArgMatches<'static>> {
112 let args = if wild::args_os().nth(1) == Some("cache".into())
113 || wild::args_os().any(|arg| arg == "--no-config")
115 // Skip the arguments in bats config file
117 wild::args_os().collect::<Vec<_>>()
119 let mut cli_args = wild::args_os();
121 // Read arguments from bats config file
122 let mut args = get_args_from_env_var()
123 .unwrap_or_else(get_args_from_config_file)
124 .chain_err(|| "Could not parse configuration file")?;
126 // Put the zero-th CLI argument (program name) first
127 args.insert(0, cli_args.next().unwrap());
129 // .. and the rest at the end
130 cli_args.for_each(|a| args.push(a));
135 Ok(clap_app::build_app(interactive_output).get_matches_from(args))
138 pub fn config(&self) -> Result<Config> {
139 let files = self.files();
140 let output_components = self.output_components()?;
142 let paging_mode = match self.matches.value_of("paging") {
143 Some("always") => PagingMode::Always,
144 Some("never") => PagingMode::Never,
145 Some("auto") | _ => {
146 if files.contains(&InputFile::StdIn) {
147 // If we are reading from stdin, only enable paging if we write to an
148 // interactive terminal and if we do not *read* from an interactive
150 if self.interactive_output && !atty::is(Stream::Stdin) {
151 PagingMode::QuitIfOneScreen
155 } else if self.interactive_output {
156 PagingMode::QuitIfOneScreen
163 let mut syntax_mapping = SyntaxMapping::new();
165 if let Some(values) = self.matches.values_of("map-syntax") {
166 for from_to in values {
167 let parts: Vec<_> = from_to.split(':').collect();
169 if parts.len() != 2 {
170 return Err("Invalid syntax mapping. The format of the -m/--map-syntax option is 'from:to'.".into());
173 syntax_mapping.insert(parts[0], parts[1]);
178 true_color: is_truecolor_terminal(),
179 language: self.matches.value_of("language").or_else(|| {
180 if self.matches.is_present("show-all") {
181 Some("show-nonprintable")
186 show_nonprintable: self.matches.is_present("show-all"),
187 output_wrap: if !self.interactive_output {
188 // We don't have the tty width when piping to another program.
189 // There's no point in wrapping when this is the case.
192 match self.matches.value_of("wrap") {
193 Some("character") => OutputWrap::Character,
194 Some("never") => OutputWrap::None,
195 Some("auto") | _ => {
196 if output_components.plain() {
199 OutputWrap::Character
204 colored_output: match self.matches.value_of("color") {
205 Some("always") => true,
206 Some("never") => false,
207 Some("auto") | _ => self.interactive_output,
212 .value_of("terminal-width")
214 if w.starts_with('+') || w.starts_with('-') {
215 // Treat argument as a delta to the current terminal width
216 w.parse().ok().map(|delta: i16| {
217 let old_width: u16 = Term::stdout().size().1;
218 let new_width: i32 = i32::from(old_width) + i32::from(delta);
230 .unwrap_or(Term::stdout().size().1 as usize),
231 loop_through: !(self.interactive_output
232 || self.matches.value_of("color") == Some("always")
233 || self.matches.value_of("decorations") == Some("always")),
239 .or_else(|| env::var("BAT_TABS").ok())
240 .and_then(|t| t.parse().ok())
242 if output_components.plain() && paging_mode == PagingMode::Never {
252 .or_else(|| env::var("BAT_THEME").ok())
253 .unwrap_or_else(|| String::from(BAT_THEME_DEFAULT)),
254 line_ranges: LineRanges::from(
257 .values_of("line-range")
258 .map(|vs| vs.map(LineRange::from).collect()),
260 .unwrap_or_else(|| vec![]),
264 pager: self.matches.value_of("pager"),
265 use_italic_text: match self.matches.value_of("italic-text") {
266 Some("always") => true,
269 highlight_lines: self
271 .values_of("highlight-line")
272 .and_then(|ws| ws.map(|w| w.parse().ok()).collect())
273 .unwrap_or_default(),
277 fn files(&self) -> Vec<InputFile> {
286 InputFile::Ordinary(filename)
291 .unwrap_or_else(|| vec![InputFile::StdIn])
294 fn output_components(&self) -> Result<OutputComponents> {
295 let matches = &self.matches;
297 if matches.value_of("decorations") == Some("never") {
299 } else if matches.is_present("number") {
300 [OutputComponent::Numbers].iter().cloned().collect()
301 } else if matches.is_present("plain") {
302 [OutputComponent::Plain].iter().cloned().collect()
304 let env_style_components: Option<Vec<OutputComponent>> =
305 transpose(env::var("BAT_STYLE").ok().map(|style_str| {
308 .map(|x| OutputComponent::from_str(&x))
309 .collect::<Result<Vec<OutputComponent>>>()
317 .map(|style| style.parse::<OutputComponent>())
318 .filter_map(|style| style.ok())
321 .or(env_style_components)
322 .unwrap_or_else(|| vec![OutputComponent::Full])
324 .map(|style| style.components(self.interactive_output))
325 .fold(HashSet::new(), |mut acc, components| {
326 acc.extend(components.iter().cloned());
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