on 5faf7ca help sign in
bat/src/output.rs
134 lines 4.6 kB history raw
1use std::env;
2use std::ffi::OsString;
3use std::io::{self, Write};
4use std::path::PathBuf;
5use std::process::{Child, Command, Stdio};
7use shell_words;
9use crate::errors::*;
10use crate::less::retrieve_less_version;
11use crate::PagingMode;
13#[derive(Debug)]
14pub enum OutputType {
15 Pager(Child),
16 Stdout(io::Stdout),
19impl OutputType {
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 fn try_pager(quit_if_one_screen: bool, pager_from_config: Option<&str>) -> Result<Self> {
31 let mut replace_arguments_to_less = false;
33 let pager_from_env = match (env::var("BAT_PAGER"), env::var("PAGER")) {
34 (Ok(bat_pager), _) => Some(bat_pager),
35 (_, Ok(pager)) => {
36 // less needs to be called with the '-R' option in order to properly interpret the
37 // ANSI color sequences printed by bat. If someone has set PAGER="less -F", we
38 // therefore need to overwrite the arguments and add '-R'.
39 //
40 // We only do this for PAGER (as it is not specific to 'bat'), not for BAT_PAGER
41 // or bats '--pager' command line option.
42 replace_arguments_to_less = true;
43 Some(pager)
44 }
45 _ => None,
46 };
48 let pager_from_config = pager_from_config.map(|p| p.to_string());
50 if pager_from_config.is_some() {
51 replace_arguments_to_less = false;
52 }
54 let pager = pager_from_config
55 .or(pager_from_env)
56 .unwrap_or_else(|| String::from("less"));
58 let pagerflags =
59 shell_words::split(&pager).chain_err(|| "Could not parse pager command.")?;
61 match pagerflags.split_first() {
62 Some((pager_name, args)) => {
63 let mut pager_path = PathBuf::from(pager_name);
65 if pager_path.file_stem() == Some(&OsString::from("bat")) {
66 pager_path = PathBuf::from("less");
67 }
69 let is_less = pager_path.file_stem() == Some(&OsString::from("less"));
71 let mut process = if is_less {
72 let mut p = Command::new(&pager_path);
73 if args.is_empty() || replace_arguments_to_less {
74 p.arg("--RAW-CONTROL-CHARS");
75 if quit_if_one_screen {
76 p.arg("--quit-if-one-screen");
77 }
79 // Passing '--no-init' fixes a bug with '--quit-if-one-screen' in older
80 // versions of 'less'. Unfortunately, it also breaks mouse-wheel support.
81 //
82 // See: http://www.greenwoodsoftware.com/less/news.530.html
83 match retrieve_less_version() {
84 None => {
85 p.arg("--no-init");
86 }
87 Some(version) if version < 530 => {
88 p.arg("--no-init");
89 }
90 _ => {}
91 }
92 } else {
93 p.args(args);
94 }
95 p.env("LESSCHARSET", "UTF-8");
96 p
97 } else {
98 let mut p = Command::new(&pager_path);
99 p.args(args);
100 p
101 };
103 Ok(process
104 .stdin(Stdio::piped())
105 .spawn()
106 .map(OutputType::Pager)
107 .unwrap_or_else(|_| OutputType::stdout()))
108 }
109 None => Ok(OutputType::stdout()),
110 }
111 }
113 fn stdout() -> Self {
114 OutputType::Stdout(io::stdout())
115 }
117 pub fn handle(&mut self) -> Result<&mut dyn Write> {
118 Ok(match *self {
119 OutputType::Pager(ref mut command) => command
120 .stdin
121 .as_mut()
122 .chain_err(|| "Could not open stdin for pager")?,
123 OutputType::Stdout(ref mut handle) => handle,
124 })
125 }
128impl Drop for OutputType {
129 fn drop(&mut self) {
130 if let OutputType::Pager(ref mut command) = *self {
131 let _ = command.wait();
132 }
133 }