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