on 5f6e310 help sign in
bat/src/output.rs
158 lines 5.8 kB history raw
1use std::io::{self, Write};
2#[cfg(feature = "paging")]
3use std::process::Child;
5#[cfg(feature = "paging")]
6use crate::config::PagingMode;
7use crate::errors::*;
8#[cfg(feature = "paging")]
9use crate::less::retrieve_less_version;
11#[derive(Debug)]
12pub enum OutputType {
13 #[cfg(feature = "paging")]
14 Pager(Child),
15 Stdout(io::Stdout),
18impl OutputType {
19 #[cfg(feature = "paging")]
20 pub fn from_mode(mode: PagingMode, pager: Option<&str>) -> Result<Self> {
21 use self::PagingMode::*;
22 Ok(match mode {
23 Always => OutputType::try_pager(false, pager)?,
24 QuitIfOneScreen => OutputType::try_pager(true, pager)?,
25 _ => OutputType::stdout(),
26 })
27 }
29 /// Try to launch the pager. Fall back to stdout in case of errors.
30 #[cfg(feature = "paging")]
31 fn try_pager(quit_if_one_screen: bool, pager_from_config: Option<&str>) -> Result<Self> {
32 use std::env;
33 use std::ffi::OsString;
34 use std::path::PathBuf;
35 use std::process::{Command, Stdio};
37 let mut replace_arguments_to_less = false;
39 let pager_from_env = match (env::var("BAT_PAGER"), env::var("PAGER")) {
40 (Ok(bat_pager), _) => Some(bat_pager),
41 (_, Ok(pager)) => {
42 // less needs to be called with the '-R' option in order to properly interpret the
43 // ANSI color sequences printed by bat. If someone has set PAGER="less -F", we
44 // therefore need to overwrite the arguments and add '-R'.
45 //
46 // We only do this for PAGER (as it is not specific to 'bat'), not for BAT_PAGER
47 // or bats '--pager' command line option.
48 replace_arguments_to_less = true;
49 Some(pager)
50 }
51 _ => None,
52 };
54 let pager_from_config = pager_from_config.map(|p| p.to_string());
56 if pager_from_config.is_some() {
57 replace_arguments_to_less = false;
58 }
60 let pager = pager_from_config
61 .or(pager_from_env)
62 .unwrap_or_else(|| String::from("less"));
64 let pagerflags =
65 shell_words::split(&pager).chain_err(|| "Could not parse pager command.")?;
67 match pagerflags.split_first() {
68 Some((pager_name, args)) => {
69 let mut pager_path = PathBuf::from(pager_name);
71 if pager_path.file_stem() == Some(&OsString::from("bat")) {
72 pager_path = PathBuf::from("less");
73 }
75 let is_less = pager_path.file_stem() == Some(&OsString::from("less"));
77 let mut process = if is_less {
78 let mut p = Command::new(&pager_path);
79 if args.is_empty() || replace_arguments_to_less {
80 p.arg("--RAW-CONTROL-CHARS");
81 if quit_if_one_screen {
82 p.arg("--quit-if-one-screen");
83 }
85 let less_version = retrieve_less_version();
87 // Passing '--no-init' fixes a bug with '--quit-if-one-screen' in older
88 // versions of 'less'. Unfortunately, it also breaks mouse-wheel support.
89 //
90 // See: http://www.greenwoodsoftware.com/less/news.530.html
91 match less_version {
92 None => {
93 p.arg("--no-init");
94 }
95 Some(version) if version < 530 => {
96 p.arg("--no-init");
97 }
98 _ => {}
99 }
101 // Passing '--mouse' allows mouse scrolling in terminals which do not
102 // support "fake scrolling", see https://github.com/sharkdp/bat/issues/904
103 // The '--mouse' argument is only supported in less 551 or higher. We do
104 // not enable this option everywhere because it prevents users from
105 // drag-selecting text without pressing shift.
106 if env::var_os("TMUX").is_some() {
107 match less_version {
108 Some(version) if version >= 551 => {
109 p.arg("--mouse");
110 }
111 _ => {}
112 }
113 }
114 } else {
115 p.args(args);
116 }
117 p.env("LESSCHARSET", "UTF-8");
118 p
119 } else {
120 let mut p = Command::new(&pager_path);
121 p.args(args);
122 p
123 };
125 Ok(process
126 .stdin(Stdio::piped())
127 .spawn()
128 .map(OutputType::Pager)
129 .unwrap_or_else(|_| OutputType::stdout()))
130 }
131 None => Ok(OutputType::stdout()),
132 }
133 }
135 pub(crate) fn stdout() -> Self {
136 OutputType::Stdout(io::stdout())
137 }
139 pub fn handle(&mut self) -> Result<&mut dyn Write> {
140 Ok(match *self {
141 #[cfg(feature = "paging")]
142 OutputType::Pager(ref mut command) => command
143 .stdin
144 .as_mut()
145 .chain_err(|| "Could not open stdin for pager")?,
146 OutputType::Stdout(ref mut handle) => handle,
147 })
148 }
151#[cfg(feature = "paging")]
152impl Drop for OutputType {
153 fn drop(&mut self) {
154 if let OutputType::Pager(ref mut command) = *self {
155 let _ = command.wait();
156 }
157 }