on 90e7d2f help sign in
bat/src/printer.rs
629 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(&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.filename());
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.filename().to_string_lossy())
239 }
240 InputFile::StdIn(Some(name)) => name.to_str().unwrap().to_string(),
241 InputFile::StdIn(None) => "STDIN".to_owned(),
242 InputFile::ThemePreviewFile => "".to_owned(),
243 };
245 writeln!(
246 handle,
247 "{}: Binary content from {} will not be printed to the terminal \
248 (but will be present if the output of 'bat' is piped). You can use 'bat -A' \
249 to show the binary file contents.",
250 Yellow.paint("[bat warning]"),
251 input
252 )?;
253 } else {
254 if self.config.style_components.grid() {
255 self.print_horizontal_line(handle, '┬')?;
256 }
257 }
258 return Ok(());
259 }
261 if self.config.style_components.grid() {
262 self.print_horizontal_line(handle, '┬')?;
264 write!(
265 handle,
266 "{}{}",
267 " ".repeat(self.panel_width),
268 self.colors
269 .grid
270 .paint(if self.panel_width > 0 { "│ " } else { "" }),
271 )?;
272 } else {
273 write!(handle, "{}", " ".repeat(self.panel_width))?;
274 }
276 let (prefix, name) = match file {
277 InputFile::Ordinary(ofile) => (
278 "File: ",
279 Cow::from(ofile.filename().to_string_lossy().to_owned()),
280 ),
281 InputFile::StdIn(Some(name)) => {
282 ("File: ", Cow::from(name.to_string_lossy().to_owned()))
283 }
284 InputFile::StdIn(None) => ("File: ", Cow::from("STDIN".to_owned())),
285 InputFile::ThemePreviewFile => ("", Cow::from("")),
286 };
288 let mode = match self.content_type {
289 Some(ContentType::BINARY) => " <BINARY>",
290 Some(ContentType::UTF_16LE) => " <UTF-16LE>",
291 Some(ContentType::UTF_16BE) => " <UTF-16BE>",
292 None => " <EMPTY>",
293 _ => "",
294 };
296 writeln!(
297 handle,
298 "{}{}{}",
299 prefix,
300 self.colors.filename.paint(name),
301 mode
302 )?;
304 if self.config.style_components.grid() {
305 if self.content_type.map_or(false, |c| c.is_text()) || self.config.show_nonprintable {
306 self.print_horizontal_line(handle, '┼')?;
307 } else {
308 self.print_horizontal_line(handle, '┴')?;
309 }
310 }
312 Ok(())
313 }
315 fn print_footer(&mut self, handle: &mut dyn Write) -> Result<()> {
316 if self.config.style_components.grid()
317 && (self.content_type.map_or(false, |c| c.is_text()) || self.config.show_nonprintable)
318 {
319 self.print_horizontal_line(handle, '┴')
320 } else {
321 Ok(())
322 }
323 }
325 fn print_snip(&mut self, handle: &mut dyn Write) -> Result<()> {
326 let panel = self.create_fake_panel(" ...");
327 let panel_count = panel.chars().count();
329 let title = "8<";
330 let title_count = title.chars().count();
332 let snip_left = "─ ".repeat((self.config.term_width - panel_count - (title_count / 2)) / 4);
333 let snip_left_count = snip_left.chars().count(); // Can't use .len() with Unicode.
335 let snip_right =
336 " ─".repeat((self.config.term_width - panel_count - snip_left_count - title_count) / 2);
338 write!(
339 handle,
340 "{}\n",
341 self.colors
342 .grid
343 .paint(format!("{}{}{}{}", panel, snip_left, title, snip_right))
344 )?;
346 Ok(())
347 }
349 fn print_line(
350 &mut self,
351 out_of_range: bool,
352 handle: &mut dyn Write,
353 line_number: usize,
354 line_buffer: &[u8],
355 ) -> Result<()> {
356 let line = if self.config.show_nonprintable {
357 replace_nonprintable(&line_buffer, self.config.tab_width)
358 } else {
359 match self.content_type {
360 Some(ContentType::BINARY) | None => {
361 return Ok(());
362 }
363 Some(ContentType::UTF_16LE) => UTF_16LE
364 .decode(&line_buffer, DecoderTrap::Replace)
365 .map_err(|_| "Invalid UTF-16LE")?,
366 Some(ContentType::UTF_16BE) => UTF_16BE
367 .decode(&line_buffer, DecoderTrap::Replace)
368 .map_err(|_| "Invalid UTF-16BE")?,
369 _ => String::from_utf8_lossy(&line_buffer).to_string(),
370 }
371 };
373 let regions = {
374 let highlighter = match self.highlighter {
375 Some(ref mut highlighter) => highlighter,
376 _ => {
377 return Ok(());
378 }
379 };
380 highlighter.highlight(line.as_ref(), self.syntax_set)
381 };
383 if out_of_range {
384 return Ok(());
385 }
387 let mut cursor: usize = 0;
388 let mut cursor_max: usize = self.config.term_width;
389 let mut cursor_total: usize = 0;
390 let mut panel_wrap: Option<String> = None;
392 // Line highlighting
393 let highlight_this_line =
394 self.config.highlighted_lines.0.check(line_number) == RangeCheckResult::InRange;
396 let background_color = self
397 .background_color_highlight
398 .filter(|_| highlight_this_line);
400 // Line decorations.
401 if self.panel_width > 0 {
402 let decorations = self
403 .decorations
404 .iter()
405 .map(|ref d| d.generate(line_number, false, self))
406 .collect::<Vec<_>>();
408 for deco in decorations {
409 write!(handle, "{} ", deco.text)?;
410 cursor_max -= deco.width + 1;
411 }
412 }
414 // Line contents.
415 if self.config.output_wrap == OutputWrap::None {
416 let true_color = self.config.true_color;
417 let colored_output = self.config.colored_output;
418 let italics = self.config.use_italic_text;
420 for &(style, region) in regions.iter() {
421 let text = &*self.preprocess(region, &mut cursor_total);
422 let text_trimmed = text.trim_end_matches(|c| c == '\r' || c == '\n');
423 write!(
424 handle,
425 "{}",
426 as_terminal_escaped(
427 style,
428 text_trimmed,
429 true_color,
430 colored_output,
431 italics,
432 background_color
433 )
434 )?;
436 if text.len() != text_trimmed.len() {
437 if let Some(background_color) = background_color {
438 let mut ansi_style = Style::default();
439 ansi_style.background = Some(to_ansi_color(background_color, true_color));
440 let width = if cursor_total <= cursor_max {
441 cursor_max - cursor_total + 1
442 } else {
443 0
444 };
445 write!(handle, "{}", ansi_style.paint(" ".repeat(width)))?;
446 }
447 write!(handle, "{}", &text[text_trimmed.len()..])?;
448 }
449 }
451 if line.bytes().next_back() != Some(b'\n') {
452 writeln!(handle)?;
453 }
454 } else {
455 for &(style, region) in regions.iter() {
456 let ansi_iterator = AnsiCodeIterator::new(region);
457 let mut ansi_prefix: String = String::new();
458 for chunk in ansi_iterator {
459 match chunk {
460 // ANSI escape passthrough.
461 (text, true) => {
462 let is_ansi_csi = text.starts_with("\x1B[");
464 if is_ansi_csi && text.ends_with('m') {
465 // It's an ANSI SGR sequence.
466 // We should be mostly safe to just append these together.
467 ansi_prefix.push_str(text);
468 if text == "\x1B[0m" {
469 self.ansi_prefix_sgr = "\x1B[0m".to_owned();
470 } else {
471 self.ansi_prefix_sgr.push_str(text);
472 }
473 } else if is_ansi_csi {
474 // It's a regular CSI sequence.
475 // We should be mostly safe to just append these together.
476 ansi_prefix.push_str(text);
477 } else {
478 // It's probably a VT100 code.
479 // Passing it through is the safest bet.
480 write!(handle, "{}", text)?;
481 }
482 }
484 // Regular text.
485 (text, false) => {
486 let text = self.preprocess(
487 text.trim_end_matches(|c| c == '\r' || c == '\n'),
488 &mut cursor_total,
489 );
491 let mut max_width = cursor_max - cursor;
493 // line buffer (avoid calling write! for every character)
494 let mut line_buf = String::with_capacity(max_width * 4);
496 // Displayed width of line_buf
497 let mut current_width = 0;
499 for c in text.chars() {
500 // calculate the displayed width for next character
501 let cw = c.width().unwrap_or(0);
502 current_width += cw;
504 // if next character cannot be printed on this line,
505 // flush the buffer.
506 if current_width > max_width {
507 // Generate wrap padding if not already generated.
508 if panel_wrap.is_none() {
509 panel_wrap = if self.panel_width > 0 {
510 Some(format!(
511 "{} ",
512 self.decorations
513 .iter()
514 .map(|ref d| d
515 .generate(line_number, true, self)
516 .text)
517 .collect::<Vec<String>>()
518 .join(" ")
519 ))
520 } else {
521 Some("".to_string())
522 }
523 }
525 // It wraps.
526 write!(
527 handle,
528 "{}\n{}",
529 as_terminal_escaped(
530 style,
531 &*format!(
532 "{}{}{}",
533 self.ansi_prefix_sgr, ansi_prefix, line_buf
534 ),
535 self.config.true_color,
536 self.config.colored_output,
537 self.config.use_italic_text,
538 background_color
539 ),
540 panel_wrap.clone().unwrap()
541 )?;
543 cursor = 0;
544 max_width = cursor_max;
546 line_buf.clear();
547 current_width = cw;
548 }
550 line_buf.push(c);
551 }
553 // flush the buffer
554 cursor += current_width;
555 write!(
556 handle,
557 "{}",
558 as_terminal_escaped(
559 style,
560 &*format!(
561 "{}{}{}",
562 self.ansi_prefix_sgr, ansi_prefix, line_buf
563 ),
564 self.config.true_color,
565 self.config.colored_output,
566 self.config.use_italic_text,
567 background_color
568 )
569 )?;
571 // Clear the ANSI prefix buffer.
572 ansi_prefix.clear();
573 }
574 }
575 }
576 }
578 if let Some(background_color) = background_color {
579 let mut ansi_style = Style::default();
580 ansi_style.background =
581 Some(to_ansi_color(background_color, self.config.true_color));
583 write!(
584 handle,
585 "{}",
586 ansi_style.paint(" ".repeat(cursor_max - cursor))
587 )?;
588 }
589 writeln!(handle)?;
590 }
592 Ok(())
593 }
596const DEFAULT_GUTTER_COLOR: u8 = 238;
598#[derive(Debug, Default)]
599pub struct Colors {
600 pub grid: Style,
601 pub filename: Style,
602 pub git_added: Style,
603 pub git_removed: Style,
604 pub git_modified: Style,
605 pub line_number: Style,
608impl Colors {
609 fn plain() -> Self {
610 Colors::default()
611 }
613 fn colored(theme: &Theme, true_color: bool) -> Self {
614 let gutter_color = theme
615 .settings
616 .gutter_foreground
617 .map(|c| to_ansi_color(c, true_color))
618 .unwrap_or(Fixed(DEFAULT_GUTTER_COLOR));
620 Colors {
621 grid: gutter_color.normal(),
622 filename: Style::new().bold(),
623 git_added: Green.normal(),
624 git_removed: Red.normal(),
625 git_modified: Yellow.normal(),
626 line_number: gutter_color.normal(),
627 }
628 }