on 1b2066c help sign in
bat/src/printer.rs
527 lines 18 kB history raw
1use std::io::Write;
2use std::vec::Vec;
4use ansi_term::Colour::{Fixed, Green, Red, Yellow};
5use ansi_term::Style;
7use console::AnsiCodeIterator;
9use syntect::easy::HighlightLines;
10use syntect::highlighting::Color;
11use syntect::highlighting::Theme;
12use syntect::parsing::SyntaxSet;
14use content_inspector::ContentType;
16use encoding::all::{UTF_16BE, UTF_16LE};
17use encoding::{DecoderTrap, Encoding};
19use crate::app::Config;
20use crate::assets::HighlightingAssets;
21use crate::decorations::{
22 Decoration, GridBorderDecoration, LineChangesDecoration, LineNumberDecoration,
23};
24use crate::diff::get_git_diff;
25use crate::diff::LineChanges;
26use crate::errors::*;
27use crate::inputfile::{InputFile, InputFileReader};
28use crate::preprocessor::{expand_tabs, replace_nonprintable};
29use crate::style::OutputWrap;
30use crate::terminal::{as_terminal_escaped, to_ansi_color};
32pub trait Printer {
33 fn print_header(&mut self, handle: &mut Write, file: InputFile) -> Result<()>;
34 fn print_footer(&mut self, handle: &mut Write) -> Result<()>;
35 fn print_line(
36 &mut self,
37 out_of_range: bool,
38 handle: &mut Write,
39 line_number: usize,
40 line_buffer: &[u8],
41 ) -> Result<()>;
44pub struct SimplePrinter;
46impl SimplePrinter {
47 pub fn new() -> Self {
48 SimplePrinter {}
49 }
52impl Printer for SimplePrinter {
53 fn print_header(&mut self, _handle: &mut Write, _file: InputFile) -> Result<()> {
54 Ok(())
55 }
57 fn print_footer(&mut self, _handle: &mut Write) -> Result<()> {
58 Ok(())
59 }
61 fn print_line(
62 &mut self,
63 out_of_range: bool,
64 handle: &mut Write,
65 _line_number: usize,
66 line_buffer: &[u8],
67 ) -> Result<()> {
68 if !out_of_range {
69 handle.write_all(line_buffer)?;
70 }
71 Ok(())
72 }
75pub struct InteractivePrinter<'a> {
76 colors: Colors,
77 config: &'a Config<'a>,
78 decorations: Vec<Box<dyn Decoration>>,
79 panel_width: usize,
80 ansi_prefix_sgr: String,
81 content_type: ContentType,
82 pub line_changes: Option<LineChanges>,
83 highlighter: Option<HighlightLines<'a>>,
84 syntax_set: &'a SyntaxSet,
85 background_color_highlight: Option<Color>,
88impl<'a> InteractivePrinter<'a> {
89 pub fn new(
90 config: &'a Config,
91 assets: &'a HighlightingAssets,
92 file: InputFile,
93 reader: &mut InputFileReader,
94 ) -> Self {
95 let theme = assets.get_theme(&config.theme);
97 let background_color_highlight = theme.settings.line_highlight;
99 let colors = if config.colored_output {
100 Colors::colored(theme, config.true_color)
101 } else {
102 Colors::plain()
103 };
105 // Create decorations.
106 let mut decorations: Vec<Box<dyn Decoration>> = Vec::new();
108 if config.output_components.numbers() {
109 decorations.push(Box::new(LineNumberDecoration::new(&colors)));
110 }
112 if config.output_components.changes() {
113 decorations.push(Box::new(LineChangesDecoration::new(&colors)));
114 }
116 let mut panel_width: usize =
117 decorations.len() + decorations.iter().fold(0, |a, x| a + x.width());
119 // The grid border decoration isn't added until after the panel_width calculation, since the
120 // print_horizontal_line, print_header, and print_footer functions all assume the panel
121 // width is without the grid border.
122 if config.output_components.grid() && !decorations.is_empty() {
123 decorations.push(Box::new(GridBorderDecoration::new(&colors)));
124 }
126 // Disable the panel if the terminal is too small (i.e. can't fit 5 characters with the
127 // panel showing).
128 if config.term_width
129 < (decorations.len() + decorations.iter().fold(0, |a, x| a + x.width())) + 5
130 {
131 decorations.clear();
132 panel_width = 0;
133 }
135 let mut line_changes = None;
137 let highlighter = if reader.content_type.is_binary() {
138 None
139 } else {
140 // Get the Git modifications
141 line_changes = if config.output_components.changes() {
142 match file {
143 InputFile::Ordinary(filename) => get_git_diff(filename),
144 _ => None,
145 }
146 } else {
147 None
148 };
150 // Determine the type of syntax for highlighting
151 let syntax = assets.get_syntax(config.language, file, reader, &config.syntax_mapping);
152 Some(HighlightLines::new(syntax, theme))
153 };
155 InteractivePrinter {
156 panel_width,
157 colors,
158 config,
159 decorations,
160 content_type: reader.content_type,
161 ansi_prefix_sgr: String::new(),
162 line_changes,
163 highlighter,
164 syntax_set: &assets.syntax_set,
165 background_color_highlight,
166 }
167 }
169 fn print_horizontal_line(&mut self, handle: &mut Write, grid_char: char) -> Result<()> {
170 if self.panel_width == 0 {
171 writeln!(
172 handle,
173 "{}",
174 self.colors.grid.paint("─".repeat(self.config.term_width))
175 )?;
176 } else {
177 let hline = "─".repeat(self.config.term_width - (self.panel_width + 1));
178 let hline = format!("{}{}{}", "─".repeat(self.panel_width), grid_char, hline);
179 writeln!(handle, "{}", self.colors.grid.paint(hline))?;
180 }
182 Ok(())
183 }
185 fn preprocess(&self, text: &str, cursor: &mut usize) -> String {
186 if self.config.tab_width > 0 {
187 expand_tabs(text, self.config.tab_width, cursor)
188 } else {
189 text.to_string()
190 }
191 }
194impl<'a> Printer for InteractivePrinter<'a> {
195 fn print_header(&mut self, handle: &mut Write, file: InputFile) -> Result<()> {
196 if !self.config.output_components.header() {
197 return Ok(());
198 }
200 if self.config.output_components.grid() {
201 self.print_horizontal_line(handle, '┬')?;
203 write!(
204 handle,
205 "{}{}",
206 " ".repeat(self.panel_width),
207 self.colors
208 .grid
209 .paint(if self.panel_width > 0 { "│ " } else { "" }),
210 )?;
211 } else {
212 write!(handle, "{}", " ".repeat(self.panel_width))?;
213 }
215 let (prefix, name) = match file {
216 InputFile::Ordinary(filename) => ("File: ", filename),
217 _ => ("", "STDIN"),
218 };
220 let mode = match self.content_type {
221 ContentType::BINARY => " <BINARY>",
222 ContentType::UTF_16LE => " <UTF-16LE>",
223 ContentType::UTF_16BE => " <UTF-16BE>",
224 _ => "",
225 };
227 writeln!(
228 handle,
229 "{}{}{}",
230 prefix,
231 self.colors.filename.paint(name),
232 mode
233 )?;
235 if self.config.output_components.grid() {
236 if self.content_type.is_text() {
237 self.print_horizontal_line(handle, '┼')?;
238 } else {
239 self.print_horizontal_line(handle, '┴')?;
240 }
241 }
243 Ok(())
244 }
246 fn print_footer(&mut self, handle: &mut Write) -> Result<()> {
247 if self.config.output_components.grid() && self.content_type.is_text() {
248 self.print_horizontal_line(handle, '┴')
249 } else {
250 Ok(())
251 }
252 }
254 fn print_line(
255 &mut self,
256 out_of_range: bool,
257 handle: &mut Write,
258 line_number: usize,
259 line_buffer: &[u8],
260 ) -> Result<()> {
261 let mut line = match self.content_type {
262 ContentType::BINARY => {
263 return Ok(());
264 }
265 ContentType::UTF_16LE => UTF_16LE
266 .decode(&line_buffer, DecoderTrap::Replace)
267 .map_err(|_| "Invalid UTF-16LE")?,
268 ContentType::UTF_16BE => UTF_16BE
269 .decode(&line_buffer, DecoderTrap::Replace)
270 .map_err(|_| "Invalid UTF-16BE")?,
271 _ => String::from_utf8_lossy(&line_buffer).to_string(),
272 };
274 if self.config.show_nonprintable {
275 line = replace_nonprintable(&line, self.config.tab_width);
276 }
278 let regions = {
279 let highlighter = match self.highlighter {
280 Some(ref mut highlighter) => highlighter,
281 _ => {
282 return Ok(());
283 }
284 };
285 highlighter.highlight(line.as_ref(), self.syntax_set)
286 };
288 if out_of_range {
289 return Ok(());
290 }
292 let mut cursor: usize = 0;
293 let mut cursor_max: usize = self.config.term_width;
294 let mut cursor_total: usize = 0;
295 let mut panel_wrap: Option<String> = None;
297 // Line highlighting
298 let highlight_this_line = self
299 .config
300 .highlight_lines
301 .iter()
302 .any(|&l| l == line_number);
304 let background_color = self
305 .background_color_highlight
306 .filter(|_| highlight_this_line);
308 // Line decorations.
309 if self.panel_width > 0 {
310 let decorations = self
311 .decorations
312 .iter()
313 .map(|ref d| d.generate(line_number, false, self))
314 .collect::<Vec<_>>();
316 for deco in decorations {
317 write!(handle, "{} ", deco.text)?;
318 cursor_max -= deco.width + 1;
319 }
320 }
322 // Line contents.
323 if self.config.output_wrap == OutputWrap::None {
324 let true_color = self.config.true_color;
325 let colored_output = self.config.colored_output;
326 let italics = self.config.use_italic_text;
328 for &(style, region) in regions.iter() {
329 let text = &*self.preprocess(region, &mut cursor_total);
330 let text_trimmed = text.trim_end_matches(|c| c == '\r' || c == '\n');
331 write!(
332 handle,
333 "{}",
334 as_terminal_escaped(
335 style,
336 text_trimmed,
337 true_color,
338 colored_output,
339 italics,
340 background_color
341 )
342 )?;
344 if text.len() != text_trimmed.len() {
345 if let Some(background_color) = background_color {
346 let mut ansi_style = Style::default();
347 ansi_style.background = Some(to_ansi_color(background_color, true_color));
348 let width = if cursor_total <= cursor_max {
349 cursor_max - cursor_total + 1
350 } else {
351 0
352 };
353 write!(handle, "{}", ansi_style.paint(" ".repeat(width)))?;
354 }
355 write!(handle, "{}", &text[text_trimmed.len()..])?;
356 }
357 }
359 if line.bytes().next_back() != Some(b'\n') {
360 writeln!(handle)?;
361 }
362 } else {
363 for &(style, region) in regions.iter() {
364 let ansi_iterator = AnsiCodeIterator::new(region);
365 let mut ansi_prefix: String = String::new();
366 for chunk in ansi_iterator {
367 match chunk {
368 // ANSI escape passthrough.
369 (text, true) => {
370 let is_ansi_csi = text.starts_with("\x1B[");
372 if is_ansi_csi && text.ends_with('m') {
373 // It's an ANSI SGR sequence.
374 // We should be mostly safe to just append these together.
375 ansi_prefix.push_str(text);
376 if text == "\x1B[0m" {
377 self.ansi_prefix_sgr = "\x1B[0m".to_owned();
378 } else {
379 self.ansi_prefix_sgr.push_str(text);
380 }
381 } else if is_ansi_csi {
382 // It's a regular CSI sequence.
383 // We should be mostly safe to just append these together.
384 ansi_prefix.push_str(text);
385 } else {
386 // It's probably a VT100 code.
387 // Passing it through is the safest bet.
388 write!(handle, "{}", text)?;
389 }
390 }
392 // Regular text.
393 (text, false) => {
394 let text = self.preprocess(
395 text.trim_end_matches(|c| c == '\r' || c == '\n'),
396 &mut cursor_total,
397 );
399 let mut chars = text.chars();
400 let mut remaining = text.chars().count();
402 while remaining > 0 {
403 let available = cursor_max - cursor;
405 // It fits.
406 if remaining <= available {
407 let text = chars.by_ref().take(remaining).collect::<String>();
408 cursor += remaining;
410 write!(
411 handle,
412 "{}",
413 as_terminal_escaped(
414 style,
415 &*format!(
416 "{}{}{}",
417 self.ansi_prefix_sgr, ansi_prefix, text
418 ),
419 self.config.true_color,
420 self.config.colored_output,
421 self.config.use_italic_text,
422 background_color
423 )
424 )?;
425 break;
426 }
428 // Generate wrap padding if not already generated.
429 if panel_wrap.is_none() {
430 panel_wrap = if self.panel_width > 0 {
431 Some(format!(
432 "{} ",
433 self.decorations
434 .iter()
435 .map(|ref d| d
436 .generate(line_number, true, self)
437 .text)
438 .collect::<Vec<String>>()
439 .join(" ")
440 ))
441 } else {
442 Some("".to_string())
443 }
444 }
446 // It wraps.
447 let text = chars.by_ref().take(available).collect::<String>();
448 cursor = 0;
449 remaining -= available;
451 write!(
452 handle,
453 "{}\n{}",
454 as_terminal_escaped(
455 style,
456 &*format!(
457 "{}{}{}",
458 self.ansi_prefix_sgr, ansi_prefix, text
459 ),
460 self.config.true_color,
461 self.config.colored_output,
462 self.config.use_italic_text,
463 background_color
464 ),
465 panel_wrap.clone().unwrap()
466 )?;
467 }
469 // Clear the ANSI prefix buffer.
470 ansi_prefix.clear();
471 }
472 }
473 }
474 }
476 if let Some(background_color) = background_color {
477 let mut ansi_style = Style::default();
478 ansi_style.background =
479 Some(to_ansi_color(background_color, self.config.true_color));
481 write!(
482 handle,
483 "{}",
484 ansi_style.paint(" ".repeat(cursor_max - cursor))
485 )?;
486 }
487 writeln!(handle)?;
488 }
490 Ok(())
491 }
494const DEFAULT_GUTTER_COLOR: u8 = 238;
496#[derive(Default)]
497pub struct Colors {
498 pub grid: Style,
499 pub filename: Style,
500 pub git_added: Style,
501 pub git_removed: Style,
502 pub git_modified: Style,
503 pub line_number: Style,
506impl Colors {
507 fn plain() -> Self {
508 Colors::default()
509 }
511 fn colored(theme: &Theme, true_color: bool) -> Self {
512 let gutter_color = theme
513 .settings
514 .gutter_foreground
515 .map(|c| to_ansi_color(c, true_color))
516 .unwrap_or(Fixed(DEFAULT_GUTTER_COLOR));
518 Colors {
519 grid: gutter_color.normal(),
520 filename: Style::new().bold(),
521 git_added: Green.normal(),
522 git_removed: Red.normal(),
523 git_modified: Yellow.normal(),
524 line_number: gutter_color.normal(),
525 }
526 }