| 1 | // https://github.com/sharkdp/bat a1b9334a44a2c652f52dddaa83dbacba57372468 |
| 2 | // src/output.rs |
| 3 | // See src/utils/bat/LICENSE |
| 4 | use std::ffi::OsString; |
| 5 | use std::io::{self, Write}; |
| 6 | use std::path::PathBuf; |
| 7 | use std::process::{Child, Command, Stdio}; |
| 8 | |
| 9 | use super::less::retrieve_less_version; |
| 10 | |
| 11 | use crate::config; |
| 12 | use crate::env::DeltaEnv; |
| 13 | use crate::fatal; |
| 14 | use crate::features::navigate; |
| 15 | |
| 16 | #[derive(Debug, Default)] |
| 17 | pub struct PagerCfg { |
| 18 | pub navigate: bool, |
| 19 | pub show_themes: bool, |
| 20 | pub navigate_regex: Option<String>, |
| 21 | } |
| 22 | |
| 23 | impl From<&config::Config> for PagerCfg { |
| 24 | fn from(cfg: &config::Config) -> Self { |
| 25 | PagerCfg { |
| 26 | navigate: cfg.navigate, |
| 27 | show_themes: cfg.show_themes, |
| 28 | navigate_regex: cfg.navigate_regex.clone(), |
| 29 | } |
| 30 | } |
| 31 | } |
| 32 | impl From<config::Config> for PagerCfg { |
| 33 | fn from(cfg: config::Config) -> Self { |
| 34 | (&cfg).into() |
| 35 | } |
| 36 | } |
| 37 | |
| 38 | #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] |
| 39 | #[allow(dead_code)] |
| 40 | pub enum PagingMode { |
| 41 | Always, |
| 42 | QuitIfOneScreen, |
| 43 | #[default] |
| 44 | Never, |
| 45 | Capture, |
| 46 | } |
| 47 | const LESSUTFCHARDEF: &str = "LESSUTFCHARDEF"; |
| 48 | use crate::errors::*; |
| 49 | |
| 50 | pub enum OutputType { |
| 51 | Pager(Child), |
| 52 | Stdout(io::Stdout), |
| 53 | Capture, |
| 54 | } |
| 55 | |
| 56 | impl Drop for OutputType { |
| 57 | fn drop(&mut self) { |
| 58 | if let OutputType::Pager(ref mut command) = *self { |
| 59 | let _ = command.wait(); |
| 60 | } |
| 61 | } |
| 62 | } |
| 63 | |
| 64 | impl OutputType { |
| 65 | /// Create a pager and write all data into it. Waits until the pager exits. |
| 66 | /// The expectation is that the program will exit afterwards. |
| 67 | pub fn oneshot_write(data: String) -> io::Result<()> { |
| 68 | let mut output_type = OutputType::from_mode( |
| 69 | &DeltaEnv::init(), |
| 70 | PagingMode::QuitIfOneScreen, |
| 71 | None, |
| 72 | &PagerCfg::default(), |
| 73 | ) |
| 74 | .unwrap(); |
| 75 | let mut writer = output_type.handle().unwrap(); |
| 76 | write!(&mut writer, "{data}") |
| 77 | } |
| 78 | |
| 79 | pub fn from_mode( |
| 80 | env: &DeltaEnv, |
| 81 | mode: PagingMode, |
| 82 | pager: Option<String>, |
| 83 | config: &PagerCfg, |
| 84 | ) -> Result<Self> { |
| 85 | use self::PagingMode::*; |
| 86 | Ok(match mode { |
| 87 | Always => OutputType::try_pager(env, false, pager, config)?, |
| 88 | QuitIfOneScreen => OutputType::try_pager(env, true, pager, config)?, |
| 89 | Capture => OutputType::Capture, |
| 90 | _ => OutputType::stdout(), |
| 91 | }) |
| 92 | } |
| 93 | |
| 94 | /// Try to launch the pager. Fall back to stdout in case of errors. |
| 95 | fn try_pager( |
| 96 | env: &DeltaEnv, |
| 97 | quit_if_one_screen: bool, |
| 98 | pager_from_config: Option<String>, |
| 99 | config: &PagerCfg, |
| 100 | ) -> Result<Self> { |
| 101 | let mut replace_arguments_to_less = false; |
| 102 | |
| 103 | let pager_from_env = match env.pagers.clone() { |
| 104 | (Some(delta_pager), _) => Some(delta_pager), |
| 105 | (_, Some(pager)) => { |
| 106 | // less needs to be called with the '-R' option in order to properly interpret ANSI |
| 107 | // color sequences. If someone has set PAGER="less -F", we therefore need to |
| 108 | // overwrite the arguments and add '-R'. |
| 109 | // We only do this for PAGER, since it is used in other contexts. |
| 110 | replace_arguments_to_less = true; |
| 111 | Some(pager) |
| 112 | } |
| 113 | _ => None, |
| 114 | }; |
| 115 | |
| 116 | if pager_from_config.is_some() { |
| 117 | replace_arguments_to_less = false; |
| 118 | } |
| 119 | |
| 120 | let pager_cmd = shell_words::split( |
| 121 | &pager_from_config |
| 122 | .or(pager_from_env) |
| 123 | .unwrap_or_else(|| String::from("less")), |
| 124 | ) |
| 125 | .context("Could not parse pager command.")?; |
| 126 | |
| 127 | Ok(match pager_cmd.split_first() { |
| 128 | Some((pager_path, args)) => { |
| 129 | let pager_path = PathBuf::from(pager_path); |
| 130 | |
| 131 | let is_less = pager_path.file_stem() == Some(&OsString::from("less")); |
| 132 | |
| 133 | let process = if is_less { |
| 134 | _make_process_from_less_path( |
| 135 | pager_path, |
| 136 | args, |
| 137 | replace_arguments_to_less, |
| 138 | quit_if_one_screen, |
| 139 | config, |
| 140 | ) |
| 141 | } else { |
| 142 | _make_process_from_pager_path(pager_path, args) |
| 143 | }; |
| 144 | if let Some(mut process) = process { |
| 145 | process |
| 146 | .stdin(Stdio::piped()) |
| 147 | .spawn() |
| 148 | .map(OutputType::Pager) |
| 149 | .unwrap_or_else(|_| OutputType::stdout()) |
| 150 | } else { |
| 151 | OutputType::stdout() |
| 152 | } |
| 153 | } |
| 154 | None => OutputType::stdout(), |
| 155 | }) |
| 156 | } |
| 157 | |
| 158 | fn stdout() -> Self { |
| 159 | OutputType::Stdout(io::stdout()) |
| 160 | } |
| 161 | |
| 162 | pub fn handle(&mut self) -> Result<&mut dyn Write> { |
| 163 | Ok(match *self { |
| 164 | OutputType::Pager(ref mut command) => command |
| 165 | .stdin |
| 166 | .as_mut() |
| 167 | .context("Could not open stdin for pager")?, |
| 168 | OutputType::Stdout(ref mut handle) => handle, |
| 169 | OutputType::Capture => unreachable!("capture can not be set"), |
| 170 | }) |
| 171 | } |
| 172 | } |
| 173 | |
| 174 | fn _make_process_from_less_path( |
| 175 | less_path: PathBuf, |
| 176 | args: &[String], |
| 177 | replace_arguments_to_less: bool, |
| 178 | quit_if_one_screen: bool, |
| 179 | config: &PagerCfg, |
| 180 | ) -> Option<Command> { |
| 181 | if let Ok(less_path) = grep_cli::resolve_binary(less_path) { |
| 182 | let mut p = Command::new(less_path.clone()); |
| 183 | if args.is_empty() || replace_arguments_to_less { |
| 184 | p.args(vec!["--RAW-CONTROL-CHARS"]); |
| 185 | |
| 186 | // Passing '--no-init' fixes a bug with '--quit-if-one-screen' in older |
| 187 | // versions of 'less'. Unfortunately, it also breaks mouse-wheel support. |
| 188 | // |
| 189 | // See: http://www.greenwoodsoftware.com/less/news.530.html |
| 190 | // |
| 191 | // For newer versions (530 or 558 on Windows), we omit '--no-init' as it |
| 192 | // is not needed anymore. |
| 193 | match retrieve_less_version(less_path) { |
| 194 | None => { |
| 195 | p.arg("--no-init"); |
| 196 | } |
| 197 | Some(version) if (version < 530 || (cfg!(windows) && version < 558)) => { |
| 198 | p.arg("--no-init"); |
| 199 | } |
| 200 | _ => {} |
| 201 | } |
| 202 | |
| 203 | if quit_if_one_screen { |
| 204 | p.arg("--quit-if-one-screen"); |
| 205 | } |
| 206 | } else { |
| 207 | p.args(args); |
| 208 | } |
| 209 | |
| 210 | // less >= 633 (from May 2023) prints any characters from the Private Use Area of Unicode |
| 211 | // as control characters (e.g. <U+E012> instead of hoping that the terminal can render it). |
| 212 | // This means any Nerd Fonts will not be displayed properly. Previous versions of less just |
| 213 | // passed these characters through, and terminals usually fall back to a less obtrusive |
| 214 | // box. Use this new env var less introduced to restore the previous behavior. This sets all |
| 215 | // chars to single width (':p', see less manual). If a user provided env var is present, |
| 216 | // use do not override it. |
| 217 | // Also see delta issue 1616 and nerd-fonts/issues/1337 |
| 218 | if std::env::var(LESSUTFCHARDEF).is_err() { |
| 219 | p.env(LESSUTFCHARDEF, "E000-F8FF:p,F0000-FFFFD:p,100000-10FFFD:p"); |
| 220 | } |
| 221 | |
| 222 | p.env("LESSCHARSET", "UTF-8"); |
| 223 | p.env("LESSANSIENDCHARS", "mK"); |
| 224 | |
| 225 | if config.navigate { |
| 226 | if let Ok(hist_file) = navigate::copy_less_hist_file_and_append_navigate_regex(config) { |
| 227 | p.env("LESSHISTFILE", hist_file); |
| 228 | if config.show_themes { |
| 229 | p.arg("+n"); |
| 230 | } |
| 231 | } |
| 232 | } |
| 233 | Some(p) |
| 234 | } else { |
| 235 | None |
| 236 | } |
| 237 | } |
| 238 | |
| 239 | fn _make_process_from_pager_path(pager_path: PathBuf, args: &[String]) -> Option<Command> { |
| 240 | if pager_path.file_stem() == Some(&OsString::from("delta")) { |
| 241 | fatal( |
| 242 | "\ |
| 243 | It looks like you have set delta as the value of $PAGER. \ |
| 244 | This would result in a non-terminating recursion. \ |
| 245 | delta is not an appropriate value for $PAGER \ |
| 246 | (but it is an appropriate value for $GIT_PAGER).", |
| 247 | ); |
| 248 | } |
| 249 | if let Ok(pager_path) = grep_cli::resolve_binary(pager_path) { |
| 250 | let mut p = Command::new(pager_path); |
| 251 | p.args(args); |
| 252 | Some(p) |
| 253 | } else { |
| 254 | None |
| 255 | } |
| 256 | } |