1
0
mirror of https://github.com/sharkdp/bat.git synced 2025-09-02 11:22:30 +01:00

Merge remote-tracking branch 'origin/master' into feature/668/add-systemwide-config

This commit is contained in:
Martin Nordholts
2022-09-04 20:44:23 +02:00
75 changed files with 1532 additions and 921 deletions

View File

@@ -43,8 +43,9 @@ pub struct SyntaxReferenceInSet<'a> {
pub syntax_set: &'a SyntaxSet,
}
/// Compress for size of ~700 kB instead of ~4600 kB at the cost of ~30% longer deserialization time
pub(crate) const COMPRESS_SYNTAXES: bool = true;
/// Lazy-loaded syntaxes are already compressed, and we don't want to compress
/// already compressed data.
pub(crate) const COMPRESS_SYNTAXES: bool = false;
/// We don't want to compress our [LazyThemeSet] since the lazy-loaded themes
/// within it are already compressed, and compressing another time just makes
@@ -68,10 +69,57 @@ impl HighlightingAssets {
}
}
/// The default theme.
///
/// ### Windows and Linux
///
/// Windows and most Linux distributions has a dark terminal theme by
/// default. On these platforms, this function always returns a theme that
/// looks good on a dark background.
///
/// ### macOS
///
/// On macOS the default terminal background is light, but it is common that
/// Dark Mode is active, which makes the terminal background dark. On this
/// platform, the default theme depends on
/// ```bash
/// defaults read -globalDomain AppleInterfaceStyle
/// ````
/// To avoid the overhead of the check on macOS, simply specify a theme
/// explicitly via `--theme`, `BAT_THEME`, or `~/.config/bat`.
///
/// See <https://github.com/sharkdp/bat/issues/1746> and
/// <https://github.com/sharkdp/bat/issues/1928> for more context.
pub fn default_theme() -> &'static str {
#[cfg(not(target_os = "macos"))]
{
Self::default_dark_theme()
}
#[cfg(target_os = "macos")]
{
if macos_dark_mode_active() {
Self::default_dark_theme()
} else {
Self::default_light_theme()
}
}
}
/**
* The default theme that looks good on a dark background.
*/
fn default_dark_theme() -> &'static str {
"Monokai Extended"
}
/**
* The default theme that looks good on a light background.
*/
#[cfg(target_os = "macos")]
fn default_light_theme() -> &'static str {
"Monokai Extended Light"
}
pub fn from_cache(cache_path: &Path) -> Result<Self> {
Ok(HighlightingAssets::new(
SerializedSyntaxSet::FromFile(cache_path.join("syntaxes.bin")),
@@ -351,6 +399,16 @@ fn asset_from_cache<T: serde::de::DeserializeOwned>(
.map_err(|_| format!("Could not parse cached {}", description).into())
}
#[cfg(target_os = "macos")]
fn macos_dark_mode_active() -> bool {
let mut defaults_cmd = std::process::Command::new("defaults");
defaults_cmd.args(&["read", "-globalDomain", "AppleInterfaceStyle"]);
match defaults_cmd.output() {
Ok(output) => output.stdout == b"Dark\n",
Err(_) => true,
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -581,13 +639,22 @@ mod tests {
}
#[test]
fn syntax_detection_is_case_sensitive() {
fn syntax_detection_is_case_insensitive() {
let mut test = SyntaxDetectionTest::new();
assert_ne!(test.syntax_for_file("README.MD"), "Markdown");
assert_eq!(test.syntax_for_file("README.md"), "Markdown");
assert_eq!(test.syntax_for_file("README.mD"), "Markdown");
assert_eq!(test.syntax_for_file("README.Md"), "Markdown");
assert_eq!(test.syntax_for_file("README.MD"), "Markdown");
// Adding a mapping for "MD" in addition to "md" should not break the mapping
test.syntax_mapping
.insert("*.MD", MappingTarget::MapTo("Markdown"))
.ok();
assert_eq!(test.syntax_for_file("README.md"), "Markdown");
assert_eq!(test.syntax_for_file("README.mD"), "Markdown");
assert_eq!(test.syntax_for_file("README.Md"), "Markdown");
assert_eq!(test.syntax_for_file("README.MD"), "Markdown");
}

View File

@@ -7,7 +7,7 @@ use serde::{Deserialize, Serialize};
use crate::error::*;
#[derive(Debug, PartialEq, Default, Serialize, Deserialize)]
#[derive(Debug, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct AssetsMetadata {
bat_version: Option<String>,
creation_time: Option<SystemTime>,

View File

@@ -1,3 +1,4 @@
use std::fmt::Write;
use std::fs::read_to_string;
use std::path::{Path, PathBuf};
@@ -124,7 +125,7 @@ fn append_to_acknowledgements(
relative_path: &str,
license_text: &str,
) {
acknowledgements.push_str(&format!("## {}\n\n{}", relative_path, license_text));
write!(acknowledgements, "## {}\n\n{}", relative_path, license_text).ok();
// Make sure the last char is a newline to not mess up formatting later
if acknowledgements

View File

@@ -1,6 +1,6 @@
use std::collections::HashSet;
use std::env;
use std::path::Path;
use std::path::{Path, PathBuf};
use std::str::FromStr;
use atty::{self, Stream};
@@ -32,7 +32,7 @@ fn is_truecolor_terminal() -> bool {
}
pub struct App {
pub matches: ArgMatches<'static>,
pub matches: ArgMatches,
interactive_output: bool,
}
@@ -49,7 +49,7 @@ impl App {
})
}
fn matches(interactive_output: bool) -> Result<ArgMatches<'static>> {
fn matches(interactive_output: bool) -> Result<ArgMatches> {
let args = if wild::args_os().nth(1) == Some("cache".into())
|| wild::args_os().any(|arg| arg == "--no-config")
{
@@ -79,13 +79,13 @@ impl App {
pub fn config(&self, inputs: &[Input]) -> Result<Config> {
let style_components = self.style_components()?;
let paging_mode = match self.matches.value_of("paging") {
let paging_mode = match self.matches.get_one::<String>("paging").map(|s| s.as_str()) {
Some("always") => PagingMode::Always,
Some("never") => PagingMode::Never,
Some("auto") | None => {
// If we have -pp as an option when in auto mode, the pager should be disabled.
let extra_plain = self.matches.occurrences_of("plain") > 1;
if extra_plain || self.matches.is_present("no-paging") {
let extra_plain = self.matches.get_count("plain") > 1;
if extra_plain || self.matches.get_flag("no-paging") {
PagingMode::Never
} else if inputs.iter().any(Input::is_stdin) {
// If we are reading from stdin, only enable paging if we write to an
@@ -107,13 +107,13 @@ impl App {
let mut syntax_mapping = SyntaxMapping::builtin();
if let Some(values) = self.matches.values_of("ignored-suffix") {
if let Some(values) = self.matches.get_many::<String>("ignored-suffix") {
for suffix in values {
syntax_mapping.insert_ignored_suffix(suffix);
}
}
if let Some(values) = self.matches.values_of("map-syntax") {
if let Some(values) = self.matches.get_many::<String>("map-syntax") {
for from_to in values {
let parts: Vec<_> = from_to.split(':').collect();
@@ -125,36 +125,43 @@ impl App {
}
}
let maybe_term_width = self.matches.value_of("terminal-width").and_then(|w| {
if w.starts_with('+') || w.starts_with('-') {
// Treat argument as a delta to the current terminal width
w.parse().ok().map(|delta: i16| {
let old_width: u16 = Term::stdout().size().1;
let new_width: i32 = i32::from(old_width) + i32::from(delta);
let maybe_term_width = self
.matches
.get_one::<String>("terminal-width")
.and_then(|w| {
if w.starts_with('+') || w.starts_with('-') {
// Treat argument as a delta to the current terminal width
w.parse().ok().map(|delta: i16| {
let old_width: u16 = Term::stdout().size().1;
let new_width: i32 = i32::from(old_width) + i32::from(delta);
if new_width <= 0 {
old_width as usize
} else {
new_width as usize
}
})
} else {
w.parse().ok()
}
});
if new_width <= 0 {
old_width as usize
} else {
new_width as usize
}
})
} else {
w.parse().ok()
}
});
Ok(Config {
true_color: is_truecolor_terminal(),
language: self.matches.value_of("language").or_else(|| {
if self.matches.is_present("show-all") {
Some("show-nonprintable")
} else {
None
}
}),
show_nonprintable: self.matches.is_present("show-all"),
language: self
.matches
.get_one::<String>("language")
.map(|s| s.as_str())
.or_else(|| {
if self.matches.get_flag("show-all") {
Some("show-nonprintable")
} else {
None
}
}),
show_nonprintable: self.matches.get_flag("show-all"),
wrapping_mode: if self.interactive_output || maybe_term_width.is_some() {
match self.matches.value_of("wrap") {
match self.matches.get_one::<String>("wrap").map(|s| s.as_str()) {
Some("character") => WrappingMode::Character,
Some("never") => WrappingMode::NoWrapping(true),
Some("auto") | None => {
@@ -171,8 +178,8 @@ impl App {
// There's no point in wrapping when this is the case.
WrappingMode::NoWrapping(false)
},
colored_output: self.matches.is_present("force-colorization")
|| match self.matches.value_of("color") {
colored_output: self.matches.get_flag("force-colorization")
|| match self.matches.get_one::<String>("color").map(|s| s.as_str()) {
Some("always") => true,
Some("never") => false,
Some("auto") => env::var_os("NO_COLOR").is_none() && self.interactive_output,
@@ -181,12 +188,16 @@ impl App {
paging_mode,
term_width: maybe_term_width.unwrap_or(Term::stdout().size().1 as usize),
loop_through: !(self.interactive_output
|| self.matches.value_of("color") == Some("always")
|| self.matches.value_of("decorations") == Some("always")
|| self.matches.is_present("force-colorization")),
|| self.matches.get_one::<String>("color").map(|s| s.as_str()) == Some("always")
|| self
.matches
.get_one::<String>("decorations")
.map(|s| s.as_str())
== Some("always")
|| self.matches.get_flag("force-colorization")),
tab_width: self
.matches
.value_of("tabs")
.get_one::<String>("tabs")
.map(String::from)
.or_else(|| env::var("BAT_TABS").ok())
.and_then(|t| t.parse().ok())
@@ -199,7 +210,7 @@ impl App {
),
theme: self
.matches
.value_of("theme")
.get_one::<String>("theme")
.map(String::from)
.or_else(|| env::var("BAT_THEME").ok())
.map(|s| {
@@ -210,19 +221,19 @@ impl App {
}
})
.unwrap_or_else(|| String::from(HighlightingAssets::default_theme())),
visible_lines: match self.matches.is_present("diff") {
visible_lines: match self.matches.contains_id("diff") && self.matches.get_flag("diff") {
#[cfg(feature = "git")]
true => VisibleLines::DiffContext(
self.matches
.value_of("diff-context")
.get_one::<String>("diff-context")
.and_then(|t| t.parse().ok())
.unwrap_or(2),
),
_ => VisibleLines::Ranges(
self.matches
.values_of("line-range")
.map(|vs| vs.map(LineRange::from).collect())
.get_many::<String>("line-range")
.map(|vs| vs.map(|s| LineRange::from(s.as_str())).collect())
.transpose()?
.map(LineRanges::from)
.unwrap_or_default(),
@@ -230,45 +241,47 @@ impl App {
},
style_components,
syntax_mapping,
pager: self.matches.value_of("pager"),
use_italic_text: self.matches.value_of("italic-text") == Some("always"),
pager: self.matches.get_one::<String>("pager").map(|s| s.as_str()),
use_italic_text: self
.matches
.get_one::<String>("italic-text")
.map(|s| s.as_str())
== Some("always"),
highlighted_lines: self
.matches
.values_of("highlight-line")
.map(|ws| ws.map(LineRange::from).collect())
.get_many::<String>("highlight-line")
.map(|ws| ws.map(|s| LineRange::from(s.as_str())).collect())
.transpose()?
.map(LineRanges::from)
.map(HighlightedLineRanges)
.unwrap_or_default(),
use_custom_assets: !self.matches.is_present("no-custom-assets"),
use_custom_assets: !self.matches.get_flag("no-custom-assets"),
})
}
pub fn inputs(&self) -> Result<Vec<Input>> {
// verify equal length of file-names and input FILEs
match self.matches.values_of("file-name") {
Some(ref filenames)
if self.matches.values_of_os("FILE").is_some()
&& filenames.len() != self.matches.values_of_os("FILE").unwrap().len() =>
{
return Err("Must be one file name per input type.".into());
}
_ => {}
}
let filenames: Option<Vec<&Path>> = self
.matches
.values_of_os("file-name")
.map(|values| values.map(Path::new).collect());
.get_many::<PathBuf>("file-name")
.map(|vs| vs.map(|p| p.as_path()).collect::<Vec<_>>());
let files: Option<Vec<&Path>> = self
.matches
.get_many::<PathBuf>("FILE")
.map(|vs| vs.map(|p| p.as_path()).collect::<Vec<_>>());
// verify equal length of file-names and input FILEs
if filenames.is_some()
&& files.is_some()
&& filenames.as_ref().map(|v| v.len()) != files.as_ref().map(|v| v.len())
{
return Err("Must be one file name per input type.".into());
}
let mut filenames_or_none: Box<dyn Iterator<Item = Option<&Path>>> = match filenames {
Some(filenames) => Box::new(filenames.into_iter().map(Some)),
None => Box::new(std::iter::repeat(None)),
};
let files: Option<Vec<&Path>> = self
.matches
.values_of_os("FILE")
.map(|vs| vs.map(Path::new).collect());
if files.is_none() {
return Ok(vec![new_stdin_input(
filenames_or_none.next().unwrap_or(None),
@@ -294,12 +307,12 @@ impl App {
fn style_components(&self) -> Result<StyleComponents> {
let matches = &self.matches;
let mut styled_components =
StyleComponents(if matches.value_of("decorations") == Some("never") {
let mut styled_components = StyleComponents(
if matches.get_one::<String>("decorations").map(|s| s.as_str()) == Some("never") {
HashSet::new()
} else if matches.is_present("number") {
} else if matches.get_flag("number") {
[StyleComponent::LineNumbers].iter().cloned().collect()
} else if matches.is_present("plain") {
} else if 0 < matches.get_count("plain") {
[StyleComponent::Plain].iter().cloned().collect()
} else {
let env_style_components: Option<Vec<StyleComponent>> = env::var("BAT_STYLE")
@@ -313,7 +326,7 @@ impl App {
.transpose()?;
matches
.value_of("style")
.get_one::<String>("style")
.map(|styles| {
styles
.split(',')
@@ -322,14 +335,15 @@ impl App {
.collect::<Vec<_>>()
})
.or(env_style_components)
.unwrap_or_else(|| vec![StyleComponent::Full])
.unwrap_or_else(|| vec![StyleComponent::Default])
.into_iter()
.map(|style| style.components(self.interactive_output))
.fold(HashSet::new(), |mut acc, components| {
acc.extend(components.iter().cloned());
acc
})
});
},
);
// If `grid` is set, remove `rule` as it is a subset of `grid`, and print a warning.
if styled_components.grid() && styled_components.0.remove(&StyleComponent::Rule) {

View File

@@ -1,7 +1,10 @@
use clap::{crate_name, crate_version, App as ClapApp, AppSettings, Arg, ArgGroup, SubCommand};
use clap::{
crate_name, crate_version, value_parser, AppSettings, Arg, ArgAction, ArgGroup, ColorChoice,
Command,
};
use once_cell::sync::Lazy;
use std::env;
use std::path::Path;
use std::path::{Path, PathBuf};
static VERSION: Lazy<String> = Lazy::new(|| {
#[cfg(feature = "bugreport")]
@@ -16,23 +19,21 @@ static VERSION: Lazy<String> = Lazy::new(|| {
}
});
pub fn build_app(interactive_output: bool) -> ClapApp<'static, 'static> {
let clap_color_setting = if interactive_output && env::var_os("NO_COLOR").is_none() {
AppSettings::ColoredHelp
pub fn build_app(interactive_output: bool) -> Command<'static> {
let color_when = if interactive_output && env::var_os("NO_COLOR").is_none() {
ColorChoice::Auto
} else {
AppSettings::ColorNever
ColorChoice::Never
};
let mut app = ClapApp::new(crate_name!())
let mut app = Command::new(crate_name!())
.version(VERSION.as_str())
.global_setting(clap_color_setting)
.color(color_when)
.global_setting(AppSettings::DeriveDisplayOrder)
.global_setting(AppSettings::UnifiedHelpMessage)
.global_setting(AppSettings::HidePossibleValuesInHelp)
.setting(AppSettings::ArgsNegateSubcommands)
.setting(AppSettings::AllowExternalSubcommands)
.setting(AppSettings::DisableHelpSubcommand)
.setting(AppSettings::VersionlessSubcommands)
.hide_possible_values(true)
.args_conflicts_with_subcommands(true)
.allow_external_subcommands(true)
.disable_help_subcommand(true)
.max_term_width(100)
.about(
"A cat(1) clone with wings.\n\n\
@@ -44,20 +45,22 @@ pub fn build_app(interactive_output: bool) -> ClapApp<'static, 'static> {
)
.long_about("A cat(1) clone with syntax highlighting and Git integration.")
.arg(
Arg::with_name("FILE")
Arg::new("FILE")
.help("File(s) to print / concatenate. Use '-' for standard input.")
.long_help(
"File(s) to print / concatenate. Use a dash ('-') or no argument at all \
to read from standard input.",
)
.multiple(true)
.empty_values(false),
.takes_value(true)
.multiple_values(true)
.value_parser(value_parser!(PathBuf)),
)
.arg(
Arg::with_name("show-all")
Arg::new("show-all")
.long("show-all")
.alias("show-nonprintable")
.short("A")
.short('A')
.action(ArgAction::SetTrue)
.conflicts_with("language")
.help("Show non-printable characters (space, tab, newline, ..).")
.long_help(
@@ -67,22 +70,22 @@ pub fn build_app(interactive_output: bool) -> ClapApp<'static, 'static> {
),
)
.arg(
Arg::with_name("plain")
Arg::new("plain")
.overrides_with("plain")
.overrides_with("number")
.short("p")
.short('p')
.long("plain")
.multiple(true)
.action(ArgAction::Count)
.help("Show plain style (alias for '--style=plain').")
.long_help(
"Only show plain style, no decorations. This is an alias for \
'--style=plain'. When '-p' is used twice ('-pp'), it also disables \
automatic paging (alias for '--style=plain --pager=never').",
automatic paging (alias for '--style=plain --paging=never').",
),
)
.arg(
Arg::with_name("language")
.short("l")
Arg::new("language")
.short('l')
.long("language")
.overrides_with("language")
.help("Set the language for syntax highlighting.")
@@ -95,12 +98,11 @@ pub fn build_app(interactive_output: bool) -> ClapApp<'static, 'static> {
.takes_value(true),
)
.arg(
Arg::with_name("highlight-line")
Arg::new("highlight-line")
.long("highlight-line")
.short("H")
.short('H')
.takes_value(true)
.number_of_values(1)
.multiple(true)
.action(ArgAction::Append)
.value_name("N:M")
.help("Highlight lines N through M.")
.long_help(
@@ -114,12 +116,12 @@ pub fn build_app(interactive_output: bool) -> ClapApp<'static, 'static> {
),
)
.arg(
Arg::with_name("file-name")
Arg::new("file-name")
.long("file-name")
.takes_value(true)
.number_of_values(1)
.multiple(true)
.action(ArgAction::Append)
.value_name("name")
.value_parser(value_parser!(PathBuf))
.help("Specify the name to display for a file.")
.long_help(
"Specify the name to display for a file. Useful when piping \
@@ -133,9 +135,11 @@ pub fn build_app(interactive_output: bool) -> ClapApp<'static, 'static> {
{
app = app
.arg(
Arg::with_name("diff")
Arg::new("diff")
.long("diff")
.short("d")
.short('d')
.action(ArgAction::SetTrue)
.conflicts_with("line-range")
.help("Only show lines that have been added/removed/modified.")
.long_help(
"Only show lines that have been added/removed/modified with respect \
@@ -143,20 +147,20 @@ pub fn build_app(interactive_output: bool) -> ClapApp<'static, 'static> {
),
)
.arg(
Arg::with_name("diff-context")
Arg::new("diff-context")
.long("diff-context")
.overrides_with("diff-context")
.takes_value(true)
.value_name("N")
.validator(
|n| {
.value_parser(
|n: &str| {
n.parse::<usize>()
.map_err(|_| "must be a number")
.map(|_| ()) // Convert to Result<(), &str>
.map(|_| n.to_owned()) // Convert to Result<String, &str>
.map_err(|e| e.to_string())
}, // Convert to Result<(), String>
)
.hidden_short_help(true)
.hide_short_help(true)
.long_help(
"Include N lines of context around added/removed/modified lines when using '--diff'.",
),
@@ -164,16 +168,16 @@ pub fn build_app(interactive_output: bool) -> ClapApp<'static, 'static> {
}
app = app.arg(
Arg::with_name("tabs")
Arg::new("tabs")
.long("tabs")
.overrides_with("tabs")
.takes_value(true)
.value_name("T")
.validator(
|t| {
.value_parser(
|t: &str| {
t.parse::<u32>()
.map_err(|_t| "must be a number")
.map(|_t| ()) // Convert to Result<(), &str>
.map(|_t| t.to_owned()) // Convert to Result<String, &str>
.map_err(|e| e.to_string())
}, // Convert to Result<(), String>
)
@@ -184,12 +188,12 @@ pub fn build_app(interactive_output: bool) -> ClapApp<'static, 'static> {
),
)
.arg(
Arg::with_name("wrap")
Arg::new("wrap")
.long("wrap")
.overrides_with("wrap")
.takes_value(true)
.value_name("mode")
.possible_values(&["auto", "never", "character"])
.value_parser(["auto", "never", "character"])
.default_value("auto")
.hide_default_value(true)
.help("Specify the text-wrapping mode (*auto*, never, character).")
@@ -198,21 +202,21 @@ pub fn build_app(interactive_output: bool) -> ClapApp<'static, 'static> {
control the output width."),
)
.arg(
Arg::with_name("terminal-width")
Arg::new("terminal-width")
.long("terminal-width")
.takes_value(true)
.value_name("width")
.hidden_short_help(true)
.hide_short_help(true)
.allow_hyphen_values(true)
.validator(
|t| {
.value_parser(
|t: &str| {
let is_offset = t.starts_with('+') || t.starts_with('-');
t.parse::<i32>()
.map_err(|_e| "must be an offset or number")
.and_then(|v| if v == 0 && !is_offset {
Err("terminal width cannot be zero")
} else {
Ok(())
Ok(t.to_owned())
})
.map_err(|e| e.to_string())
})
@@ -223,10 +227,11 @@ pub fn build_app(interactive_output: bool) -> ClapApp<'static, 'static> {
),
)
.arg(
Arg::with_name("number")
Arg::new("number")
.long("number")
.overrides_with("number")
.short("n")
.short('n')
.action(ArgAction::SetTrue)
.help("Show line numbers (alias for '--style=numbers').")
.long_help(
"Only show line numbers, no other decorations. This is an alias for \
@@ -234,12 +239,12 @@ pub fn build_app(interactive_output: bool) -> ClapApp<'static, 'static> {
),
)
.arg(
Arg::with_name("color")
Arg::new("color")
.long("color")
.overrides_with("color")
.takes_value(true)
.value_name("when")
.possible_values(&["auto", "never", "always"])
.value_parser(["auto", "never", "always"])
.hide_default_value(true)
.default_value("auto")
.help("When to use colors (*auto*, never, always).")
@@ -251,23 +256,23 @@ pub fn build_app(interactive_output: bool) -> ClapApp<'static, 'static> {
),
)
.arg(
Arg::with_name("italic-text")
Arg::new("italic-text")
.long("italic-text")
.takes_value(true)
.value_name("when")
.possible_values(&["always", "never"])
.value_parser(["always", "never"])
.default_value("never")
.hide_default_value(true)
.help("Use italics in output (always, *never*)")
.long_help("Specify when to use ANSI sequences for italic text in the output. Possible values: always, *never*."),
)
.arg(
Arg::with_name("decorations")
Arg::new("decorations")
.long("decorations")
.overrides_with("decorations")
.takes_value(true)
.value_name("when")
.possible_values(&["auto", "never", "always"])
.value_parser(["auto", "never", "always"])
.default_value("auto")
.hide_default_value(true)
.help("When to show the decorations (*auto*, never, always).")
@@ -278,24 +283,26 @@ pub fn build_app(interactive_output: bool) -> ClapApp<'static, 'static> {
),
)
.arg(
Arg::with_name("force-colorization")
Arg::new("force-colorization")
.long("force-colorization")
.short("f")
.short('f')
.action(ArgAction::SetTrue)
.conflicts_with("color")
.conflicts_with("decorations")
.overrides_with("force-colorization")
.hidden_short_help(true)
.hide_short_help(true)
.long_help("Alias for '--decorations=always --color=always'. This is useful \
if the output of bat is piped to another program, but you want \
to keep the colorization/decorations.")
)
.arg(
Arg::with_name("paging")
Arg::new("paging")
.long("paging")
.overrides_with("paging")
.overrides_with("no-paging")
.takes_value(true)
.value_name("when")
.possible_values(&["auto", "never", "always"])
.value_parser(["auto", "never", "always"])
.default_value("auto")
.hide_default_value(true)
.help("Specify when to use the pager, or use `-P` to disable (*auto*, never, always).")
@@ -307,22 +314,23 @@ pub fn build_app(interactive_output: bool) -> ClapApp<'static, 'static> {
),
)
.arg(
Arg::with_name("no-paging")
.short("P")
Arg::new("no-paging")
.short('P')
.long("no-paging")
.alias("no-pager")
.action(ArgAction::SetTrue)
.overrides_with("no-paging")
.hidden(true)
.hidden_short_help(true)
.hide(true)
.hide_short_help(true)
.help("Alias for '--paging=never'")
)
.arg(
Arg::with_name("pager")
Arg::new("pager")
.long("pager")
.overrides_with("pager")
.takes_value(true)
.value_name("command")
.hidden_short_help(true)
.hide_short_help(true)
.help("Determine which pager to use.")
.long_help(
"Determine which pager is used. This option will override the \
@@ -332,12 +340,11 @@ pub fn build_app(interactive_output: bool) -> ClapApp<'static, 'static> {
),
)
.arg(
Arg::with_name("map-syntax")
.short("m")
Arg::new("map-syntax")
.short('m')
.long("map-syntax")
.multiple(true)
.action(ArgAction::Append)
.takes_value(true)
.number_of_values(1)
.value_name("glob:syntax")
.help("Use the specified syntax for files matching the glob pattern ('*.cpp:C++').")
.long_help(
@@ -350,19 +357,18 @@ pub fn build_app(interactive_output: bool) -> ClapApp<'static, 'static> {
.takes_value(true),
)
.arg(
Arg::with_name("ignored-suffix")
.number_of_values(1)
.multiple(true)
Arg::new("ignored-suffix")
.action(ArgAction::Append)
.takes_value(true)
.long("ignored-suffix")
.hidden_short_help(true)
.hide_short_help(true)
.help(
"Ignore extension. For example:\n \
'bat --ignored-suffix \".dev\" my_file.json.dev' will use JSON syntax, and ignore '.dev'"
)
)
.arg(
Arg::with_name("theme")
Arg::new("theme")
.long("theme")
.overrides_with("theme")
.takes_value(true)
@@ -376,28 +382,30 @@ pub fn build_app(interactive_output: bool) -> ClapApp<'static, 'static> {
),
)
.arg(
Arg::with_name("list-themes")
Arg::new("list-themes")
.long("list-themes")
.action(ArgAction::SetTrue)
.help("Display all supported highlighting themes.")
.long_help("Display a list of supported themes for syntax highlighting."),
)
.arg(
Arg::with_name("style")
Arg::new("style")
.long("style")
.value_name("components")
// Need to turn this off for overrides_with to work as we want. See the bottom most
// example at https://docs.rs/clap/2.32.0/clap/struct.Arg.html#method.overrides_with
.use_delimiter(false)
.use_value_delimiter(false)
.takes_value(true)
.overrides_with("style")
.overrides_with("plain")
.overrides_with("number")
// Cannot use claps built in validation because we have to turn off clap's delimiters
.validator(|val| {
.value_parser(|val: &str| {
let mut invalid_vals = val.split(',').filter(|style| {
!&[
"auto",
"full",
"default",
"plain",
"header",
"header-filename",
@@ -414,12 +422,12 @@ pub fn build_app(interactive_output: bool) -> ClapApp<'static, 'static> {
if let Some(invalid) = invalid_vals.next() {
Err(format!("Unknown style, '{}'", invalid))
} else {
Ok(())
Ok(val.to_owned())
}
})
.help(
"Comma-separated list of style elements to display \
(*auto*, full, plain, changes, header, grid, rule, numbers, snip).",
(*default*, auto, full, plain, changes, header, header-filename, header-filesize, grid, rule, numbers, snip).",
)
.long_help(
"Configure which elements (line numbers, file headers, grid \
@@ -430,8 +438,9 @@ pub fn build_app(interactive_output: bool) -> ClapApp<'static, 'static> {
'--style=\"..\"' option to the configuration file or export the \
BAT_STYLE environment variable (e.g.: export BAT_STYLE=\"..\").\n\n\
Possible values:\n\n \
* full: enables all available components (default).\n \
* auto: same as 'full', unless the output is piped.\n \
* default: enables recommended style components (default).\n \
* full: enables all available components.\n \
* auto: same as 'default', unless the output is piped.\n \
* plain: disables all available components.\n \
* changes: show Git modification markers.\n \
* header: alias for 'header-filename'.\n \
@@ -445,14 +454,12 @@ pub fn build_app(interactive_output: bool) -> ClapApp<'static, 'static> {
),
)
.arg(
Arg::with_name("line-range")
Arg::new("line-range")
.long("line-range")
.short("r")
.multiple(true)
.short('r')
.action(ArgAction::Append)
.takes_value(true)
.number_of_values(1)
.value_name("N:M")
.conflicts_with("diff")
.help("Only print the lines from N to M.")
.long_help(
"Only print the specified range of lines for each file. \
@@ -465,18 +472,19 @@ pub fn build_app(interactive_output: bool) -> ClapApp<'static, 'static> {
),
)
.arg(
Arg::with_name("list-languages")
Arg::new("list-languages")
.long("list-languages")
.short("L")
.short('L')
.action(ArgAction::SetTrue)
.conflicts_with("list-themes")
.help("Display all supported languages.")
.long_help("Display a list of supported languages for syntax highlighting."),
)
.arg(
Arg::with_name("unbuffered")
.short("u")
Arg::new("unbuffered")
.short('u')
.long("unbuffered")
.hidden_short_help(true)
.hide_short_help(true)
.long_help(
"This option exists for POSIX-compliance reasons ('u' is for \
'unbuffered'). The output is always unbuffered - this option \
@@ -484,60 +492,66 @@ pub fn build_app(interactive_output: bool) -> ClapApp<'static, 'static> {
),
)
.arg(
Arg::with_name("no-config")
Arg::new("no-config")
.long("no-config")
.hidden(true)
.hide(true)
.help("Do not use the configuration file"),
)
.arg(
Arg::with_name("no-custom-assets")
Arg::new("no-custom-assets")
.long("no-custom-assets")
.hidden(true)
.action(ArgAction::SetTrue)
.hide(true)
.help("Do not load custom assets"),
)
.arg(
Arg::with_name("config-file")
Arg::new("config-file")
.long("config-file")
.action(ArgAction::SetTrue)
.conflicts_with("list-languages")
.conflicts_with("list-themes")
.hidden(true)
.hide(true)
.help("Show path to the configuration file."),
)
.arg(
Arg::with_name("generate-config-file")
Arg::new("generate-config-file")
.long("generate-config-file")
.action(ArgAction::SetTrue)
.conflicts_with("list-languages")
.conflicts_with("list-themes")
.hidden(true)
.hide(true)
.help("Generates a default configuration file."),
)
.arg(
Arg::with_name("config-dir")
Arg::new("config-dir")
.long("config-dir")
.hidden(true)
.action(ArgAction::SetTrue)
.hide(true)
.help("Show bat's configuration directory."),
)
.arg(
Arg::with_name("cache-dir")
Arg::new("cache-dir")
.long("cache-dir")
.hidden(true)
.action(ArgAction::SetTrue)
.hide(true)
.help("Show bat's cache directory."),
)
.arg(
Arg::with_name("diagnostic")
Arg::new("diagnostic")
.long("diagnostic")
.alias("diagnostics")
.hidden_short_help(true)
.action(ArgAction::SetTrue)
.hide_short_help(true)
.help("Show diagnostic information for bug reports.")
)
.arg(
Arg::with_name("acknowledgements")
Arg::new("acknowledgements")
.long("acknowledgements")
.hidden_short_help(true)
.action(ArgAction::SetTrue)
.hide_short_help(true)
.help("Show acknowledgements."),
)
.help_message("Print this help message.")
.version_message("Show version information.");
.mut_arg("help", |arg| arg.help("Print this help message."));
// Check if the current directory contains a file name cache. Otherwise,
// enable the 'bat cache' subcommand.
@@ -545,12 +559,13 @@ pub fn build_app(interactive_output: bool) -> ClapApp<'static, 'static> {
app
} else {
app.subcommand(
SubCommand::with_name("cache")
Command::new("cache")
.about("Modify the syntax-definition and theme cache")
.arg(
Arg::with_name("build")
Arg::new("build")
.long("build")
.short("b")
.short('b')
.action(ArgAction::SetTrue)
.help("Initialize (or update) the syntax/theme cache.")
.long_help(
"Initialize (or update) the syntax/theme cache by loading from \
@@ -558,18 +573,19 @@ pub fn build_app(interactive_output: bool) -> ClapApp<'static, 'static> {
),
)
.arg(
Arg::with_name("clear")
Arg::new("clear")
.long("clear")
.short("c")
.short('c')
.action(ArgAction::SetTrue)
.help("Remove the cached syntax definitions and themes."),
)
.group(
ArgGroup::with_name("cache-actions")
ArgGroup::new("cache-actions")
.args(&["build", "clear"])
.required(true),
)
.arg(
Arg::with_name("source")
Arg::new("source")
.long("source")
.requires("build")
.takes_value(true)
@@ -577,7 +593,7 @@ pub fn build_app(interactive_output: bool) -> ClapApp<'static, 'static> {
.help("Use a different directory to load syntaxes and themes from."),
)
.arg(
Arg::with_name("target")
Arg::new("target")
.long("target")
.requires("build")
.takes_value(true)
@@ -587,8 +603,9 @@ pub fn build_app(interactive_output: bool) -> ClapApp<'static, 'static> {
),
)
.arg(
Arg::with_name("blank")
Arg::new("blank")
.long("blank")
.action(ArgAction::SetTrue)
.requires("build")
.help(
"Create completely new syntax and theme sets \
@@ -596,11 +613,17 @@ pub fn build_app(interactive_output: bool) -> ClapApp<'static, 'static> {
),
)
.arg(
Arg::with_name("acknowledgements")
Arg::new("acknowledgements")
.long("acknowledgements")
.action(ArgAction::SetTrue)
.requires("build")
.help("Build acknowledgements.bin."),
),
)
}
}
#[test]
fn verify_app() {
build_app(false).debug_assert();
}

View File

@@ -8,6 +8,7 @@ mod directories;
mod input;
use std::collections::{HashMap, HashSet};
use std::fmt::Write as _;
use std::io;
use std::io::{BufReader, Write};
use std::path::Path;
@@ -42,30 +43,30 @@ const THEME_PREVIEW_DATA: &[u8] = include_bytes!("../../../assets/theme_preview.
#[cfg(feature = "build-assets")]
fn build_assets(matches: &clap::ArgMatches) -> Result<()> {
let source_dir = matches
.value_of("source")
.get_one::<String>("source")
.map(Path::new)
.unwrap_or_else(|| PROJECT_DIRS.config_dir());
let target_dir = matches
.value_of("target")
.get_one::<String>("target")
.map(Path::new)
.unwrap_or_else(|| PROJECT_DIRS.cache_dir());
bat::assets::build(
source_dir,
!matches.is_present("blank"),
matches.is_present("acknowledgements"),
!matches.get_flag("blank"),
matches.get_flag("acknowledgements"),
target_dir,
clap::crate_version!(),
)
}
fn run_cache_subcommand(matches: &clap::ArgMatches) -> Result<()> {
if matches.is_present("build") {
if matches.get_flag("build") {
#[cfg(feature = "build-assets")]
build_assets(matches)?;
#[cfg(not(feature = "build-assets"))]
println!("bat has been built without the 'build-assets' feature. The 'cache --build' option is not available.");
} else if matches.is_present("clear") {
} else if matches.get_flag("clear") {
clear_assets();
}
@@ -128,7 +129,7 @@ pub fn get_languages(config: &Config) -> Result<String> {
if config.loop_through {
for lang in languages {
result += &format!("{}:{}\n", lang.name, lang.file_extensions.join(","));
writeln!(result, "{}:{}", lang.name, lang.file_extensions.join(",")).ok();
}
} else {
let longest = languages
@@ -149,7 +150,7 @@ pub fn get_languages(config: &Config) -> Result<String> {
};
for lang in languages {
result += &format!("{:width$}{}", lang.name, separator, width = longest);
write!(result, "{:width$}{}", lang.name, separator, width = longest).ok();
// Number of characters on this line so far, wrap before `desired_width`
let mut num_chars = 0;
@@ -160,11 +161,11 @@ pub fn get_languages(config: &Config) -> Result<String> {
let new_chars = word.len() + comma_separator.len();
if num_chars + new_chars >= desired_width {
num_chars = 0;
result += &format!("\n{:width$}{}", "", separator, width = longest);
write!(result, "\n{:width$}{}", "", separator, width = longest).ok();
}
num_chars += new_chars;
result += &format!("{}", style.paint(&word[..]));
write!(result, "{}", style.paint(&word[..])).ok();
if extension.peek().is_some() {
result += comma_separator;
}
@@ -230,8 +231,10 @@ fn run_controller(inputs: Vec<Input>, config: &Config) -> Result<bool> {
#[cfg(feature = "bugreport")]
fn invoke_bugreport(app: &App) {
use bugreport::{bugreport, collector::*, format::Markdown};
let pager = bat::config::get_pager_executable(app.matches.value_of("pager"))
.unwrap_or_else(|| "less".to_owned()); // FIXME: Avoid non-canonical path to "less".
let pager = bat::config::get_pager_executable(
app.matches.get_one::<String>("pager").map(|s| s.as_str()),
)
.unwrap_or_else(|| "less".to_owned()); // FIXME: Avoid non-canonical path to "less".
let mut custom_assets_metadata = PROJECT_DIRS.cache_dir().to_path_buf();
custom_assets_metadata.push("metadata.yaml");
@@ -265,6 +268,10 @@ fn invoke_bugreport(app: &App) {
"Custom assets metadata",
custom_assets_metadata,
))
.info(DirectoryEntries::new(
"Custom assets",
PROJECT_DIRS.cache_dir(),
))
.info(CompileTimeInformation::default());
#[cfg(feature = "paging")]
@@ -284,7 +291,7 @@ fn invoke_bugreport(app: &App) {
fn run() -> Result<bool> {
let app = App::new()?;
if app.matches.is_present("diagnostic") {
if app.matches.get_flag("diagnostic") {
#[cfg(feature = "bugreport")]
invoke_bugreport(&app);
#[cfg(not(feature = "bugreport"))]
@@ -293,11 +300,11 @@ fn run() -> Result<bool> {
}
match app.matches.subcommand() {
("cache", Some(cache_matches)) => {
Some(("cache", cache_matches)) => {
// If there is a file named 'cache' in the current working directory,
// arguments for subcommand 'cache' are not mandatory.
// If there are non-zero arguments, execute the subcommand cache, else, open the file cache.
if !cache_matches.args.is_empty() {
if cache_matches.args_present() {
run_cache_subcommand(cache_matches)?;
Ok(true)
} else {
@@ -311,7 +318,7 @@ fn run() -> Result<bool> {
let inputs = app.inputs()?;
let config = app.config(&inputs)?;
if app.matches.is_present("list-languages") {
if app.matches.get_flag("list-languages") {
let languages: String = get_languages(&config)?;
let inputs: Vec<Input> = vec![Input::from_reader(Box::new(languages.as_bytes()))];
let plain_config = Config {
@@ -320,22 +327,22 @@ fn run() -> Result<bool> {
..Default::default()
};
run_controller(inputs, &plain_config)
} else if app.matches.is_present("list-themes") {
} else if app.matches.get_flag("list-themes") {
list_themes(&config)?;
Ok(true)
} else if app.matches.is_present("config-file") {
} else if app.matches.get_flag("config-file") {
println!("{}", config_file().to_string_lossy());
Ok(true)
} else if app.matches.is_present("generate-config-file") {
} else if app.matches.get_flag("generate-config-file") {
generate_config_file()?;
Ok(true)
} else if app.matches.is_present("config-dir") {
} else if app.matches.get_flag("config-dir") {
writeln!(io::stdout(), "{}", config_dir())?;
Ok(true)
} else if app.matches.is_present("cache-dir") {
} else if app.matches.get_flag("cache-dir") {
writeln!(io::stdout(), "{}", cache_dir())?;
Ok(true)
} else if app.matches.is_present("acknowledgements") {
} else if app.matches.get_flag("acknowledgements") {
writeln!(io::stdout(), "{}", bat::assets::get_acknowledgements())?;
Ok(true)
} else {

View File

@@ -2,11 +2,14 @@ use std::io::Write;
use thiserror::Error;
#[derive(Error, Debug)]
#[non_exhaustive]
pub enum Error {
#[error(transparent)]
Io(#[from] ::std::io::Error),
#[error(transparent)]
SyntectError(#[from] ::syntect::LoadingError),
SyntectError(#[from] ::syntect::Error),
#[error(transparent)]
SyntectLoadingError(#[from] ::syntect::LoadingError),
#[error(transparent)]
ParseIntError(#[from] ::std::num::ParseIntError),
#[error(transparent)]

View File

@@ -118,7 +118,7 @@ impl OpenedInput<'_> {
self.metadata
.user_provided_name
.as_ref()
.or_else(|| match self.kind {
.or(match self.kind {
OpenedInputKind::OrdinaryFile(ref path) => Some(path),
_ => None,
})

View File

@@ -3,21 +3,38 @@
use std::ffi::OsStr;
use std::process::Command;
pub fn retrieve_less_version(less_path: &dyn AsRef<OsStr>) -> Option<usize> {
#[derive(Debug, PartialEq, Eq)]
pub enum LessVersion {
Less(usize),
BusyBox,
}
pub fn retrieve_less_version(less_path: &dyn AsRef<OsStr>) -> Option<LessVersion> {
let resolved_path = grep_cli::resolve_binary(less_path.as_ref()).ok()?;
let cmd = Command::new(resolved_path).arg("--version").output().ok()?;
parse_less_version(&cmd.stdout)
if cmd.status.success() {
parse_less_version(&cmd.stdout)
} else {
parse_less_version_busybox(&cmd.stderr)
}
}
fn parse_less_version(output: &[u8]) -> Option<usize> {
fn parse_less_version(output: &[u8]) -> Option<LessVersion> {
if !output.starts_with(b"less ") {
return None;
}
let version = std::str::from_utf8(&output[5..]).ok()?;
let end = version.find(|c: char| !c.is_ascii_digit())?;
version[..end].parse::<usize>().ok()
Some(LessVersion::Less(version[..end].parse::<usize>().ok()?))
}
fn parse_less_version_busybox(output: &[u8]) -> Option<LessVersion> {
match std::str::from_utf8(output) {
Ok(version) if version.contains("BusyBox ") => Some(LessVersion::BusyBox),
_ => None,
}
}
#[test]
@@ -30,7 +47,7 @@ For information about the terms of redistribution,
see the file named README in the less distribution.
Homepage: http://www.greenwoodsoftware.com/less";
assert_eq!(Some(487), parse_less_version(output));
assert_eq!(Some(LessVersion::Less(487)), parse_less_version(output));
}
#[test]
@@ -43,7 +60,7 @@ For information about the terms of redistribution,
see the file named README in the less distribution.
Homepage: http://www.greenwoodsoftware.com/less";
assert_eq!(Some(529), parse_less_version(output));
assert_eq!(Some(LessVersion::Less(529)), parse_less_version(output));
}
#[test]
@@ -56,7 +73,7 @@ For information about the terms of redistribution,
see the file named README in the less distribution.
Home page: http://www.greenwoodsoftware.com/less";
assert_eq!(Some(551), parse_less_version(output));
assert_eq!(Some(LessVersion::Less(551)), parse_less_version(output));
}
#[test]
@@ -69,7 +86,7 @@ For information about the terms of redistribution,
see the file named README in the less distribution.
Home page: https://greenwoodsoftware.com/less";
assert_eq!(Some(581), parse_less_version(output));
assert_eq!(Some(LessVersion::Less(581)), parse_less_version(output));
}
#[test]
@@ -77,4 +94,38 @@ fn test_parse_less_version_wrong_program() {
let output = b"more from util-linux 2.34";
assert_eq!(None, parse_less_version(output));
assert_eq!(None, parse_less_version_busybox(output));
}
#[test]
fn test_parse_less_version_busybox() {
let output = b"pkg/less: unrecognized option '--version'
BusyBox v1.35.0 (2022-04-21 10:38:11 EDT) multi-call binary.
Usage: less [-EFIMmNSRh~] [FILE]...
View FILE (or stdin) one screenful at a time
-E Quit once the end of a file is reached
-F Quit if entire file fits on first screen
-I Ignore case in all searches
-M,-m Display status line with line numbers
and percentage through the file
-N Prefix line number to each line
-S Truncate long lines
-R Remove color escape codes in input
-~ Suppress ~s displayed past EOF";
assert_eq!(
Some(LessVersion::BusyBox),
parse_less_version_busybox(output)
);
}
#[test]
fn test_parse_less_version_invalid_utf_8() {
let output = b"\xff";
assert_eq!(None, parse_less_version(output));
assert_eq!(None, parse_less_version_busybox(output));
}

View File

@@ -46,10 +46,9 @@ pub(crate) mod printer;
pub mod style;
pub(crate) mod syntax_mapping;
mod terminal;
mod vscreen;
pub(crate) mod wrapping;
pub use pretty_printer::{Input, PrettyPrinter};
pub use pretty_printer::{Input, PrettyPrinter, Syntax};
pub use syntax_mapping::{MappingTarget, SyntaxMapping};
pub use wrapping::WrappingMode;

View File

@@ -168,7 +168,7 @@ fn test_parse_minus_fail() {
assert!(range.is_err());
}
#[derive(Copy, Clone, Debug, PartialEq)]
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum RangeCheckResult {
// Within one of the given ranges
InRange,

View File

@@ -4,7 +4,7 @@ use std::process::Child;
use crate::error::*;
#[cfg(feature = "paging")]
use crate::less::retrieve_less_version;
use crate::less::{retrieve_less_version, LessVersion};
#[cfg(feature = "paging")]
use crate::paging::PagingMode;
#[cfg(feature = "paging")]
@@ -83,13 +83,13 @@ impl OutputType {
let replace_arguments_to_less = pager.source == PagerSource::EnvVarPager;
if args.is_empty() || replace_arguments_to_less {
p.arg("--RAW-CONTROL-CHARS");
p.arg("-R"); // Short version of --RAW-CONTROL-CHARS for maximum compatibility
if single_screen_action == SingleScreenAction::Quit {
p.arg("--quit-if-one-screen");
p.arg("-F"); // Short version of --quit-if-one-screen for compatibility
}
if wrapping_mode == WrappingMode::NoWrapping(true) {
p.arg("--chop-long-lines");
p.arg("-S"); // Short version of --chop-long-lines for compatibility
}
// Passing '--no-init' fixes a bug with '--quit-if-one-screen' in older
@@ -103,7 +103,9 @@ impl OutputType {
None => {
p.arg("--no-init");
}
Some(version) if (version < 530 || (cfg!(windows) && version < 558)) => {
Some(LessVersion::Less(version))
if (version < 530 || (cfg!(windows) && version < 558)) =>
{
p.arg("--no-init");
}
_ => {}

View File

@@ -40,15 +40,23 @@ impl PagerKind {
fn from_bin(bin: &str) -> PagerKind {
use std::path::Path;
match Path::new(bin)
.file_stem()
.map(|s| s.to_string_lossy())
.as_deref()
{
Some("bat") => PagerKind::Bat,
// Set to `less` by default on most Linux distros.
let pager_bin = Path::new(bin).file_stem();
// The name of the current running binary. Normally `bat` but sometimes
// `batcat` for compatibility reasons.
let current_bin = env::args_os().next();
// Check if the current running binary is set to be our pager.
let is_current_bin_pager = current_bin
.map(|s| Path::new(&s).file_stem() == pager_bin)
.unwrap_or(false);
match pager_bin.map(|s| s.to_string_lossy()).as_deref() {
Some("less") => PagerKind::Less,
Some("more") => PagerKind::More,
Some("most") => PagerKind::Most,
_ if is_current_bin_pager => PagerKind::Bat,
_ => PagerKind::Unknown,
}
}

View File

@@ -1,4 +1,4 @@
#[derive(Debug, Clone, Copy, PartialEq)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PagingMode {
Always,
QuitIfOneScreen,

View File

@@ -1,35 +1,28 @@
use console::AnsiCodeIterator;
use std::fmt::Write;
/// Expand tabs like an ANSI-enabled expand(1).
pub fn expand_tabs(line: &str, width: usize, cursor: &mut usize) -> String {
let mut buffer = String::with_capacity(line.len() * 2);
pub fn expand_tabs(mut text: &str, width: usize, cursor: &mut usize) -> String {
let mut buffer = String::with_capacity(text.len() * 2);
for chunk in AnsiCodeIterator::new(line) {
match chunk {
(text, true) => buffer.push_str(text),
(mut text, false) => {
while let Some(index) = text.find('\t') {
// Add previous text.
if index > 0 {
*cursor += index;
buffer.push_str(&text[0..index]);
}
// Add tab.
let spaces = width - (*cursor % width);
*cursor += spaces;
buffer.push_str(&*" ".repeat(spaces));
// Next.
text = &text[index + 1..text.len()];
}
*cursor += text.len();
buffer.push_str(text);
}
while let Some(index) = text.find('\t') {
// Add previous text.
if index > 0 {
*cursor += index;
buffer.push_str(&text[0..index]);
}
// Add tab.
let spaces = width - (*cursor % width);
*cursor += spaces;
buffer.push_str(&*" ".repeat(spaces));
// Next.
text = &text[index + 1..text.len()];
}
*cursor += text.len();
buffer.push_str(text);
buffer
}
@@ -101,7 +94,7 @@ pub fn replace_nonprintable(input: &[u8], tab_width: usize) -> String {
c => output.push_str(&c.escape_unicode().collect::<String>()),
}
} else {
output.push_str(&format!("\\x{:02X}", input[idx]));
write!(output, "\\x{:02X}", input[idx]).ok();
idx += 1;
}
}

View File

@@ -2,7 +2,6 @@ use std::io::Read;
use std::path::Path;
use console::Term;
use syntect::parsing::SyntaxReference;
use crate::{
assets::HighlightingAssets,
@@ -28,6 +27,12 @@ struct ActiveStyleComponents {
snip: bool,
}
#[non_exhaustive]
pub struct Syntax {
pub name: String,
pub file_extensions: Vec<String>,
}
pub struct PrettyPrinter<'a> {
inputs: Vec<Input<'a>>,
config: Config<'a>,
@@ -164,6 +169,12 @@ impl<'a> PrettyPrinter<'a> {
self
}
/// Whether to print binary content or nonprintable characters (default: no)
pub fn show_nonprintable(&mut self, yes: bool) -> &mut Self {
self.config.show_nonprintable = yes;
self
}
/// Whether to show "snip" markers between visible line ranges (default: no)
pub fn snip(&mut self, yes: bool) -> &mut Self {
self.active_style_components.snip = yes;
@@ -234,10 +245,18 @@ impl<'a> PrettyPrinter<'a> {
self.assets.themes()
}
pub fn syntaxes(&self) -> impl Iterator<Item = &SyntaxReference> {
pub fn syntaxes(&self) -> impl Iterator<Item = Syntax> + '_ {
// We always use assets from the binary, which are guaranteed to always
// be valid, so get_syntaxes() can never fail here
self.assets.get_syntaxes().unwrap().iter()
self.assets
.get_syntaxes()
.unwrap()
.iter()
.filter(|s| !s.hidden)
.map(|s| Syntax {
name: s.name.clone(),
file_extensions: s.file_extensions.clone(),
})
}
/// Pretty-print all specified inputs. This method will "use" all stored inputs.

View File

@@ -6,8 +6,6 @@ use ansi_term::Style;
use bytesize::ByteSize;
use console::AnsiCodeIterator;
use syntect::easy::HighlightLines;
use syntect::highlighting::Color;
use syntect::highlighting::Theme;
@@ -33,7 +31,6 @@ use crate::line_range::RangeCheckResult;
use crate::preprocessor::{expand_tabs, replace_nonprintable};
use crate::style::StyleComponent;
use crate::terminal::{as_terminal_escaped, to_ansi_color};
use crate::vscreen::AnsiStyle;
use crate::wrapping::WrappingMode;
pub(crate) trait Printer {
@@ -122,7 +119,6 @@ pub(crate) struct InteractivePrinter<'a> {
config: &'a Config<'a>,
decorations: Vec<Box<dyn Decoration>>,
panel_width: usize,
ansi_style: AnsiStyle,
content_type: Option<ContentType>,
#[cfg(feature = "git")]
pub line_changes: &'a Option<LineChanges>,
@@ -206,7 +202,6 @@ impl<'a> InteractivePrinter<'a> {
config,
decorations,
content_type: input.reader.content_type,
ansi_style: AnsiStyle::new(),
#[cfg(feature = "git")]
line_changes,
highlighter_from_set,
@@ -445,9 +440,21 @@ impl<'a> Printer for InteractivePrinter<'a> {
return Ok(());
}
};
highlighter_from_set
// skip syntax highlighting on long lines
let too_long = line.len() > 1024 * 16;
let for_highlighting: &str = if too_long { "\n" } else { &line };
let mut highlighted_line = highlighter_from_set
.highlighter
.highlight(&line, highlighter_from_set.syntax_set)
.highlight_line(for_highlighting, highlighter_from_set.syntax_set)?;
if too_long {
highlighted_line[0].1 = &line;
}
highlighted_line
};
if out_of_range {
@@ -464,7 +471,7 @@ impl<'a> Printer for InteractivePrinter<'a> {
self.config.highlighted_lines.0.check(line_number) == RangeCheckResult::InRange;
if highlight_this_line && self.config.theme == "ansi" {
self.ansi_style.update("^[4m");
write!(handle, "\x1B[4m")?;
}
let background_color = self
@@ -491,51 +498,37 @@ impl<'a> Printer for InteractivePrinter<'a> {
let italics = self.config.use_italic_text;
for &(style, region) in &regions {
let ansi_iterator = AnsiCodeIterator::new(region);
for chunk in ansi_iterator {
match chunk {
// ANSI escape passthrough.
(ansi, true) => {
self.ansi_style.update(ansi);
write!(handle, "{}", ansi)?;
}
let text = &*self.preprocess(region, &mut cursor_total);
let text_trimmed = text.trim_end_matches(|c| c == '\r' || c == '\n');
// Regular text.
(text, false) => {
let text = &*self.preprocess(text, &mut cursor_total);
let text_trimmed = text.trim_end_matches(|c| c == '\r' || c == '\n');
write!(
handle,
"{}",
as_terminal_escaped(
style,
text_trimmed,
true_color,
colored_output,
italics,
background_color
)
)?;
write!(
handle,
"{}",
as_terminal_escaped(
style,
&format!("{}{}", self.ansi_style, text_trimmed),
true_color,
colored_output,
italics,
background_color
)
)?;
if text.len() != text_trimmed.len() {
if let Some(background_color) = background_color {
let ansi_style = Style {
background: to_ansi_color(background_color, true_color),
..Default::default()
};
if text.len() != text_trimmed.len() {
if let Some(background_color) = background_color {
let ansi_style = Style {
background: to_ansi_color(background_color, true_color),
..Default::default()
};
let width = if cursor_total <= cursor_max {
cursor_max - cursor_total + 1
} else {
0
};
write!(handle, "{}", ansi_style.paint(" ".repeat(width)))?;
}
write!(handle, "{}", &text[text_trimmed.len()..])?;
}
}
let width = if cursor_total <= cursor_max {
cursor_max - cursor_total + 1
} else {
0
};
write!(handle, "{}", ansi_style.paint(" ".repeat(width)))?;
}
write!(handle, "{}", &text[text_trimmed.len()..])?;
}
}
@@ -544,98 +537,82 @@ impl<'a> Printer for InteractivePrinter<'a> {
}
} else {
for &(style, region) in &regions {
let ansi_iterator = AnsiCodeIterator::new(region);
for chunk in ansi_iterator {
match chunk {
// ANSI escape passthrough.
(ansi, true) => {
self.ansi_style.update(ansi);
write!(handle, "{}", ansi)?;
}
let text = self.preprocess(
region.trim_end_matches(|c| c == '\r' || c == '\n'),
&mut cursor_total,
);
// Regular text.
(text, false) => {
let text = self.preprocess(
text.trim_end_matches(|c| c == '\r' || c == '\n'),
&mut cursor_total,
);
let mut max_width = cursor_max - cursor;
let mut max_width = cursor_max - cursor;
// line buffer (avoid calling write! for every character)
let mut line_buf = String::with_capacity(max_width * 4);
// line buffer (avoid calling write! for every character)
let mut line_buf = String::with_capacity(max_width * 4);
// Displayed width of line_buf
let mut current_width = 0;
// Displayed width of line_buf
let mut current_width = 0;
for c in text.chars() {
// calculate the displayed width for next character
let cw = c.width().unwrap_or(0);
current_width += cw;
for c in text.chars() {
// calculate the displayed width for next character
let cw = c.width().unwrap_or(0);
current_width += cw;
// if next character cannot be printed on this line,
// flush the buffer.
if current_width > max_width {
// Generate wrap padding if not already generated.
if panel_wrap.is_none() {
panel_wrap = if self.panel_width > 0 {
Some(format!(
"{} ",
self.decorations
.iter()
.map(|d| d
.generate(line_number, true, self)
.text)
.collect::<Vec<String>>()
.join(" ")
))
} else {
Some("".to_string())
}
}
// It wraps.
write!(
handle,
"{}\n{}",
as_terminal_escaped(
style,
&*format!("{}{}", self.ansi_style, line_buf),
self.config.true_color,
self.config.colored_output,
self.config.use_italic_text,
background_color
),
panel_wrap.clone().unwrap()
)?;
cursor = 0;
max_width = cursor_max;
line_buf.clear();
current_width = cw;
}
line_buf.push(c);
// if next character cannot be printed on this line,
// flush the buffer.
if current_width > max_width {
// Generate wrap padding if not already generated.
if panel_wrap.is_none() {
panel_wrap = if self.panel_width > 0 {
Some(format!(
"{} ",
self.decorations
.iter()
.map(|d| d.generate(line_number, true, self).text)
.collect::<Vec<String>>()
.join(" ")
))
} else {
Some("".to_string())
}
// flush the buffer
cursor += current_width;
write!(
handle,
"{}",
as_terminal_escaped(
style,
&*format!("{}{}", self.ansi_style, line_buf),
self.config.true_color,
self.config.colored_output,
self.config.use_italic_text,
background_color
)
)?;
}
// It wraps.
write!(
handle,
"{}\n{}",
as_terminal_escaped(
style,
&line_buf,
self.config.true_color,
self.config.colored_output,
self.config.use_italic_text,
background_color
),
panel_wrap.clone().unwrap()
)?;
cursor = 0;
max_width = cursor_max;
line_buf.clear();
current_width = cw;
}
line_buf.push(c);
}
// flush the buffer
cursor += current_width;
write!(
handle,
"{}",
as_terminal_escaped(
style,
&line_buf,
self.config.true_color,
self.config.colored_output,
self.config.use_italic_text,
background_color
)
)?;
}
if let Some(background_color) = background_color {
@@ -654,7 +631,6 @@ impl<'a> Printer for InteractivePrinter<'a> {
}
if highlight_this_line && self.config.theme == "ansi" {
self.ansi_style.update("^[24m");
write!(handle, "\x1B[24m")?;
}

View File

@@ -17,6 +17,7 @@ pub enum StyleComponent {
LineNumbers,
Snip,
Full,
Default,
Plain,
}
@@ -25,7 +26,7 @@ impl StyleComponent {
match self {
StyleComponent::Auto => {
if interactive_terminal {
StyleComponent::Full.components(interactive_terminal)
StyleComponent::Default.components(interactive_terminal)
} else {
StyleComponent::Plain.components(interactive_terminal)
}
@@ -48,6 +49,14 @@ impl StyleComponent {
StyleComponent::LineNumbers,
StyleComponent::Snip,
],
StyleComponent::Default => &[
#[cfg(feature = "git")]
StyleComponent::Changes,
StyleComponent::Grid,
StyleComponent::HeaderFilename,
StyleComponent::LineNumbers,
StyleComponent::Snip,
],
StyleComponent::Plain => &[],
}
}
@@ -69,6 +78,7 @@ impl FromStr for StyleComponent {
"numbers" => Ok(StyleComponent::LineNumbers),
"snip" => Ok(StyleComponent::Snip),
"full" => Ok(StyleComponent::Full),
"default" => Ok(StyleComponent::Default),
"plain" => Ok(StyleComponent::Plain),
_ => Err(format!("Unknown style '{}'", s).into()),
}

View File

@@ -7,7 +7,7 @@ use globset::{Candidate, GlobBuilder, GlobMatcher};
pub mod ignored_suffixes;
#[derive(Debug, Clone, Copy, PartialEq)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum MappingTarget<'a> {
/// For mapping a path to a specific syntax.
@@ -67,6 +67,11 @@ impl<'a> SyntaxMapping<'a> {
.insert("*.pac", MappingTarget::MapTo("JavaScript (Babel)"))
.unwrap();
// See #2151, https://nmap.org/book/nse-language.html
mapping
.insert("*.nse", MappingTarget::MapTo("Lua"))
.unwrap();
// See #1008
mapping
.insert("rails", MappingTarget::MapToUnknown)
@@ -120,6 +125,11 @@ impl<'a> SyntaxMapping<'a> {
mapping.insert(glob, MappingTarget::MapTo("INI")).unwrap();
}
// unix mail spool
for glob in &["/var/spool/mail/*", "/var/mail/*"] {
mapping.insert(glob, MappingTarget::MapTo("Email")).unwrap()
}
// pacman hooks
mapping
.insert("*.hook", MappingTarget::MapTo("INI"))
@@ -181,6 +191,7 @@ impl<'a> SyntaxMapping<'a> {
}
pub(crate) fn get_syntax_for(&self, path: impl AsRef<Path>) -> Option<MappingTarget<'a>> {
// Try matching on the file name as-is.
let candidate = Candidate::new(&path);
let candidate_filename = path.as_ref().file_name().map(Candidate::new);
for (ref glob, ref syntax) in self.mappings.iter().rev() {
@@ -192,7 +203,13 @@ impl<'a> SyntaxMapping<'a> {
return Some(*syntax);
}
}
None
// Try matching on the file name after removing an ignored suffix.
let file_name = path.as_ref().file_name()?;
self.ignored_suffixes
.try_with_stripped_suffix(file_name, |stripped_file_name| {
Ok(self.get_syntax_for(stripped_file_name))
})
.ok()?
}
pub fn insert_ignored_suffix(&mut self, suffix: &'a str) {

View File

@@ -1,212 +0,0 @@
use std::fmt::{Display, Formatter};
// Wrapper to avoid unnecessary branching when input doesn't have ANSI escape sequences.
pub struct AnsiStyle {
attributes: Option<Attributes>,
}
impl AnsiStyle {
pub fn new() -> Self {
AnsiStyle { attributes: None }
}
pub fn update(&mut self, sequence: &str) -> bool {
match &mut self.attributes {
Some(a) => a.update(sequence),
None => {
self.attributes = Some(Attributes::new());
self.attributes.as_mut().unwrap().update(sequence)
}
}
}
}
impl Display for AnsiStyle {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self.attributes {
Some(ref a) => a.fmt(f),
None => Ok(()),
}
}
}
struct Attributes {
foreground: String,
background: String,
underlined: String,
/// The character set to use.
/// REGEX: `\^[()][AB0-3]`
charset: String,
/// A buffer for unknown sequences.
unknown_buffer: String,
/// ON: ^[1m
/// OFF: ^[22m
bold: String,
/// ON: ^[2m
/// OFF: ^[22m
dim: String,
/// ON: ^[4m
/// OFF: ^[24m
underline: String,
/// ON: ^[3m
/// OFF: ^[23m
italic: String,
/// ON: ^[9m
/// OFF: ^[29m
strike: String,
}
impl Attributes {
pub fn new() -> Self {
Attributes {
foreground: "".to_owned(),
background: "".to_owned(),
underlined: "".to_owned(),
charset: "".to_owned(),
unknown_buffer: "".to_owned(),
bold: "".to_owned(),
dim: "".to_owned(),
underline: "".to_owned(),
italic: "".to_owned(),
strike: "".to_owned(),
}
}
/// Update the attributes with an escape sequence.
/// Returns `false` if the sequence is unsupported.
pub fn update(&mut self, sequence: &str) -> bool {
let mut chars = sequence.char_indices().skip(1);
if let Some((_, t)) = chars.next() {
match t {
'(' => self.update_with_charset('(', chars.map(|(_, c)| c)),
')' => self.update_with_charset(')', chars.map(|(_, c)| c)),
'[' => {
if let Some((i, last)) = chars.last() {
// SAFETY: Always starts with ^[ and ends with m.
self.update_with_csi(last, &sequence[2..i])
} else {
false
}
}
_ => self.update_with_unsupported(sequence),
}
} else {
false
}
}
fn sgr_reset(&mut self) {
self.foreground.clear();
self.background.clear();
self.underlined.clear();
self.bold.clear();
self.dim.clear();
self.underline.clear();
self.italic.clear();
self.strike.clear();
}
fn update_with_sgr(&mut self, parameters: &str) -> bool {
let mut iter = parameters
.split(';')
.map(|p| if p.is_empty() { "0" } else { p })
.map(|p| p.parse::<u16>())
.map(|p| p.unwrap_or(0)); // Treat errors as 0.
while let Some(p) = iter.next() {
match p {
0 => self.sgr_reset(),
1 => self.bold = format!("\x1B[{}m", parameters),
2 => self.dim = format!("\x1B[{}m", parameters),
3 => self.italic = format!("\x1B[{}m", parameters),
4 => self.underline = format!("\x1B[{}m", parameters),
23 => self.italic.clear(),
24 => self.underline.clear(),
22 => {
self.bold.clear();
self.dim.clear();
}
30..=39 => self.foreground = Self::parse_color(p, &mut iter),
40..=49 => self.background = Self::parse_color(p, &mut iter),
58..=59 => self.underlined = Self::parse_color(p, &mut iter),
90..=97 => self.foreground = Self::parse_color(p, &mut iter),
100..=107 => self.foreground = Self::parse_color(p, &mut iter),
_ => {
// Unsupported SGR sequence.
// Be compatible and pretend one just wasn't was provided.
}
}
}
true
}
fn update_with_csi(&mut self, finalizer: char, sequence: &str) -> bool {
if finalizer == 'm' {
self.update_with_sgr(sequence)
} else {
false
}
}
fn update_with_unsupported(&mut self, sequence: &str) -> bool {
self.unknown_buffer.push_str(sequence);
false
}
fn update_with_charset(&mut self, kind: char, set: impl Iterator<Item = char>) -> bool {
self.charset = format!("\x1B{}{}", kind, set.take(1).collect::<String>());
true
}
fn parse_color(color: u16, parameters: &mut dyn Iterator<Item = u16>) -> String {
match color % 10 {
8 => match parameters.next() {
Some(5) /* 256-color */ => format!("\x1B[{};5;{}m", color, join(";", 1, parameters)),
Some(2) /* 24-bit color */ => format!("\x1B[{};2;{}m", color, join(";", 3, parameters)),
Some(c) => format!("\x1B[{};{}m", color, c),
_ => "".to_owned(),
},
9 => "".to_owned(),
_ => format!("\x1B[{}m", color),
}
}
}
impl Display for Attributes {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{}{}{}{}{}{}{}{}{}",
self.foreground,
self.background,
self.underlined,
self.charset,
self.bold,
self.dim,
self.underline,
self.italic,
self.strike,
)
}
}
fn join(
delimiter: &str,
limit: usize,
iterator: &mut dyn Iterator<Item = impl ToString>,
) -> String {
iterator
.take(limit)
.map(|i| i.to_string())
.collect::<Vec<String>>()
.join(delimiter)
}