on 522ab7a help sign in
bat/src/printer.rs
633 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;
24use crate::decorations::{
25 Decoration, GridBorderDecoration, LineChangesDecoration, LineNumberDecoration,
26};
27use crate::diff::get_git_diff;
28use crate::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 pub line_changes: Option<LineChanges>,
104 highlighter: Option<HighlightLines<'a>>,
105 syntax_set: &'a SyntaxSet,
106 background_color_highlight: Option<Color>,
109impl<'a> InteractivePrinter<'a> {
110 pub fn new(
111 config: &'a Config,
112 assets: &'a HighlightingAssets,
113 file: InputFile,
114 reader: &mut InputFileReader,
115 ) -> Self {
116 let theme = assets.get_theme(&config.theme);
118 let background_color_highlight = theme.settings.line_highlight;
120 let colors = if config.colored_output {
121 Colors::colored(theme, config.true_color)
122 } else {
123 Colors::plain()
124 };
126 // Create decorations.
127 let mut decorations: Vec<Box<dyn Decoration>> = Vec::new();
129 if config.style_components.numbers() {
130 decorations.push(Box::new(LineNumberDecoration::new(&colors)));
131 }
133 if config.style_components.changes() {
134 decorations.push(Box::new(LineChangesDecoration::new(&colors)));
135 }
137 let mut panel_width: usize =
138 decorations.len() + decorations.iter().fold(0, |a, x| a + x.width());
140 // The grid border decoration isn't added until after the panel_width calculation, since the
141 // print_horizontal_line, print_header, and print_footer functions all assume the panel
142 // width is without the grid border.
143 if config.style_components.grid() && !decorations.is_empty() {
144 decorations.push(Box::new(GridBorderDecoration::new(&colors)));
145 }
147 // Disable the panel if the terminal is too small (i.e. can't fit 5 characters with the
148 // panel showing).
149 if config.term_width
150 < (decorations.len() + decorations.iter().fold(0, |a, x| a + x.width())) + 5
151 {
152 decorations.clear();
153 panel_width = 0;
154 }
156 let mut line_changes = None;
158 let highlighter = if reader
159 .content_type
160 .map_or(false, |c| c.is_binary() && !config.show_nonprintable)
161 {
162 None
163 } else {
164 // Get the Git modifications
165 line_changes = if config.style_components.changes() {
166 match file {
167 InputFile::Ordinary(filename) => get_git_diff(filename),
168 _ => None,
169 }
170 } else {
171 None
172 };
174 // Determine the type of syntax for highlighting
175 let syntax = assets.get_syntax(config.language, file, reader, &config.syntax_mapping);
176 Some(HighlightLines::new(syntax, theme))
177 };
179 InteractivePrinter {
180 panel_width,
181 colors,
182 config,
183 decorations,
184 content_type: reader.content_type,
185 ansi_prefix_sgr: String::new(),
186 line_changes,
187 highlighter,
188 syntax_set: &assets.syntax_set,
189 background_color_highlight,
190 }
191 }
193 fn print_horizontal_line(&mut self, handle: &mut dyn Write, grid_char: char) -> Result<()> {
194 if self.panel_width == 0 {
195 writeln!(
196 handle,
197 "{}",
198 self.colors.grid.paint("─".repeat(self.config.term_width))
199 )?;
200 } else {
201 let hline = "─".repeat(self.config.term_width - (self.panel_width + 1));
202 let hline = format!("{}{}{}", "─".repeat(self.panel_width), grid_char, hline);
203 writeln!(handle, "{}", self.colors.grid.paint(hline))?;
204 }
206 Ok(())
207 }
209 fn create_fake_panel(&self, text: &str) -> String {
210 if self.panel_width == 0 {
211 "".to_string()
212 } else {
213 let text_truncated: String = text.chars().take(self.panel_width - 1).collect();
214 let text_filled: String = format!(
215 "{}{}",
216 text_truncated,
217 " ".repeat(self.panel_width - 1 - text_truncated.len())
218 );
219 if self.config.style_components.grid() {
220 format!("{} │ ", text_filled)
221 } else {
222 format!("{}", text_filled)
223 }
224 }
225 }
227 fn preprocess(&self, text: &str, cursor: &mut usize) -> String {
228 if self.config.tab_width > 0 {
229 expand_tabs(text, self.config.tab_width, cursor)
230 } else {
231 text.to_string()
232 }
233 }
236impl<'a> Printer for InteractivePrinter<'a> {
237 fn print_header(
238 &mut self,
239 handle: &mut dyn Write,
240 file: InputFile,
241 file_name: Option<&str>,
242 ) -> Result<()> {
243 if !self.config.style_components.header() {
244 if Some(ContentType::BINARY) == self.content_type && !self.config.show_nonprintable {
245 let input = match file {
246 InputFile::Ordinary(filename) => format!(
247 "file '{}'",
248 file_name.unwrap_or(&filename.to_string_lossy())
249 ),
250 _ => file_name.unwrap_or("STDIN").to_owned(),
251 };
253 writeln!(
254 handle,
255 "{}: Binary content from {} will not be printed to the terminal \
256 (but will be present if the output of 'bat' is piped). You can use 'bat -A' \
257 to show the binary file contents.",
258 Yellow.paint("[bat warning]"),
259 input
260 )?;
261 } else {
262 if self.config.style_components.grid() {
263 self.print_horizontal_line(handle, '┬')?;
264 }
265 }
266 return Ok(());
267 }
269 if self.config.style_components.grid() {
270 self.print_horizontal_line(handle, '┬')?;
272 write!(
273 handle,
274 "{}{}",
275 " ".repeat(self.panel_width),
276 self.colors
277 .grid
278 .paint(if self.panel_width > 0 { "│ " } else { "" }),
279 )?;
280 } else {
281 write!(handle, "{}", " ".repeat(self.panel_width))?;
282 }
284 let (prefix, name) = match file {
285 InputFile::Ordinary(filename) => (
286 "File: ",
287 Cow::from(file_name.unwrap_or(&filename.to_string_lossy()).to_owned()),
288 ),
289 _ => ("File: ", Cow::from(file_name.unwrap_or("STDIN").to_owned())),
290 };
292 let mode = match self.content_type {
293 Some(ContentType::BINARY) => " <BINARY>",
294 Some(ContentType::UTF_16LE) => " <UTF-16LE>",
295 Some(ContentType::UTF_16BE) => " <UTF-16BE>",
296 None => " <EMPTY>",
297 _ => "",
298 };
300 writeln!(
301 handle,
302 "{}{}{}",
303 prefix,
304 self.colors.filename.paint(name),
305 mode
306 )?;
308 if self.config.style_components.grid() {
309 if self.content_type.map_or(false, |c| c.is_text()) || self.config.show_nonprintable {
310 self.print_horizontal_line(handle, '┼')?;
311 } else {
312 self.print_horizontal_line(handle, '┴')?;
313 }
314 }
316 Ok(())
317 }
319 fn print_footer(&mut self, handle: &mut dyn Write) -> Result<()> {
320 if self.config.style_components.grid()
321 && (self.content_type.map_or(false, |c| c.is_text()) || self.config.show_nonprintable)
322 {
323 self.print_horizontal_line(handle, '┴')
324 } else {
325 Ok(())
326 }
327 }
329 fn print_snip(&mut self, handle: &mut dyn Write) -> Result<()> {
330 let panel = self.create_fake_panel(" ...");
331 let panel_count = panel.chars().count();
333 let title = "8<";
334 let title_count = title.chars().count();
336 let snip_left = "─ ".repeat((self.config.term_width - panel_count - (title_count / 2)) / 4);
337 let snip_left_count = snip_left.chars().count(); // Can't use .len() with Unicode.
339 let snip_right =
340 " ─".repeat((self.config.term_width - panel_count - snip_left_count - title_count) / 2);
342 write!(
343 handle,
344 "{}\n",
345 self.colors
346 .grid
347 .paint(format!("{}{}{}{}", panel, snip_left, title, snip_right))
348 )?;
350 Ok(())
351 }
353 fn print_line(
354 &mut self,
355 out_of_range: bool,
356 handle: &mut dyn Write,
357 line_number: usize,
358 line_buffer: &[u8],
359 ) -> Result<()> {
360 let line = if self.config.show_nonprintable {
361 replace_nonprintable(&line_buffer, self.config.tab_width)
362 } else {
363 match self.content_type {
364 Some(ContentType::BINARY) | None => {
365 return Ok(());
366 }
367 Some(ContentType::UTF_16LE) => UTF_16LE
368 .decode(&line_buffer, DecoderTrap::Replace)
369 .map_err(|_| "Invalid UTF-16LE")?,
370 Some(ContentType::UTF_16BE) => UTF_16BE
371 .decode(&line_buffer, DecoderTrap::Replace)
372 .map_err(|_| "Invalid UTF-16BE")?,
373 _ => String::from_utf8_lossy(&line_buffer).to_string(),
374 }
375 };
377 let regions = {
378 let highlighter = match self.highlighter {
379 Some(ref mut highlighter) => highlighter,
380 _ => {
381 return Ok(());
382 }
383 };
384 highlighter.highlight(line.as_ref(), self.syntax_set)
385 };
387 if out_of_range {
388 return Ok(());
389 }
391 let mut cursor: usize = 0;
392 let mut cursor_max: usize = self.config.term_width;
393 let mut cursor_total: usize = 0;
394 let mut panel_wrap: Option<String> = None;
396 // Line highlighting
397 let highlight_this_line =
398 self.config.highlighted_lines.0.check(line_number) == RangeCheckResult::InRange;
400 let background_color = self
401 .background_color_highlight
402 .filter(|_| highlight_this_line);
404 // Line decorations.
405 if self.panel_width > 0 {
406 let decorations = self
407 .decorations
408 .iter()
409 .map(|ref d| d.generate(line_number, false, self))
410 .collect::<Vec<_>>();
412 for deco in decorations {
413 write!(handle, "{} ", deco.text)?;
414 cursor_max -= deco.width + 1;
415 }
416 }
418 // Line contents.
419 if self.config.output_wrap == OutputWrap::None {
420 let true_color = self.config.true_color;
421 let colored_output = self.config.colored_output;
422 let italics = self.config.use_italic_text;
424 for &(style, region) in regions.iter() {
425 let text = &*self.preprocess(region, &mut cursor_total);
426 let text_trimmed = text.trim_end_matches(|c| c == '\r' || c == '\n');
427 write!(
428 handle,
429 "{}",
430 as_terminal_escaped(
431 style,
432 text_trimmed,
433 true_color,
434 colored_output,
435 italics,
436 background_color
437 )
438 )?;
440 if text.len() != text_trimmed.len() {
441 if let Some(background_color) = background_color {
442 let mut ansi_style = Style::default();
443 ansi_style.background = Some(to_ansi_color(background_color, true_color));
444 let width = if cursor_total <= cursor_max {
445 cursor_max - cursor_total + 1
446 } else {
447 0
448 };
449 write!(handle, "{}", ansi_style.paint(" ".repeat(width)))?;
450 }
451 write!(handle, "{}", &text[text_trimmed.len()..])?;
452 }
453 }
455 if line.bytes().next_back() != Some(b'\n') {
456 writeln!(handle)?;
457 }
458 } else {
459 for &(style, region) in regions.iter() {
460 let ansi_iterator = AnsiCodeIterator::new(region);
461 let mut ansi_prefix: String = String::new();
462 for chunk in ansi_iterator {
463 match chunk {
464 // ANSI escape passthrough.
465 (text, true) => {
466 let is_ansi_csi = text.starts_with("\x1B[");
468 if is_ansi_csi && text.ends_with('m') {
469 // It's an ANSI SGR sequence.
470 // We should be mostly safe to just append these together.
471 ansi_prefix.push_str(text);
472 if text == "\x1B[0m" {
473 self.ansi_prefix_sgr = "\x1B[0m".to_owned();
474 } else {
475 self.ansi_prefix_sgr.push_str(text);
476 }
477 } else if is_ansi_csi {
478 // It's a regular CSI sequence.
479 // We should be mostly safe to just append these together.
480 ansi_prefix.push_str(text);
481 } else {
482 // It's probably a VT100 code.
483 // Passing it through is the safest bet.
484 write!(handle, "{}", text)?;
485 }
486 }
488 // Regular text.
489 (text, false) => {
490 let text = self.preprocess(
491 text.trim_end_matches(|c| c == '\r' || c == '\n'),
492 &mut cursor_total,
493 );
495 let mut max_width = cursor_max - cursor;
497 // line buffer (avoid calling write! for every character)
498 let mut line_buf = String::with_capacity(max_width * 4);
500 // Displayed width of line_buf
501 let mut current_width = 0;
503 for c in text.chars() {
504 // calculate the displayed width for next character
505 let cw = c.width().unwrap_or(0);
506 current_width += cw;
508 // if next character cannot be printed on this line,
509 // flush the buffer.
510 if current_width > max_width {
511 // Generate wrap padding if not already generated.
512 if panel_wrap.is_none() {
513 panel_wrap = if self.panel_width > 0 {
514 Some(format!(
515 "{} ",
516 self.decorations
517 .iter()
518 .map(|ref d| d
519 .generate(line_number, true, self)
520 .text)
521 .collect::<Vec<String>>()
522 .join(" ")
523 ))
524 } else {
525 Some("".to_string())
526 }
527 }
529 // It wraps.
530 write!(
531 handle,
532 "{}\n{}",
533 as_terminal_escaped(
534 style,
535 &*format!(
536 "{}{}{}",
537 self.ansi_prefix_sgr, ansi_prefix, line_buf
538 ),
539 self.config.true_color,
540 self.config.colored_output,
541 self.config.use_italic_text,
542 background_color
543 ),
544 panel_wrap.clone().unwrap()
545 )?;
547 cursor = 0;
548 max_width = cursor_max;
550 line_buf.clear();
551 current_width = cw;
552 }
554 line_buf.push(c);
555 }
557 // flush the buffer
558 cursor += current_width;
559 write!(
560 handle,
561 "{}",
562 as_terminal_escaped(
563 style,
564 &*format!(
565 "{}{}{}",
566 self.ansi_prefix_sgr, ansi_prefix, line_buf
567 ),
568 self.config.true_color,
569 self.config.colored_output,
570 self.config.use_italic_text,
571 background_color
572 )
573 )?;
575 // Clear the ANSI prefix buffer.
576 ansi_prefix.clear();
577 }
578 }
579 }
580 }
582 if let Some(background_color) = background_color {
583 let mut ansi_style = Style::default();
584 ansi_style.background =
585 Some(to_ansi_color(background_color, self.config.true_color));
587 write!(
588 handle,
589 "{}",
590 ansi_style.paint(" ".repeat(cursor_max - cursor))
591 )?;
592 }
593 writeln!(handle)?;
594 }
596 Ok(())
597 }
600const DEFAULT_GUTTER_COLOR: u8 = 238;
602#[derive(Debug, Default)]
603pub struct Colors {
604 pub grid: Style,
605 pub filename: Style,
606 pub git_added: Style,
607 pub git_removed: Style,
608 pub git_modified: Style,
609 pub line_number: Style,
612impl Colors {
613 fn plain() -> Self {
614 Colors::default()
615 }
617 fn colored(theme: &Theme, true_color: bool) -> Self {
618 let gutter_color = theme
619 .settings
620 .gutter_foreground
621 .map(|c| to_ansi_color(c, true_color))
622 .unwrap_or(Fixed(DEFAULT_GUTTER_COLOR));
624 Colors {
625 grid: gutter_color.normal(),
626 filename: Style::new().bold(),
627 git_added: Green.normal(),
628 git_removed: Red.normal(),
629 git_modified: Yellow.normal(),
630 line_number: gutter_color.normal(),
631 }
632 }