Expose new theme selection in CLI

This commit is contained in:
Tau Gärtli
2024-07-18 15:38:28 +02:00
parent cda363a3f7
commit cea45e05f3
8 changed files with 227 additions and 33 deletions

View File

@ -9,6 +9,9 @@ use crate::{
config::{get_args_from_config_file, get_args_from_env_opts_var, get_args_from_env_vars},
};
use bat::style::StyleComponentList;
use bat::theme::{
theme, ColorScheme, ColorSchemeDetector, DetectColorScheme, ThemeOptions, ThemeRequest,
};
use bat::StripAnsiMode;
use clap::ArgMatches;
@ -16,7 +19,6 @@ use console::Term;
use crate::input::{new_file_input, new_stdin_input};
use bat::{
assets::HighlightingAssets,
bat_warning,
config::{Config, VisibleLines},
error::*,
@ -254,18 +256,7 @@ impl App {
Some("auto") => StripAnsiMode::Auto,
_ => unreachable!("other values for --strip-ansi are not allowed"),
},
theme: self
.matches
.get_one::<String>("theme")
.map(String::from)
.map(|s| {
if s == "default" {
String::from(HighlightingAssets::default_theme())
} else {
s
}
})
.unwrap_or_else(|| String::from(HighlightingAssets::default_theme())),
theme: theme(self.theme_options(), &TerminalColorSchemeDetector),
visible_lines: match self.matches.try_contains_id("diff").unwrap_or_default()
&& self.matches.get_flag("diff")
{
@ -424,4 +415,72 @@ impl App {
Ok(styled_components)
}
fn theme_options(&self) -> ThemeOptions {
let theme = self
.matches
.get_one::<String>("theme")
.map(|t| ThemeRequest::from_str(t).unwrap());
let theme_dark = self
.matches
.get_one::<String>("theme-dark")
.map(|t| ThemeRequest::from_str(t).unwrap());
let theme_light = self
.matches
.get_one::<String>("theme-light")
.map(|t| ThemeRequest::from_str(t).unwrap());
let detect_color_scheme = match self
.matches
.get_one::<String>("detect-color-scheme")
.map(|s| s.as_str())
{
Some("auto") => DetectColorScheme::Auto,
Some("never") => DetectColorScheme::Never,
Some("always") => DetectColorScheme::Always,
_ => unreachable!("other values for --detect-color-scheme are not allowed"),
};
ThemeOptions {
theme,
theme_dark,
theme_light,
detect_color_scheme,
}
}
}
struct TerminalColorSchemeDetector;
#[cfg(feature = "detect-color-scheme")]
impl ColorSchemeDetector for TerminalColorSchemeDetector {
fn should_detect(&self) -> bool {
// Querying the terminal for its colors via OSC 10 / OSC 11 requires "exclusive" access
// since we read/write from the terminal and enable/disable raw mode.
// This causes race conditions with pagers such as less when they are attached to the
// same terminal as us.
//
// This is usually only an issue when the output is manually piped to a pager.
// For example: `bat Cargo.toml | less`.
// Otherwise, if we start the pager ourselves, then there's no race condition
// since the pager is started *after* the color is detected.
std::io::stdout().is_terminal()
}
fn detect(&self) -> Option<ColorScheme> {
use terminal_colorsaurus::{color_scheme, ColorScheme as ColorsaurusScheme, QueryOptions};
match color_scheme(QueryOptions::default()).ok()? {
ColorsaurusScheme::Dark => Some(ColorScheme::Dark),
ColorsaurusScheme::Light => Some(ColorScheme::Light),
}
}
}
#[cfg(not(feature = "detect-color-scheme"))]
impl ColorSchemeDetector for TerminalColorSchemeDetector {
fn should_detect(&self) -> bool {
false
}
fn detect(&self) -> Option<ColorScheme> {
None
}
}

View File

@ -375,13 +375,64 @@ pub fn build_app(interactive_output: bool) -> Command {
.overrides_with("theme")
.help("Set the color theme for syntax highlighting.")
.long_help(
"Set the theme for syntax highlighting. Use '--list-themes' to \
"Set the theme for syntax highlighting. Note that this option overrides \
'--theme-dark' and '--theme-light'. Use '--list-themes' to \
see all available themes. To set a default theme, add the \
'--theme=\"...\"' option to the configuration file or export the \
BAT_THEME environment variable (e.g.: export \
BAT_THEME=\"...\").",
),
)
.arg(
Arg::new("detect-color-scheme")
.long("detect-color-scheme")
.overrides_with("detect-color-scheme")
.value_name("when")
.value_parser(["auto", "never", "always"])
.default_value("auto")
.hide_default_value(true)
.help("Specify when to query the terminal for its colors.")
.long_help(
"Specify when to query the terminal for its colors \
in order to pick an appropriate syntax highlighting theme. \
Use '--theme-light' and '--theme-dark' (or the environment variables \
BAT_THEME_LIGHT and BAT_THEME_DARK) to configure which themes are picked. \
You may also use '--theme' to set a theme that is used regardless of the terminal's colors.\n\n\
Possible values:\n\
* auto (default):\n \
Only query the terminals colors if the output is not redirected. \
This is to prevent race conditions with pagers such as less.\n\
* never\n \
Never query the terminal for its colors \
and assume that the terminal has a dark background.\n\
* always\n \
Always query the terminal for its colors, \
regardless of whether or not the output is redirected."),
)
.arg(
Arg::new("theme-light")
.long("theme-light")
.overrides_with("theme-light")
.value_name("theme")
.help("Sets the color theme for syntax highlighting used for light backgrounds.")
.long_help(
"Sets the theme name for syntax highlighting used when the terminal uses a light background. \
Use '--list-themes' to see all available themes. To set a default theme, add the \
'--theme-light=\"...\" option to the configuration file or export the BAT_THEME_LIGHT \
environment variable (e.g. export BAT_THEME_LIGHT=\"...\")."),
)
.arg(
Arg::new("theme-dark")
.long("theme-dark")
.overrides_with("theme-dark")
.value_name("theme")
.help("Sets the color theme for syntax highlighting used for dark backgrounds.")
.long_help(
"Sets the theme name for syntax highlighting used when the terminal uses a dark background. \
Use '--list-themes' to see all available themes. To set a default theme, add the \
'--theme-dark=\"...\" option to the configuration file or export the BAT_THEME_DARK \
environment variable (e.g. export BAT_THEME_DARK=\"...\")."),
)
.arg(
Arg::new("list-themes")
.long("list-themes")

View File

@ -141,6 +141,8 @@ pub fn get_args_from_env_vars() -> Vec<OsString> {
[
("--tabs", "BAT_TABS"),
("--theme", "BAT_THEME"),
("--theme-dark", "BAT_THEME_DARK"),
("--theme-light", "BAT_THEME_LIGHT"),
("--pager", "BAT_PAGER"),
("--paging", "BAT_PAGING"),
("--style", "BAT_STYLE"),

View File

@ -18,8 +18,8 @@ pub fn theme(options: ThemeOptions, detector: &dyn ColorSchemeDetector) -> Strin
fn choose_theme(options: ThemeOptions, color_scheme: ColorScheme) -> Option<ThemeRequest> {
match color_scheme {
ColorScheme::Dark => options.dark_theme,
ColorScheme::Light => options.light_theme,
ColorScheme::Dark => options.theme_dark,
ColorScheme::Light => options.theme_light,
}
}
@ -45,9 +45,9 @@ pub struct ThemeOptions {
/// Always use this theme regardless of the terminal's background color.
pub theme: Option<ThemeRequest>,
/// The theme to use in case the terminal uses a dark background with light text.
pub dark_theme: Option<ThemeRequest>,
pub theme_dark: Option<ThemeRequest>,
/// The theme to use in case the terminal uses a light background with dark text.
pub light_theme: Option<ThemeRequest>,
pub theme_light: Option<ThemeRequest>,
/// Detect whether or not the terminal is dark or light by querying for its colors.
pub detect_color_scheme: DetectColorScheme,
}
@ -182,8 +182,8 @@ mod tests {
},
ThemeOptions {
theme: Some(ThemeRequest::Named("Theme".to_string())),
dark_theme: Some(ThemeRequest::Named("Dark Theme".to_string())),
light_theme: Some(ThemeRequest::Named("Light Theme".to_string())),
theme_dark: Some(ThemeRequest::Named("Dark Theme".to_string())),
theme_light: Some(ThemeRequest::Named("Light Theme".to_string())),
..Default::default()
},
] {
@ -237,8 +237,8 @@ mod tests {
for options in [
ThemeOptions::default(),
ThemeOptions {
dark_theme: Some(ThemeRequest::Default),
light_theme: Some(ThemeRequest::Default),
theme_dark: Some(ThemeRequest::Default),
theme_light: Some(ThemeRequest::Default),
..Default::default()
},
] {
@ -256,8 +256,8 @@ mod tests {
fn chooses_dark_theme_if_dark_or_unknown() {
for color_scheme in [Some(Dark), None] {
let options = ThemeOptions {
dark_theme: Some(ThemeRequest::Named("Dark".to_string())),
light_theme: Some(ThemeRequest::Named("Light".to_string())),
theme_dark: Some(ThemeRequest::Named("Dark".to_string())),
theme_light: Some(ThemeRequest::Named("Light".to_string())),
..Default::default()
};
let detector = ConstantDetector(color_scheme);
@ -268,8 +268,8 @@ mod tests {
#[test]
fn chooses_light_theme_if_light() {
let options = ThemeOptions {
dark_theme: Some(ThemeRequest::Named("Dark".to_string())),
light_theme: Some(ThemeRequest::Named("Light".to_string())),
theme_dark: Some(ThemeRequest::Named("Dark".to_string())),
theme_light: Some(ThemeRequest::Named("Light".to_string())),
..Default::default()
};
let detector = ConstantDetector(Some(ColorScheme::Light));