on 96aedf6 help sign in
bat/src/printer.rs
639 lines 22 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(
38 &mut self,
39 handle: &mut dyn Write,
40 file: InputFile,
41 file_name: Option<&str>,
42 ) -> Result<()>;
43 fn print_footer(&mut self, handle: &mut dyn Write) -> Result<()>;
45 fn print_snip(&mut self, handle: &mut dyn Write) -> Result<()>;
47 fn print_line(
48 &mut self,
49 out_of_range: bool,
50 handle: &mut dyn Write,
51 line_number: usize,
52 line_buffer: &[u8],
53 ) -> Result<()>;
56pub struct SimplePrinter;
58impl SimplePrinter {
59 pub fn new() -> Self {
60 SimplePrinter {}
61 }
64impl Printer for SimplePrinter {
65 fn print_header(
66 &mut self,
67 _handle: &mut dyn Write,
68 _file: InputFile,
69 _file_name: Option<&str>,
70 ) -> Result<()> {
71 Ok(())
72 }
74 fn print_footer(&mut self, _handle: &mut dyn Write) -> Result<()> {
75 Ok(())
76 }
78 fn print_snip(&mut self, _handle: &mut dyn Write) -> Result<()> {
79 Ok(())
80 }
82 fn print_line(
83 &mut self,
84 out_of_range: bool,
85 handle: &mut dyn Write,
86 _line_number: usize,
87 line_buffer: &[u8],
88 ) -> Result<()> {
89 if !out_of_range {
90 handle.write_all(line_buffer)?;
91 }
92 Ok(())
93 }
96pub struct InteractivePrinter<'a> {
97 colors: Colors,
98 config: &'a Config<'a>,
99 decorations: Vec<Box<dyn Decoration>>,
100 panel_width: usize,
101 ansi_prefix_sgr: String,
102 content_type: Option<ContentType>,
103 #[cfg(feature = "git")]
104 pub line_changes: Option<LineChanges>,
105 highlighter: Option<HighlightLines<'a>>,
106 syntax_set: &'a SyntaxSet,
107 background_color_highlight: Option<Color>,
110impl<'a> InteractivePrinter<'a> {
111 pub fn new(
112 config: &'a Config,
113 assets: &'a HighlightingAssets,
114 file: InputFile,
115 reader: &mut InputFileReader,
116 ) -> Self {
117 let theme = assets.get_theme(&config.theme);
119 let background_color_highlight = theme.settings.line_highlight;
121 let colors = if config.colored_output {
122 Colors::colored(theme, config.true_color)
123 } else {
124 Colors::plain()
125 };
127 // Create decorations.
128 let mut decorations: Vec<Box<dyn Decoration>> = Vec::new();
130 if config.style_components.numbers() {
131 decorations.push(Box::new(LineNumberDecoration::new(&colors)));
132 }
134 #[cfg(feature = "git")]
135 {
136 if config.style_components.changes() {
137 decorations.push(Box::new(LineChangesDecoration::new(&colors)));
138 }
139 }
141 let mut panel_width: usize =
142 decorations.len() + decorations.iter().fold(0, |a, x| a + x.width());
144 // The grid border decoration isn't added until after the panel_width calculation, since the
145 // print_horizontal_line, print_header, and print_footer functions all assume the panel
146 // width is without the grid border.
147 if config.style_components.grid() && !decorations.is_empty() {
148 decorations.push(Box::new(GridBorderDecoration::new(&colors)));
149 }
151 // Disable the panel if the terminal is too small (i.e. can't fit 5 characters with the
152 // panel showing).
153 if config.term_width
154 < (decorations.len() + decorations.iter().fold(0, |a, x| a + x.width())) + 5
155 {
156 decorations.clear();
157 panel_width = 0;
158 }
160 #[cfg(feature = "git")]
161 let mut line_changes = None;
163 let highlighter = if reader
164 .content_type
165 .map_or(false, |c| c.is_binary() && !config.show_nonprintable)
166 {
167 None
168 } else {
169 // Get the Git modifications
170 #[cfg(feature = "git")]
171 {
172 if config.style_components.changes() {
173 if let InputFile::Ordinary(filename) = file {
174 line_changes = get_git_diff(filename);
175 }
176 }
177 }
179 // Determine the type of syntax for highlighting
180 let syntax = assets.get_syntax(config.language, file, reader, &config.syntax_mapping);
181 Some(HighlightLines::new(syntax, theme))
182 };
184 InteractivePrinter {
185 panel_width,
186 colors,
187 config,
188 decorations,
189 content_type: reader.content_type,
190 ansi_prefix_sgr: String::new(),
191 #[cfg(feature = "git")]
192 line_changes,
193 highlighter,
194 syntax_set: &assets.syntax_set,
195 background_color_highlight,
196 }
197 }
199 fn print_horizontal_line(&mut self, handle: &mut dyn Write, grid_char: char) -> Result<()> {
200 if self.panel_width == 0 {
201 writeln!(
202 handle,
203 "{}",
204 self.colors.grid.paint("─".repeat(self.config.term_width))
205 )?;
206 } else {
207 let hline = "─".repeat(self.config.term_width - (self.panel_width + 1));
208 let hline = format!("{}{}{}", "─".repeat(self.panel_width), grid_char, hline);
209 writeln!(handle, "{}", self.colors.grid.paint(hline))?;
210 }
212 Ok(())
213 }
215 fn create_fake_panel(&self, text: &str) -> String {
216 if self.panel_width == 0 {
217 "".to_string()
218 } else {
219 let text_truncated: String = text.chars().take(self.panel_width - 1).collect();
220 let text_filled: String = format!(
221 "{}{}",
222 text_truncated,
223 " ".repeat(self.panel_width - 1 - text_truncated.len())
224 );
225 if self.config.style_components.grid() {
226 format!("{} │ ", text_filled)
227 } else {
228 format!("{}", text_filled)
229 }
230 }
231 }
233 fn preprocess(&self, text: &str, cursor: &mut usize) -> String {
234 if self.config.tab_width > 0 {
235 expand_tabs(text, self.config.tab_width, cursor)
236 } else {
237 text.to_string()
238 }
239 }
242impl<'a> Printer for InteractivePrinter<'a> {
243 fn print_header(
244 &mut self,
245 handle: &mut dyn Write,
246 file: InputFile,
247 file_name: Option<&str>,
248 ) -> Result<()> {
249 if !self.config.style_components.header() {
250 if Some(ContentType::BINARY) == self.content_type && !self.config.show_nonprintable {
251 let input = match file {
252 InputFile::Ordinary(filename) => format!(
253 "file '{}'",
254 file_name.unwrap_or(&filename.to_string_lossy())
255 ),
256 _ => file_name.unwrap_or("STDIN").to_owned(),
257 };
259 writeln!(
260 handle,
261 "{}: Binary content from {} will not be printed to the terminal \
262 (but will be present if the output of 'bat' is piped). You can use 'bat -A' \
263 to show the binary file contents.",
264 Yellow.paint("[bat warning]"),
265 input
266 )?;
267 } else {
268 if self.config.style_components.grid() {
269 self.print_horizontal_line(handle, '┬')?;
270 }
271 }
272 return Ok(());
273 }
275 if self.config.style_components.grid() {
276 self.print_horizontal_line(handle, '┬')?;
278 write!(
279 handle,
280 "{}{}",
281 " ".repeat(self.panel_width),
282 self.colors
283 .grid
284 .paint(if self.panel_width > 0 { "│ " } else { "" }),
285 )?;
286 } else {
287 write!(handle, "{}", " ".repeat(self.panel_width))?;
288 }
290 let (prefix, name) = match file {
291 InputFile::Ordinary(filename) => (
292 "File: ",
293 Cow::from(file_name.unwrap_or(&filename.to_string_lossy()).to_owned()),
294 ),
295 _ => ("File: ", Cow::from(file_name.unwrap_or("STDIN").to_owned())),
296 };
298 let mode = match self.content_type {
299 Some(ContentType::BINARY) => " <BINARY>",
300 Some(ContentType::UTF_16LE) => " <UTF-16LE>",
301 Some(ContentType::UTF_16BE) => " <UTF-16BE>",
302 None => " <EMPTY>",
303 _ => "",
304 };
306 writeln!(
307 handle,
308 "{}{}{}",
309 prefix,
310 self.colors.filename.paint(name),
311 mode
312 )?;
314 if self.config.style_components.grid() {
315 if self.content_type.map_or(false, |c| c.is_text()) || self.config.show_nonprintable {
316 self.print_horizontal_line(handle, '┼')?;
317 } else {
318 self.print_horizontal_line(handle, '┴')?;
319 }
320 }
322 Ok(())
323 }
325 fn print_footer(&mut self, handle: &mut dyn Write) -> Result<()> {
326 if self.config.style_components.grid()
327 && (self.content_type.map_or(false, |c| c.is_text()) || self.config.show_nonprintable)
328 {
329 self.print_horizontal_line(handle, '┴')
330 } else {
331 Ok(())
332 }
333 }
335 fn print_snip(&mut self, handle: &mut dyn Write) -> Result<()> {
336 let panel = self.create_fake_panel(" ...");
337 let panel_count = panel.chars().count();
339 let title = "8<";
340 let title_count = title.chars().count();
342 let snip_left = "─ ".repeat((self.config.term_width - panel_count - (title_count / 2)) / 4);
343 let snip_left_count = snip_left.chars().count(); // Can't use .len() with Unicode.
345 let snip_right =
346 " ─".repeat((self.config.term_width - panel_count - snip_left_count - title_count) / 2);
348 write!(
349 handle,
350 "{}\n",
351 self.colors
352 .grid
353 .paint(format!("{}{}{}{}", panel, snip_left, title, snip_right))
354 )?;
356 Ok(())
357 }
359 fn print_line(
360 &mut self,
361 out_of_range: bool,
362 handle: &mut dyn Write,
363 line_number: usize,
364 line_buffer: &[u8],
365 ) -> Result<()> {
366 let line = if self.config.show_nonprintable {
367 replace_nonprintable(&line_buffer, self.config.tab_width)
368 } else {
369 match self.content_type {
370 Some(ContentType::BINARY) | None => {
371 return Ok(());
372 }
373 Some(ContentType::UTF_16LE) => UTF_16LE
374 .decode(&line_buffer, DecoderTrap::Replace)
375 .map_err(|_| "Invalid UTF-16LE")?,
376 Some(ContentType::UTF_16BE) => UTF_16BE
377 .decode(&line_buffer, DecoderTrap::Replace)
378 .map_err(|_| "Invalid UTF-16BE")?,
379 _ => String::from_utf8_lossy(&line_buffer).to_string(),
380 }
381 };
383 let regions = {
384 let highlighter = match self.highlighter {
385 Some(ref mut highlighter) => highlighter,
386 _ => {
387 return Ok(());
388 }
389 };
390 highlighter.highlight(line.as_ref(), self.syntax_set)
391 };
393 if out_of_range {
394 return Ok(());
395 }
397 let mut cursor: usize = 0;
398 let mut cursor_max: usize = self.config.term_width;
399 let mut cursor_total: usize = 0;
400 let mut panel_wrap: Option<String> = None;
402 // Line highlighting
403 let highlight_this_line =
404 self.config.highlighted_lines.0.check(line_number) == RangeCheckResult::InRange;
406 let background_color = self
407 .background_color_highlight
408 .filter(|_| highlight_this_line);
410 // Line decorations.
411 if self.panel_width > 0 {
412 let decorations = self
413 .decorations
414 .iter()
415 .map(|ref d| d.generate(line_number, false, self))
416 .collect::<Vec<_>>();
418 for deco in decorations {
419 write!(handle, "{} ", deco.text)?;
420 cursor_max -= deco.width + 1;
421 }
422 }
424 // Line contents.
425 if self.config.output_wrap == OutputWrap::None {
426 let true_color = self.config.true_color;
427 let colored_output = self.config.colored_output;
428 let italics = self.config.use_italic_text;
430 for &(style, region) in regions.iter() {
431 let text = &*self.preprocess(region, &mut cursor_total);
432 let text_trimmed = text.trim_end_matches(|c| c == '\r' || c == '\n');
433 write!(
434 handle,
435 "{}",
436 as_terminal_escaped(
437 style,
438 text_trimmed,
439 true_color,
440 colored_output,
441 italics,
442 background_color
443 )
444 )?;
446 if text.len() != text_trimmed.len() {
447 if let Some(background_color) = background_color {
448 let mut ansi_style = Style::default();
449 ansi_style.background = Some(to_ansi_color(background_color, true_color));
450 let width = if cursor_total <= cursor_max {
451 cursor_max - cursor_total + 1
452 } else {
453 0
454 };
455 write!(handle, "{}", ansi_style.paint(" ".repeat(width)))?;
456 }
457 write!(handle, "{}", &text[text_trimmed.len()..])?;
458 }
459 }
461 if line.bytes().next_back() != Some(b'\n') {
462 writeln!(handle)?;
463 }
464 } else {
465 for &(style, region) in regions.iter() {
466 let ansi_iterator = AnsiCodeIterator::new(region);
467 let mut ansi_prefix: String = String::new();
468 for chunk in ansi_iterator {
469 match chunk {
470 // ANSI escape passthrough.
471 (text, true) => {
472 let is_ansi_csi = text.starts_with("\x1B[");
474 if is_ansi_csi && text.ends_with('m') {
475 // It's an ANSI SGR sequence.
476 // We should be mostly safe to just append these together.
477 ansi_prefix.push_str(text);
478 if text == "\x1B[0m" {
479 self.ansi_prefix_sgr = "\x1B[0m".to_owned();
480 } else {
481 self.ansi_prefix_sgr.push_str(text);
482 }
483 } else if is_ansi_csi {
484 // It's a regular CSI sequence.
485 // We should be mostly safe to just append these together.
486 ansi_prefix.push_str(text);
487 } else {
488 // It's probably a VT100 code.
489 // Passing it through is the safest bet.
490 write!(handle, "{}", text)?;
491 }
492 }
494 // Regular text.
495 (text, false) => {
496 let text = self.preprocess(
497 text.trim_end_matches(|c| c == '\r' || c == '\n'),
498 &mut cursor_total,
499 );
501 let mut max_width = cursor_max - cursor;
503 // line buffer (avoid calling write! for every character)
504 let mut line_buf = String::with_capacity(max_width * 4);
506 // Displayed width of line_buf
507 let mut current_width = 0;
509 for c in text.chars() {
510 // calculate the displayed width for next character
511 let cw = c.width().unwrap_or(0);
512 current_width += cw;
514 // if next character cannot be printed on this line,
515 // flush the buffer.
516 if current_width > max_width {
517 // Generate wrap padding if not already generated.
518 if panel_wrap.is_none() {
519 panel_wrap = if self.panel_width > 0 {
520 Some(format!(
521 "{} ",
522 self.decorations
523 .iter()
524 .map(|ref d| d
525 .generate(line_number, true, self)
526 .text)
527 .collect::<Vec<String>>()
528 .join(" ")
529 ))
530 } else {
531 Some("".to_string())
532 }
533 }
535 // It wraps.
536 write!(
537 handle,
538 "{}\n{}",
539 as_terminal_escaped(
540 style,
541 &*format!(
542 "{}{}{}",
543 self.ansi_prefix_sgr, ansi_prefix, line_buf
544 ),
545 self.config.true_color,
546 self.config.colored_output,
547 self.config.use_italic_text,
548 background_color
549 ),
550 panel_wrap.clone().unwrap()
551 )?;
553 cursor = 0;
554 max_width = cursor_max;
556 line_buf.clear();
557 current_width = cw;
558 }
560 line_buf.push(c);
561 }
563 // flush the buffer
564 cursor += current_width;
565 write!(
566 handle,
567 "{}",
568 as_terminal_escaped(
569 style,
570 &*format!(
571 "{}{}{}",
572 self.ansi_prefix_sgr, ansi_prefix, line_buf
573 ),
574 self.config.true_color,
575 self.config.colored_output,
576 self.config.use_italic_text,
577 background_color
578 )
579 )?;
581 // Clear the ANSI prefix buffer.
582 ansi_prefix.clear();
583 }
584 }
585 }
586 }
588 if let Some(background_color) = background_color {
589 let mut ansi_style = Style::default();
590 ansi_style.background =
591 Some(to_ansi_color(background_color, self.config.true_color));
593 write!(
594 handle,
595 "{}",
596 ansi_style.paint(" ".repeat(cursor_max - cursor))
597 )?;
598 }
599 writeln!(handle)?;
600 }
602 Ok(())
603 }
606const DEFAULT_GUTTER_COLOR: u8 = 238;
608#[derive(Debug, Default)]
609pub struct Colors {
610 pub grid: Style,
611 pub filename: Style,
612 pub git_added: Style,
613 pub git_removed: Style,
614 pub git_modified: Style,
615 pub line_number: Style,
618impl Colors {
619 fn plain() -> Self {
620 Colors::default()
621 }
623 fn colored(theme: &Theme, true_color: bool) -> Self {
624 let gutter_color = theme
625 .settings
626 .gutter_foreground
627 .map(|c| to_ansi_color(c, true_color))
628 .unwrap_or(Fixed(DEFAULT_GUTTER_COLOR));
630 Colors {
631 grid: gutter_color.normal(),
632 filename: Style::new().bold(),
633 git_added: Green.normal(),
634 git_removed: Red.normal(),
635 git_modified: Yellow.normal(),
636 line_number: gutter_color.normal(),
637 }
638 }