on master help sign in
Also replace 'more' from PAGER with 'less'

But first do some quite significant refactorings to keep the code clean and easy to understand.

commitbfa5342331cc17508ec2c528f2369514221ad3e4 authorMartin Nordholts <enselic@gmail.com> dateWed 30 Dec 2020, 13:25 (6 years ago) parent22bdc7c
3 files changed+144−87
CHANGELOG.md+1−1 src/output.rs+54−73 src/pager.rs+89−13
CHANGELOG.md+1−1
@@ -11,7 +11,7 @@
1111- Make ./tests/syntax-tests/regression_test.sh work on recent versions of macOS, see #1443 (@Enselic)
1212- VimL syntax highlighting fix, see #1450 (@esensar)
1313- 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)
1515
1616## Other
1717
src/output.rs+54−73
@@ -48,90 +48,71 @@ impl OutputType {
4848 wrapping_mode: WrappingMode,
4949 pager_from_config: Option<&str>,
5050 ) -> Result<Self> {
51− use std::ffi::OsString;
52− use std::path::PathBuf;
51+ use crate::pager::{self, PagerKind, PagerSource};
5352 use std::process::{Command, Stdio};
54− use crate::pager::*;
5553
56− let Pager { pager, source } = get_pager(pager_from_config);
54+ let pager_opt =
55+ pager::get_pager(pager_from_config).chain_err(|| "Could not parse pager command.")?;
5756
58− let pagerflags =
59− shell_words::split(&pager).chain_err(|| "Could not parse pager command.")?;
57+ let pager = match pager_opt {
58+ Some(pager) => pager,
59+ None => return Ok(OutputType::stdout()),
60+ };
6061
61− match pagerflags.split_first() {
62− Some((pager_name, pager_args)) => {
63− let mut pager_path = PathBuf::from(pager_name);
64− let mut args = pager_args;
65− let empty_args = vec![];
62+ if pager.kind == PagerKind::Bat {
63+ return Err(ErrorKind::InvalidPagerValueBat.into());
64+ }
6665
67− if pager_path.file_stem() == Some(&OsString::from("bat")) {
68− return Err(ErrorKind::InvalidPagerValueBat.into());
66+ let mut p = Command::new(pager.bin);
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");
6982 }
7083
71− if pager_path.file_stem() == Some(&OsString::from("most")) && source == PagerSource::PagerEnvVar {
72− pager_path = PathBuf::from("less");
73− args = &empty_args;
84+ if wrapping_mode == WrappingMode::NoWrapping {
85+ p.arg("--chop-long-lines");
7486 }
7587
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
99− // versions of 'less'. Unfortunately, it also breaks mouse-wheel support.
100− //
101− // See: http://www.greenwoodsoftware.com/less/news.530.html
102− //
103− // For newer versions (530 or 558 on Windows), we omit '--no-init' as it
104− // is not needed anymore.
105− match retrieve_less_version() {
106− None => {
107− p.arg("--no-init");
108− }
109− Some(version)
110− if (version < 530 || (cfg!(windows) && version < 558)) =>
111− {
112− p.arg("--no-init");
113− }
114− _ => {}
115− }
116− } else {
117− p.args(args);
88+ // Passing '--no-init' fixes a bug with '--quit-if-one-screen' in older
89+ // versions of 'less'. Unfortunately, it also breaks mouse-wheel support.
90+ //
91+ // See: http://www.greenwoodsoftware.com/less/news.530.html
92+ //
93+ // For newer versions (530 or 558 on Windows), we omit '--no-init' as it
94+ // is not needed anymore.
95+ match retrieve_less_version() {
96+ None => {
97+ p.arg("--no-init");
98+ }
99+ Some(version) if (version < 530 || (cfg!(windows) && version < 558)) => {
100+ p.arg("--no-init");
118101 }
119− p.env("LESSCHARSET", "UTF-8");
120− p
121− } else {
122− let mut p = Command::new(&pager_path);
123− 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()))
102+ _ => {}
103+ }
104+ } else {
105+ p.args(args);
132106 }
133− None => Ok(OutputType::stdout()),
134− }
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)
115+ .unwrap_or_else(|_| OutputType::stdout()))
135116 }
136117
137118 pub(crate) fn stdout() -> Self {
src/pager.rs+89−13
@@ -1,3 +1,6 @@
1+use shell_words::ParseError;
2+use std::env;
3+
14/// If we use a pager, this enum tells us from where we were told to use it.
25#[derive(Debug, PartialEq)]
36pub enum PagerSource {
@@ -14,31 +17,104 @@ pub enum PagerSource {
1417 Default,
1518}
1619
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+
1762/// A pager such as 'less', and from where we got it.
63+#[derive(Debug)]
1864pub struct Pager {
19− pub pager: String,
65+ // The pager binary
66+ pub bin: String,
67+
68+ // The pager binary arguments (that we might tweak)
69+ pub args: Vec<String>,
70+
71+ // What pager this is
72+ pub kind: PagerKind,
73+
74+ // From where this pager comes
2075 pub source: PagerSource,
2176}
2277
2378impl Pager {
24− fn new(pager: &str, source: PagerSource) -> Pager {
79+ fn new(bin: &str, args: &[String], kind: PagerKind, source: PagerSource) -> Pager {
2580 Pager {
26− pager: String::from(pager),
81+ bin: String::from(bin),
82+ args: args.to_vec(),
83+ kind,
2784 source,
2885 }
2986 }
3087}
3188
3289/// Returns what pager to use, after looking at both config and environment variables.
33−pub fn get_pager(pager_from_config: Option<&str>) -> Pager {
34− match (
35− pager_from_config,
36− std::env::var("BAT_PAGER"),
37− std::env::var("PAGER"),
38− ) {
39− (Some(config), _, _) => Pager::new(config, PagerSource::Config),
40− (_, Ok(bat_pager), _) => Pager::new(&bat_pager, PagerSource::BatPagerEnvVar),
41− (_, _, Ok(pager)) => Pager::new(&pager, PagerSource::PagerEnvVar),
42− _ => Pager::new("less", PagerSource::Default),
90+pub fn get_pager(config_pager: Option<&str>) -> Result<Option<Pager>, ParseError> {
91+ let bat_pager = env::var("BAT_PAGER");
92+ let pager = env::var("PAGER");
93+
94+ let (cmd, source) = match (config_pager, &bat_pager, &pager) {
95+ (Some(config_pager), _, _) => (config_pager, PagerSource::Config),
96+ (_, Ok(bat_pager), _) => (bat_pager.as_str(), PagerSource::BatPagerEnvVar),
97+ (_, _, Ok(pager)) => (pager.as_str(), PagerSource::PagerEnvVar),
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),
43119 }
44120}