on 47abb19 help sign in
bat/src/printer.rs
632 lines 23 kB history raw
1use std::borrow::Cow;
2use std::io::Write;
3use std::vec::Vec;
5use ansi_term::Colour::{Fixed, Green, Red, Yellow};
6use ansi_term::Style;
8use console::AnsiCodeIterator;
10use syntect::easy::HighlightLines;
11use syntect::highlighting::Color;
12use syntect::highlighting::Theme;
13use syntect::parsing::SyntaxSet;
15use content_inspector::ContentType;
17use encoding::all::{UTF_16BE, UTF_16LE};
18use encoding::{DecoderTrap, Encoding};
20use unicode_width::UnicodeWidthChar;
22use crate::assets::HighlightingAssets;
23use crate::config::Config;
24#[cfg(feature = "git")]
25use crate::decorations::LineChangesDecoration;
26use crate::decorations::{Decoration, GridBorderDecoration, LineNumberDecoration};
27#[cfg(feature = "git")]
28use crate::diff::{get_git_diff, LineChanges};
29use crate::errors::*;
30use crate::inputfile::{InputFile, InputFileReader};
31use crate::line_range::RangeCheckResult;
32use crate::preprocessor::{expand_tabs, replace_nonprintable};
33use crate::terminal::{as_terminal_escaped, to_ansi_color};
34use crate::wrap::OutputWrap;
36pub trait Printer {
37 fn print_header(&mut self, handle: &mut dyn Write, file: InputFile) -> Result<()>;
38 fn print_footer(&mut self, handle: &mut dyn Write) -> Result<()>;
40 fn print_snip(&mut self, handle: &mut dyn Write) -> Result<()>;
42 fn print_line(
43 &mut self,
44 out_of_range: bool,
45 handle: &mut dyn Write,
46 line_number: usize,
47 line_buffer: &[u8],
48 ) -> Result<()>;
51pub struct SimplePrinter;
53impl SimplePrinter {
54 pub fn new() -> Self {
55 SimplePrinter {}
56 }
59impl Printer for SimplePrinter {
60 fn print_header(&mut self, _handle: &mut dyn Write, _file: InputFile) -> Result<()> {
61 Ok(())
62 }
64 fn print_footer(&mut self, _handle: &mut dyn Write) -> Result<()> {
65 Ok(())
66 }
68 fn print_snip(&mut self, _handle: &mut dyn Write) -> Result<()> {
69 Ok(())
70 }
72 fn print_line(
73 &mut self,
74 out_of_range: bool,
75 handle: &mut dyn Write,
76 _line_number: usize,
77 line_buffer: &[u8],
78 ) -> Result<()> {
79 if !out_of_range {
80 handle.write_all(line_buffer)?;
81 }
82 Ok(())
83 }
86pub struct InteractivePrinter<'a> {
87 colors: Colors,
88 config: &'a Config<'a>,
89 decorations: Vec<Box<dyn Decoration>>,
90 panel_width: usize,
91 ansi_prefix_sgr: String,
92 content_type: Option<ContentType>,
93 #[cfg(feature = "git")]
94 pub line_changes: Option<LineChanges>,
95 highlighter: Option<HighlightLines<'a>>,
96 syntax_set: &'a SyntaxSet,
97 background_color_highlight: Option<Color>,
100impl<'a> InteractivePrinter<'a> {
101 pub fn new(
102 config: &'a Config,
103 assets: &'a HighlightingAssets,
104 file: InputFile,
105 reader: &mut InputFileReader,
106 ) -> Self {
107 let theme = assets.get_theme(&config.theme);
109 let background_color_highlight = theme.settings.line_highlight;
111 let colors = if config.colored_output {
112 Colors::colored(theme, config.true_color)
113 } else {
114 Colors::plain()
115 };
117 // Create decorations.
118 let mut decorations: Vec<Box<dyn Decoration>> = Vec::new();
120 if config.style_components.numbers() {
121 decorations.push(Box::new(LineNumberDecoration::new(&colors)));
122 }
124 #[cfg(feature = "git")]
125 {
126 if config.style_components.changes() {
127 decorations.push(Box::new(LineChangesDecoration::new(&colors)));
128 }
129 }
131 let mut panel_width: usize =
132 decorations.len() + decorations.iter().fold(0, |a, x| a + x.width());
134 // The grid border decoration isn't added until after the panel_width calculation, since the
135 // print_horizontal_line, print_header, and print_footer functions all assume the panel
136 // width is without the grid border.
137 if config.style_components.grid() && !decorations.is_empty() {
138 decorations.push(Box::new(GridBorderDecoration::new(&colors)));
139 }
141 // Disable the panel if the terminal is too small (i.e. can't fit 5 characters with the
142 // panel showing).
143 if config.term_width
144 < (decorations.len() + decorations.iter().fold(0, |a, x| a + x.width())) + 5
145 {
146 decorations.clear();
147 panel_width = 0;
148 }
150 #[cfg(feature = "git")]
151 let mut line_changes = None;
153 let highlighter = if reader
154 .content_type
155 .map_or(false, |c| c.is_binary() && !config.show_nonprintable)
156 {
157 None
158 } else {
159 // Get the Git modifications
160 #[cfg(feature = "git")]
161 {
162 if config.style_components.changes() {
163 if let InputFile::Ordinary(ofile) = file {
164 line_changes = get_git_diff(ofile.provided_path());
165 }
166 }
167 }
169 // Determine the type of syntax for highlighting
170 let syntax = assets.get_syntax(config.language, file, reader, &config.syntax_mapping);
171 Some(HighlightLines::new(syntax, theme))
172 };
174 InteractivePrinter {
175 panel_width,
176 colors,
177 config,
178 decorations,
179 content_type: reader.content_type,
180 ansi_prefix_sgr: String::new(),
181 #[cfg(feature = "git")]
182 line_changes,
183 highlighter,
184 syntax_set: &assets.syntax_set,
185 background_color_highlight,
186 }
187 }
189 fn print_horizontal_line(&mut self, handle: &mut dyn Write, grid_char: char) -> Result<()> {
190 if self.panel_width == 0 {
191 writeln!(
192 handle,
193 "{}",
194 self.colors.grid.paint("─".repeat(self.config.term_width))
195 )?;
196 } else {
197 let hline = "─".repeat(self.config.term_width - (self.panel_width + 1));
198 let hline = format!("{}{}{}", "─".repeat(self.panel_width), grid_char, hline);
199 writeln!(handle, "{}", self.colors.grid.paint(hline))?;
200 }
202 Ok(())
203 }
205 fn create_fake_panel(&self, text: &str) -> String {
206 if self.panel_width == 0 {
207 "".to_string()
208 } else {
209 let text_truncated: String = text.chars().take(self.panel_width - 1).collect();
210 let text_filled: String = format!(
211 "{}{}",
212 text_truncated,
213 " ".repeat(self.panel_width - 1 - text_truncated.len())
214 );
215 if self.config.style_components.grid() {
216 format!("{} │ ", text_filled)
217 } else {
218 format!("{}", text_filled)
219 }
220 }
221 }
223 fn preprocess(&self, text: &str, cursor: &mut usize) -> String {
224 if self.config.tab_width > 0 {
225 expand_tabs(text, self.config.tab_width, cursor)
226 } else {
227 text.to_string()
228 }
229 }
232impl<'a> Printer for InteractivePrinter<'a> {
233 fn print_header(&mut self, handle: &mut dyn Write, file: InputFile) -> Result<()> {
234 if !self.config.style_components.header() {
235 if Some(ContentType::BINARY) == self.content_type && !self.config.show_nonprintable {
236 let input = match file {
237 InputFile::Ordinary(ofile) => {
238 format!("file '{}'", &ofile.provided_path().to_string_lossy())
239 }
240 InputFile::StdIn(Some(name)) => format!(
241 "STDIN (with name '{}')",
242 name.to_string_lossy().into_owned()
243 ),
244 InputFile::StdIn(None) => "STDIN".to_owned(),
245 InputFile::ThemePreviewFile => "".to_owned(),
246 };
248 writeln!(
249 handle,
250 "{}: Binary content from {} will not be printed to the terminal \
251 (but will be present if the output of 'bat' is piped). You can use 'bat -A' \
252 to show the binary file contents.",
253 Yellow.paint("[bat warning]"),
254 input
255 )?;
256 } else {
257 if self.config.style_components.grid() {
258 self.print_horizontal_line(handle, '┬')?;
259 }
260 }
261 return Ok(());
262 }
264 if self.config.style_components.grid() {
265 self.print_horizontal_line(handle, '┬')?;
267 write!(
268 handle,
269 "{}{}",
270 " ".repeat(self.panel_width),
271 self.colors
272 .grid
273 .paint(if self.panel_width > 0 { "│ " } else { "" }),
274 )?;
275 } else {
276 write!(handle, "{}", " ".repeat(self.panel_width))?;
277 }
279 let (prefix, name) = match file {
280 InputFile::Ordinary(ofile) => (
281 "File: ",
282 Cow::from(ofile.provided_path().to_string_lossy().to_owned()),
283 ),
284 InputFile::StdIn(Some(name)) => {
285 ("File: ", Cow::from(name.to_string_lossy().to_owned()))
286 }
287 InputFile::StdIn(None) => ("File: ", Cow::from("STDIN".to_owned())),
288 InputFile::ThemePreviewFile => ("", Cow::from("")),
289 };
291 let mode = match self.content_type {
292 Some(ContentType::BINARY) => " <BINARY>",
293 Some(ContentType::UTF_16LE) => " <UTF-16LE>",
294 Some(ContentType::UTF_16BE) => " <UTF-16BE>",
295 None => " <EMPTY>",
296 _ => "",
297 };
299 writeln!(
300 handle,
301 "{}{}{}",
302 prefix,
303 self.colors.filename.paint(name),
304 mode
305 )?;
307 if self.config.style_components.grid() {
308 if self.content_type.map_or(false, |c| c.is_text()) || self.config.show_nonprintable {
309 self.print_horizontal_line(handle, '┼')?;
310 } else {
311 self.print_horizontal_line(handle, '┴')?;
312 }
313 }
315 Ok(())
316 }
318 fn print_footer(&mut self, handle: &mut dyn Write) -> Result<()> {
319 if self.config.style_components.grid()
320 && (self.content_type.map_or(false, |c| c.is_text()) || self.config.show_nonprintable)
321 {
322 self.print_horizontal_line(handle, '┴')
323 } else {
324 Ok(())
325 }
326 }
328 fn print_snip(&mut self, handle: &mut dyn Write) -> Result<()> {
329 let panel = self.create_fake_panel(" ...");
330 let panel_count = panel.chars().count();
332 let title = "8<";
333 let title_count = title.chars().count();
335 let snip_left = "─ ".repeat((self.config.term_width - panel_count - (title_count / 2)) / 4);
336 let snip_left_count = snip_left.chars().count(); // Can't use .len() with Unicode.
338 let snip_right =
339 " ─".repeat((self.config.term_width - panel_count - snip_left_count - title_count) / 2);
341 write!(
342 handle,
343 "{}\n",
344 self.colors
345 .grid
346 .paint(format!("{}{}{}{}", panel, snip_left, title, snip_right))
347 )?;
349 Ok(())
350 }
352 fn print_line(
353 &mut self,
354 out_of_range: bool,
355 handle: &mut dyn Write,
356 line_number: usize,
357 line_buffer: &[u8],
358 ) -> Result<()> {
359 let line = if self.config.show_nonprintable {
360 replace_nonprintable(&line_buffer, self.config.tab_width)
361 } else {
362 match self.content_type {
363 Some(ContentType::BINARY) | None => {
364 return Ok(());
365 }
366 Some(ContentType::UTF_16LE) => UTF_16LE
367 .decode(&line_buffer, DecoderTrap::Replace)
368 .map_err(|_| "Invalid UTF-16LE")?,
369 Some(ContentType::UTF_16BE) => UTF_16BE
370 .decode(&line_buffer, DecoderTrap::Replace)
371 .map_err(|_| "Invalid UTF-16BE")?,
372 _ => String::from_utf8_lossy(&line_buffer).to_string(),
373 }
374 };
376 let regions = {
377 let highlighter = match self.highlighter {
378 Some(ref mut highlighter) => highlighter,
379 _ => {
380 return Ok(());
381 }
382 };
383 highlighter.highlight(line.as_ref(), self.syntax_set)
384 };
386 if out_of_range {
387 return Ok(());
388 }
390 let mut cursor: usize = 0;
391 let mut cursor_max: usize = self.config.term_width;
392 let mut cursor_total: usize = 0;
393 let mut panel_wrap: Option<String> = None;
395 // Line highlighting
396 let highlight_this_line =
397 self.config.highlighted_lines.0.check(line_number) == RangeCheckResult::InRange;
399 let background_color = self
400 .background_color_highlight
401 .filter(|_| highlight_this_line);
403 // Line decorations.
404 if self.panel_width > 0 {
405 let decorations = self
406 .decorations
407 .iter()
408 .map(|ref d| d.generate(line_number, false, self))
409 .collect::<Vec<_>>();
411 for deco in decorations {
412 write!(handle, "{} ", deco.text)?;
413 cursor_max -= deco.width + 1;
414 }
415 }
417 // Line contents.
418 if self.config.output_wrap == OutputWrap::None {
419 let true_color = self.config.true_color;
420 let colored_output = self.config.colored_output;
421 let italics = self.config.use_italic_text;
423 for &(style, region) in regions.iter() {
424 let text = &*self.preprocess(region, &mut cursor_total);
425 let text_trimmed = text.trim_end_matches(|c| c == '\r' || c == '\n');
426 write!(
427 handle,
428 "{}",
429 as_terminal_escaped(
430 style,
431 text_trimmed,
432 true_color,
433 colored_output,
434 italics,
435 background_color
436 )
437 )?;
439 if text.len() != text_trimmed.len() {
440 if let Some(background_color) = background_color {
441 let mut ansi_style = Style::default();
442 ansi_style.background = Some(to_ansi_color(background_color, true_color));
443 let width = if cursor_total <= cursor_max {
444 cursor_max - cursor_total + 1
445 } else {
446 0
447 };
448 write!(handle, "{}", ansi_style.paint(" ".repeat(width)))?;
449 }
450 write!(handle, "{}", &text[text_trimmed.len()..])?;
451 }
452 }
454 if line.bytes().next_back() != Some(b'\n') {
455 writeln!(handle)?;
456 }
457 } else {
458 for &(style, region) in regions.iter() {
459 let ansi_iterator = AnsiCodeIterator::new(region);
460 let mut ansi_prefix: String = String::new();
461 for chunk in ansi_iterator {
462 match chunk {
463 // ANSI escape passthrough.
464 (text, true) => {
465 let is_ansi_csi = text.starts_with("\x1B[");
467 if is_ansi_csi && text.ends_with('m') {
468 // It's an ANSI SGR sequence.
469 // We should be mostly safe to just append these together.
470 ansi_prefix.push_str(text);
471 if text == "\x1B[0m" {
472 self.ansi_prefix_sgr = "\x1B[0m".to_owned();
473 } else {
474 self.ansi_prefix_sgr.push_str(text);
475 }
476 } else if is_ansi_csi {
477 // It's a regular CSI sequence.
478 // We should be mostly safe to just append these together.
479 ansi_prefix.push_str(text);
480 } else {
481 // It's probably a VT100 code.
482 // Passing it through is the safest bet.
483 write!(handle, "{}", text)?;
484 }
485 }
487 // Regular text.
488 (text, false) => {
489 let text = self.preprocess(
490 text.trim_end_matches(|c| c == '\r' || c == '\n'),
491 &mut cursor_total,
492 );
494 let mut max_width = cursor_max - cursor;
496 // line buffer (avoid calling write! for every character)
497 let mut line_buf = String::with_capacity(max_width * 4);
499 // Displayed width of line_buf
500 let mut current_width = 0;
502 for c in text.chars() {
503 // calculate the displayed width for next character
504 let cw = c.width().unwrap_or(0);
505 current_width += cw;
507 // if next character cannot be printed on this line,
508 // flush the buffer.
509 if current_width > max_width {
510 // Generate wrap padding if not already generated.
511 if panel_wrap.is_none() {
512 panel_wrap = if self.panel_width > 0 {
513 Some(format!(
514 "{} ",
515 self.decorations
516 .iter()
517 .map(|ref d| d
518 .generate(line_number, true, self)
519 .text)
520 .collect::<Vec<String>>()
521 .join(" ")
522 ))
523 } else {
524 Some("".to_string())
525 }
526 }
528 // It wraps.
529 write!(
530 handle,
531 "{}\n{}",
532 as_terminal_escaped(
533 style,
534 &*format!(
535 "{}{}{}",
536 self.ansi_prefix_sgr, ansi_prefix, line_buf
537 ),
538 self.config.true_color,
539 self.config.colored_output,
540 self.config.use_italic_text,
541 background_color
542 ),
543 panel_wrap.clone().unwrap()
544 )?;
546 cursor = 0;
547 max_width = cursor_max;
549 line_buf.clear();
550 current_width = cw;
551 }
553 line_buf.push(c);
554 }
556 // flush the buffer
557 cursor += current_width;
558 write!(
559 handle,
560 "{}",
561 as_terminal_escaped(
562 style,
563 &*format!(
564 "{}{}{}",
565 self.ansi_prefix_sgr, ansi_prefix, line_buf
566 ),
567 self.config.true_color,
568 self.config.colored_output,
569 self.config.use_italic_text,
570 background_color
571 )
572 )?;
574 // Clear the ANSI prefix buffer.
575 ansi_prefix.clear();
576 }
577 }
578 }
579 }
581 if let Some(background_color) = background_color {
582 let mut ansi_style = Style::default();
583 ansi_style.background =
584 Some(to_ansi_color(background_color, self.config.true_color));
586 write!(
587 handle,
588 "{}",
589 ansi_style.paint(" ".repeat(cursor_max - cursor))
590 )?;
591 }
592 writeln!(handle)?;
593 }
595 Ok(())
596 }
599const DEFAULT_GUTTER_COLOR: u8 = 238;
601#[derive(Debug, Default)]
602pub struct Colors {
603 pub grid: Style,
604 pub filename: Style,
605 pub git_added: Style,
606 pub git_removed: Style,
607 pub git_modified: Style,
608 pub line_number: Style,
611impl Colors {
612 fn plain() -> Self {
613 Colors::default()
614 }
616 fn colored(theme: &Theme, true_color: bool) -> Self {
617 let gutter_color = theme
618 .settings
619 .gutter_foreground
620 .map(|c| to_ansi_color(c, true_color))
621 .unwrap_or(Fixed(DEFAULT_GUTTER_COLOR));
623 Colors {
624 grid: gutter_color.normal(),
625 filename: Style::new().bold(),
626 git_added: Green.normal(),
627 git_removed: Red.normal(),
628 git_modified: Yellow.normal(),
629 line_number: gutter_color.normal(),
630 }
631 }