on 3d07dec help sign in
bat/src/output.rs
184 lines 6.1 kB history raw
1use std::io::{self, Write};
2#[cfg(feature = "paging")]
3use std::process::Child;
5use crate::error::*;
6#[cfg(feature = "paging")]
7use crate::less::retrieve_less_version;
8#[cfg(feature = "paging")]
9use crate::paging::PagingMode;
10#[cfg(feature = "paging")]
11use crate::wrapping::WrappingMode;
13#[cfg(feature = "paging")]
14#[derive(Debug, PartialEq)]
15enum SingleScreenAction {
16 Quit,
17 Nothing,
20#[derive(Debug)]
21pub enum OutputType {
22 #[cfg(feature = "paging")]
23 Pager(Child),
24 Stdout(io::Stdout),
27impl OutputType {
28 #[cfg(feature = "paging")]
29 pub fn from_mode(
30 paging_mode: PagingMode,
31 wrapping_mode: WrappingMode,
32 pager: Option<&str>,
33 ) -> Result<Self> {
34 use self::PagingMode::*;
35 Ok(match paging_mode {
36 Always => OutputType::try_pager(SingleScreenAction::Nothing, wrapping_mode, pager)?,
37 QuitIfOneScreen => {
38 OutputType::try_pager(SingleScreenAction::Quit, wrapping_mode, pager)?
39 }
40 _ => OutputType::stdout(),
41 })
42 }
44 /// Try to launch the pager. Fall back to stdout in case of errors.
45 #[cfg(feature = "paging")]
46 fn try_pager(
47 single_screen_action: SingleScreenAction,
48 wrapping_mode: WrappingMode,
49 pager_from_config: Option<&str>,
50 ) -> Result<Self> {
51 use std::env;
52 use std::ffi::OsString;
53 use std::path::PathBuf;
54 use std::process::{Command, Stdio};
56 let mut replace_arguments_to_less = false;
58 let pager_from_env = match (env::var("BAT_PAGER"), env::var("PAGER")) {
59 (Ok(bat_pager), _) => Some(bat_pager),
60 (_, Ok(pager)) => {
61 // less needs to be called with the '-R' option in order to properly interpret the
62 // ANSI color sequences printed by bat. If someone has set PAGER="less -F", we
63 // therefore need to overwrite the arguments and add '-R'.
64 //
65 // We only do this for PAGER (as it is not specific to 'bat'), not for BAT_PAGER
66 // or bats '--pager' command line option.
67 replace_arguments_to_less = true;
68 Some(pager)
69 }
70 _ => None,
71 };
73 let pager_from_config = pager_from_config.map(|p| p.to_string());
75 if pager_from_config.is_some() {
76 replace_arguments_to_less = false;
77 }
79 let pager = pager_from_config
80 .or(pager_from_env)
81 .unwrap_or_else(|| String::from("less"));
83 let pagerflags =
84 shell_words::split(&pager).chain_err(|| "Could not parse pager command.")?;
86 match pagerflags.split_first() {
87 Some((pager_name, args)) => {
88 let pager_path = PathBuf::from(pager_name);
90 if pager_path.file_stem() == Some(&OsString::from("bat")) {
91 return Err(ErrorKind::InvalidPagerValueBat.into());
92 }
94 let is_less = pager_path.file_stem() == Some(&OsString::from("less"));
96 let mut process = if is_less {
97 let mut p = Command::new(&pager_path);
98 if args.is_empty() || replace_arguments_to_less {
99 p.arg("--RAW-CONTROL-CHARS");
100 if single_screen_action == SingleScreenAction::Quit {
101 p.arg("--quit-if-one-screen");
102 }
104 if wrapping_mode == WrappingMode::NoWrapping {
105 p.arg("--chop-long-lines");
106 }
108 // Passing '--no-init' fixes a bug with '--quit-if-one-screen' in older
109 // versions of 'less'. Unfortunately, it also breaks mouse-wheel support.
110 //
111 // See: http://www.greenwoodsoftware.com/less/news.530.html
112 //
113 // For newer versions (530 or 558 on Windows), we omit '--no-init' as it
114 // is not needed anymore.
115 match retrieve_less_version() {
116 None => {
117 p.arg("--no-init");
118 }
119 Some(version)
120 if (version < 530 || (cfg!(windows) && version < 558)) =>
121 {
122 p.arg("--no-init");
123 }
124 _ => {}
125 }
126 } else {
127 p.args(args);
128 }
129 p.env("LESSCHARSET", "UTF-8");
130 p
131 } else {
132 let mut p = Command::new(&pager_path);
133 p.args(args);
134 p
135 };
137 Ok(process
138 .stdin(Stdio::piped())
139 .spawn()
140 .map(OutputType::Pager)
141 .unwrap_or_else(|_| OutputType::stdout()))
142 }
143 None => Ok(OutputType::stdout()),
144 }
145 }
147 pub(crate) fn stdout() -> Self {
148 OutputType::Stdout(io::stdout())
149 }
151 #[cfg(feature = "paging")]
152 pub(crate) fn is_pager(&self) -> bool {
153 if let OutputType::Pager(_) = self {
154 true
155 } else {
156 false
157 }
158 }
160 #[cfg(not(feature = "paging"))]
161 pub(crate) fn is_pager(&self) -> bool {
162 false
163 }
165 pub fn handle(&mut self) -> Result<&mut dyn Write> {
166 Ok(match *self {
167 #[cfg(feature = "paging")]
168 OutputType::Pager(ref mut command) => command
169 .stdin
170 .as_mut()
171 .chain_err(|| "Could not open stdin for pager")?,
172 OutputType::Stdout(ref mut handle) => handle,
173 })
174 }
177#[cfg(feature = "paging")]
178impl Drop for OutputType {
179 fn drop(&mut self) {
180 if let OutputType::Pager(ref mut command) = *self {
181 let _ = command.wait();
182 }
183 }