on master help sign in
Also replace 'more' from PAGER with 'less'
bfa5342Martin Nordholts
CHANGELOG.md+1−1
@@ -11,7 +11,7 @@
11- Make ./tests/syntax-tests/regression_test.sh work on recent versions of macOS, see #1443 (@Enselic)
11- Make ./tests/syntax-tests/regression_test.sh work on recent versions of macOS, see #1443 (@Enselic)
12- VimL syntax highlighting fix, see #1450 (@esensar)
12- VimL syntax highlighting fix, see #1450 (@esensar)
13- Print an 'Invalid syntax theme settings' error message if a custom theme is broken, see #614 (@Enselic)
13- Print an 'Invalid syntax theme settings' error message if a custom theme is broken, see #614 (@Enselic)
14−- If `PAGER=most` (but not `BAT_PAGER` or `--pager`), silently use `less` instead since `most` does not support colors, see #1063 (@Enselic)
14+- If `PAGER` (but not `BAT_PAGER` or `--pager`) is `more` or `most`, silently use `less` instead to ensure support for colors, see #1063 (@Enselic)
15
15
16## Other
16## Other
17
17
src/output.rs+54−73
@@ -48,90 +48,71 @@ impl OutputType {
48 wrapping_mode: WrappingMode,
48 wrapping_mode: WrappingMode,
49 pager_from_config: Option<&str>,
49 pager_from_config: Option<&str>,
50 ) -> Result<Self> {
50 ) -> Result<Self> {
51− use std::ffi::OsString;
51+ use crate::pager::{self, PagerKind, PagerSource};
52− use std::path::PathBuf;
53 use std::process::{Command, Stdio};
52 use std::process::{Command, Stdio};
54− use crate::pager::*;
55
53
54+ let pager_opt =
56− let Pager { pager, source } = get_pager(pager_from_config);
55+ pager::get_pager(pager_from_config).chain_err(|| "Could not parse pager command.")?;
57
56
58− let pagerflags =
57+ let pager = match pager_opt {
59− shell_words::split(&pager).chain_err(|| "Could not parse pager command.")?;
58+ Some(pager) => pager,
59+ None => return Ok(OutputType::stdout()),
60+ };
60
61
61− match pagerflags.split_first() {
62+ if pager.kind == PagerKind::Bat {
62− Some((pager_name, pager_args)) => {
63+ return Err(ErrorKind::InvalidPagerValueBat.into());
63− let mut pager_path = PathBuf::from(pager_name);
64+ }
64− let mut args = pager_args;
65− let empty_args = vec![];
66
65
67− if pager_path.file_stem() == Some(&OsString::from("bat")) {
66+ let mut p = Command::new(pager.bin);
68− return Err(ErrorKind::InvalidPagerValueBat.into());
67+ let args = pager.args;
68+
69+ if pager.kind == PagerKind::Less {
70+ // less needs to be called with the '-R' option in order to properly interpret the
71+ // ANSI color sequences printed by bat. If someone has set PAGER="less -F", we
72+ // therefore need to overwrite the arguments and add '-R'.
73+ //
74+ // We only do this for PAGER (as it is not specific to 'bat'), not for BAT_PAGER
75+ // or bats '--pager' command line option.
76+ let replace_arguments_to_less = pager.source == PagerSource::PagerEnvVar;
77+
78+ if args.is_empty() || replace_arguments_to_less {
79+ p.arg("--RAW-CONTROL-CHARS");
80+ if single_screen_action == SingleScreenAction::Quit {
81+ p.arg("--quit-if-one-screen");
69 }
82 }
70
83
71− if pager_path.file_stem() == Some(&OsString::from("most")) && source == PagerSource::PagerEnvVar {
84+ if wrapping_mode == WrappingMode::NoWrapping {
72− pager_path = PathBuf::from("less");
85+ p.arg("--chop-long-lines");
73− args = &empty_args;
74 }
86 }
75
87
76− let is_less = pager_path.file_stem() == Some(&OsString::from("less"));
77−
78− let mut process = if is_less {
79− // less needs to be called with the '-R' option in order to properly interpret the
80− // ANSI color sequences printed by bat. If someone has set PAGER="less -F", we
81− // therefore need to overwrite the arguments and add '-R'.
82− //
83− // We only do this for PAGER (as it is not specific to 'bat'), not for BAT_PAGER
84− // or bats '--pager' command line option.
85− let replace_arguments_to_less = source == PagerSource::PagerEnvVar;
86−
87− let mut p = Command::new(&pager_path);
88− if args.is_empty() || replace_arguments_to_less {
89− p.arg("--RAW-CONTROL-CHARS");
90− if single_screen_action == SingleScreenAction::Quit {
91− p.arg("--quit-if-one-screen");
92− }
93−
94− if wrapping_mode == WrappingMode::NoWrapping {
95− p.arg("--chop-long-lines");
96− }
97−
98− // Passing '--no-init' fixes a bug with '--quit-if-one-screen' in older
88+ // Passing '--no-init' fixes a bug with '--quit-if-one-screen' in older
99− // versions of 'less'. Unfortunately, it also breaks mouse-wheel support.
89+ // versions of 'less'. Unfortunately, it also breaks mouse-wheel support.
100− //
90+ //
101− // See: http://www.greenwoodsoftware.com/less/news.530.html
91+ // See: http://www.greenwoodsoftware.com/less/news.530.html
102− //
92+ //
103− // For newer versions (530 or 558 on Windows), we omit '--no-init' as it
93+ // For newer versions (530 or 558 on Windows), we omit '--no-init' as it
104− // is not needed anymore.
94+ // is not needed anymore.
105− match retrieve_less_version() {
95+ match retrieve_less_version() {
106− None => {
96+ None => {
107− p.arg("--no-init");
97+ p.arg("--no-init");
108− }
98+ }
109− Some(version)
110− if (version < 530 || (cfg!(windows) && version < 558)) =>
99+ Some(version) if (version < 530 || (cfg!(windows) && version < 558)) => {
111− {
112− p.arg("--no-init");
100+ p.arg("--no-init");
113− }
114− _ => {}
115− }
116− } else {
117− p.args(args);
118 }
101 }
119− p.env("LESSCHARSET", "UTF-8");
102+ _ => {}
120− p
103+ }
121− } else {
104+ } else {
122− let mut p = Command::new(&pager_path);
123− p.args(args);
105+ p.args(args);
124− p
125− };
126−
127− Ok(process
128− .stdin(Stdio::piped())
129− .spawn()
130− .map(OutputType::Pager)
131− .unwrap_or_else(|_| OutputType::stdout()))
132 }
106 }
107+ p.env("LESSCHARSET", "UTF-8");
108+ } else {
109+ p.args(args);
110+ };
111+
112+ Ok(p.stdin(Stdio::piped())
113+ .spawn()
114+ .map(OutputType::Pager)
133− None => Ok(OutputType::stdout()),
115+ .unwrap_or_else(|_| OutputType::stdout()))
134− }
135 }
116 }
136
117
137 pub(crate) fn stdout() -> Self {
118 pub(crate) fn stdout() -> Self {
src/pager.rs+89−13
@@ -1,3 +1,6 @@
1+use shell_words::ParseError;
2+use std::env;
3+
1/// If we use a pager, this enum tells us from where we were told to use it.
4/// If we use a pager, this enum tells us from where we were told to use it.
2#[derive(Debug, PartialEq)]
5#[derive(Debug, PartialEq)]
3pub enum PagerSource {
6pub enum PagerSource {
@@ -14,31 +17,104 @@ pub enum PagerSource {
14 Default,
17 Default,
15}
18}
16
19
20+/// We know about some pagers, for example 'less'. This is a list of all pagers we know about
21+#[derive(Debug, PartialEq)]
22+pub enum PagerKind {
23+ /// The pager is ourselves
24+ Bat,
25+
26+ /// less
27+ Less,
28+
29+ /// more
30+ More,
31+
32+ /// most
33+ Most,
34+
35+ /// A pager we don't know about
36+ Unknown,
37+}
38+
39+impl PagerKind {
40+ fn from_bin(bin: &str) -> PagerKind {
41+ use std::ffi::OsStr;
42+ use std::path::Path;
43+
44+ let stem = Path::new(bin)
45+ .file_stem()
46+ .unwrap_or_else(|| OsStr::new("unknown"));
47+
48+ if stem == OsStr::new("bat") {
49+ PagerKind::Bat
50+ } else if stem == OsStr::new("less") {
51+ PagerKind::Less
52+ } else if stem == OsStr::new("more") {
53+ PagerKind::More
54+ } else if stem == OsStr::new("most") {
55+ PagerKind::Most
56+ } else {
57+ PagerKind::Unknown
58+ }
59+ }
60+}
61+
17/// A pager such as 'less', and from where we got it.
62/// A pager such as 'less', and from where we got it.
63+#[derive(Debug)]
18pub struct Pager {
64pub struct Pager {
65+ // The pager binary
66+ pub bin: String,
67+
68+ // The pager binary arguments (that we might tweak)
19− pub pager: String,
69+ pub args: Vec<String>,
70+
71+ // What pager this is
72+ pub kind: PagerKind,
73+
74+ // From where this pager comes
20 pub source: PagerSource,
75 pub source: PagerSource,
21}
76}
22
77
23impl Pager {
78impl Pager {
24− fn new(pager: &str, source: PagerSource) -> Pager {
79+ fn new(bin: &str, args: &[String], kind: PagerKind, source: PagerSource) -> Pager {
25 Pager {
80 Pager {
26− pager: String::from(pager),
81+ bin: String::from(bin),
82+ args: args.to_vec(),
83+ kind,
27 source,
84 source,
28 }
85 }
29 }
86 }
30}
87}
31
88
32/// Returns what pager to use, after looking at both config and environment variables.
89/// Returns what pager to use, after looking at both config and environment variables.
33−pub fn get_pager(pager_from_config: Option<&str>) -> Pager {
90+pub fn get_pager(config_pager: Option<&str>) -> Result<Option<Pager>, ParseError> {
34− match (
35− pager_from_config,
36− std::env::var("BAT_PAGER"),
91+ let bat_pager = env::var("BAT_PAGER");
37− std::env::var("PAGER"),
92+ let pager = env::var("PAGER");
38− ) {
93+
94+ let (cmd, source) = match (config_pager, &bat_pager, &pager) {
39− (Some(config), _, _) => Pager::new(config, PagerSource::Config),
95+ (Some(config_pager), _, _) => (config_pager, PagerSource::Config),
40− (_, Ok(bat_pager), _) => Pager::new(&bat_pager, PagerSource::BatPagerEnvVar),
96+ (_, Ok(bat_pager), _) => (bat_pager.as_str(), PagerSource::BatPagerEnvVar),
41− (_, _, Ok(pager)) => Pager::new(&pager, PagerSource::PagerEnvVar),
97+ (_, _, Ok(pager)) => (pager.as_str(), PagerSource::PagerEnvVar),
42− _ => Pager::new("less", PagerSource::Default),
98+ _ => ("less", PagerSource::Default),
99+ };
100+
101+ let parts = shell_words::split(cmd)?;
102+ match parts.split_first() {
103+ Some((bin, args)) => {
104+ let kind = PagerKind::from_bin(bin);
105+
106+ // 'more' and 'most' does not supports colors; automatically use 'less' instead
107+ // if the problematic pager came from the generic PAGER env var
108+ let no_color_support = kind == PagerKind::More || kind == PagerKind::Most;
109+ let use_less_instead = no_color_support && source == PagerSource::PagerEnvVar;
110+
111+ Ok(Some(if use_less_instead {
112+ let no_args = vec![];
113+ Pager::new("less", &no_args, PagerKind::Less, PagerSource::PagerEnvVar)
114+ } else {
115+ Pager::new(bin, args, kind, source)
116+ }))
117+ }
118+ None => Ok(None),
43 }
119 }
44}
120}