on 747b154 help sign in
bat/src/output.rs
158 lines 5.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;
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 crate::pager::{self, PagerKind, PagerSource};
52 use std::process::{Command, Stdio};
54 let pager_opt =
55 pager::get_pager(pager_from_config).map_err(|_| "Could not parse pager command.")?;
57 let pager = match pager_opt {
58 Some(pager) => pager,
59 None => return Ok(OutputType::stdout()),
60 };
62 if pager.kind == PagerKind::Bat {
63 return Err(Error::InvalidPagerValueBat);
64 }
66 let resolved_path = match grep_cli::resolve_binary(&pager.bin) {
67 Ok(path) => path,
68 Err(_) => {
69 return Ok(OutputType::stdout());
70 }
71 };
73 let mut p = Command::new(resolved_path);
74 let args = pager.args;
76 if pager.kind == PagerKind::Less {
77 // less needs to be called with the '-R' option in order to properly interpret the
78 // ANSI color sequences printed by bat. If someone has set PAGER="less -F", we
79 // therefore need to overwrite the arguments and add '-R'.
80 //
81 // We only do this for PAGER (as it is not specific to 'bat'), not for BAT_PAGER
82 // or bats '--pager' command line option.
83 let replace_arguments_to_less = pager.source == PagerSource::EnvVarPager;
85 if args.is_empty() || replace_arguments_to_less {
86 p.arg("--RAW-CONTROL-CHARS");
87 if single_screen_action == SingleScreenAction::Quit {
88 p.arg("--quit-if-one-screen");
89 }
91 if wrapping_mode == WrappingMode::NoWrapping(true) {
92 p.arg("--chop-long-lines");
93 }
95 // Passing '--no-init' fixes a bug with '--quit-if-one-screen' in older
96 // versions of 'less'. Unfortunately, it also breaks mouse-wheel support.
97 //
98 // See: http://www.greenwoodsoftware.com/less/news.530.html
99 //
100 // For newer versions (530 or 558 on Windows), we omit '--no-init' as it
101 // is not needed anymore.
102 match retrieve_less_version(&pager.bin) {
103 None => {
104 p.arg("--no-init");
105 }
106 Some(version) if (version < 530 || (cfg!(windows) && version < 558)) => {
107 p.arg("--no-init");
108 }
109 _ => {}
110 }
111 } else {
112 p.args(args);
113 }
114 p.env("LESSCHARSET", "UTF-8");
115 } else {
116 p.args(args);
117 };
119 Ok(p.stdin(Stdio::piped())
120 .spawn()
121 .map(OutputType::Pager)
122 .unwrap_or_else(|_| OutputType::stdout()))
123 }
125 pub(crate) fn stdout() -> Self {
126 OutputType::Stdout(io::stdout())
127 }
129 #[cfg(feature = "paging")]
130 pub(crate) fn is_pager(&self) -> bool {
131 matches!(self, OutputType::Pager(_))
132 }
134 #[cfg(not(feature = "paging"))]
135 pub(crate) fn is_pager(&self) -> bool {
136 false
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 .ok_or("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 }