on ad42b27 help sign in
bat/src/printer.rs
600 lines 21 kB history raw
1use std::io::Write;
2use std::vec::Vec;
3use std::borrow::Cow;
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 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::line_range::RangeCheckResult;
29use crate::preprocessor::{expand_tabs, replace_nonprintable};
30use crate::style::OutputWrap;
31use crate::terminal::{as_terminal_escaped, to_ansi_color};
32use crate::Config;
34pub trait Printer {
35 fn print_header(&mut self, handle: &mut dyn Write, file: InputFile) -> Result<()>;
36 fn print_footer(&mut self, handle: &mut dyn Write) -> Result<()>;
38 fn print_snip(&mut self, handle: &mut dyn Write) -> Result<()>;
40 fn print_line(
41 &mut self,
42 out_of_range: bool,
43 handle: &mut dyn Write,
44 line_number: usize,
45 line_buffer: &[u8],
46 ) -> Result<()>;
49pub struct SimplePrinter;
51impl SimplePrinter {
52 pub fn new() -> Self {
53 SimplePrinter {}
54 }
57impl Printer for SimplePrinter {
58 fn print_header(&mut self, _handle: &mut dyn Write, _file: InputFile) -> Result<()> {
59 Ok(())
60 }
62 fn print_footer(&mut self, _handle: &mut dyn Write) -> Result<()> {
63 Ok(())
64 }
66 fn print_snip(&mut self, _handle: &mut dyn Write) -> Result<()> {
67 Ok(())
68 }
70 fn print_line(
71 &mut self,
72 out_of_range: bool,
73 handle: &mut dyn Write,
74 _line_number: usize,
75 line_buffer: &[u8],
76 ) -> Result<()> {
77 if !out_of_range {
78 handle.write_all(line_buffer)?;
79 }
80 Ok(())
81 }
84pub struct InteractivePrinter<'a> {
85 colors: Colors,
86 config: &'a Config<'a>,
87 decorations: Vec<Box<dyn Decoration>>,
88 panel_width: usize,
89 ansi_prefix_sgr: String,
90 content_type: Option<ContentType>,
91 pub line_changes: Option<LineChanges>,
92 highlighter: Option<HighlightLines<'a>>,
93 syntax_set: &'a SyntaxSet,
94 background_color_highlight: Option<Color>,
97impl<'a> InteractivePrinter<'a> {
98 pub fn new(
99 config: &'a Config,
100 assets: &'a HighlightingAssets,
101 file: InputFile,
102 reader: &mut InputFileReader,
103 ) -> Self {
104 let theme = assets.get_theme(&config.theme);
106 let background_color_highlight = theme.settings.line_highlight;
108 let colors = if config.colored_output {
109 Colors::colored(theme, config.true_color)
110 } else {
111 Colors::plain()
112 };
114 // Create decorations.
115 let mut decorations: Vec<Box<dyn Decoration>> = Vec::new();
117 if config.output_components.numbers() {
118 decorations.push(Box::new(LineNumberDecoration::new(&colors)));
119 }
121 if config.output_components.changes() {
122 decorations.push(Box::new(LineChangesDecoration::new(&colors)));
123 }
125 let mut panel_width: usize =
126 decorations.len() + decorations.iter().fold(0, |a, x| a + x.width());
128 // The grid border decoration isn't added until after the panel_width calculation, since the
129 // print_horizontal_line, print_header, and print_footer functions all assume the panel
130 // width is without the grid border.
131 if config.output_components.grid() && !decorations.is_empty() {
132 decorations.push(Box::new(GridBorderDecoration::new(&colors)));
133 }
135 // Disable the panel if the terminal is too small (i.e. can't fit 5 characters with the
136 // panel showing).
137 if config.term_width
138 < (decorations.len() + decorations.iter().fold(0, |a, x| a + x.width())) + 5
139 {
140 decorations.clear();
141 panel_width = 0;
142 }
144 let mut line_changes = None;
146 let highlighter = if reader
147 .content_type
148 .map_or(false, |c| c.is_binary() && !config.show_nonprintable)
149 {
150 None
151 } else {
152 // Get the Git modifications
153 line_changes = if config.output_components.changes() {
154 match file {
155 InputFile::Ordinary(filename) => get_git_diff(filename),
156 _ => None,
157 }
158 } else {
159 None
160 };
162 // Determine the type of syntax for highlighting
163 let syntax = assets.get_syntax(config.language, file, reader, &config.syntax_mapping);
164 Some(HighlightLines::new(syntax, theme))
165 };
167 InteractivePrinter {
168 panel_width,
169 colors,
170 config,
171 decorations,
172 content_type: reader.content_type,
173 ansi_prefix_sgr: String::new(),
174 line_changes,
175 highlighter,
176 syntax_set: &assets.syntax_set,
177 background_color_highlight,
178 }
179 }
181 fn print_horizontal_line(&mut self, handle: &mut dyn Write, grid_char: char) -> Result<()> {
182 if self.panel_width == 0 {
183 writeln!(
184 handle,
185 "{}",
186 self.colors.grid.paint("─".repeat(self.config.term_width))
187 )?;
188 } else {
189 let hline = "─".repeat(self.config.term_width - (self.panel_width + 1));
190 let hline = format!("{}{}{}", "─".repeat(self.panel_width), grid_char, hline);
191 writeln!(handle, "{}", self.colors.grid.paint(hline))?;
192 }
194 Ok(())
195 }
197 fn create_fake_panel(&self, text: &str) -> String {
198 if self.panel_width == 0 {
199 "".to_string()
200 } else {
201 let text_truncated: String = text.chars().take(self.panel_width - 1).collect();
202 let text_filled: String = format!(
203 "{}{}",
204 text_truncated,
205 " ".repeat(self.panel_width - 1 - text_truncated.len())
206 );
207 if self.config.output_components.grid() {
208 format!("{} │ ", text_filled)
209 } else {
210 format!("{}", text_filled)
211 }
212 }
213 }
215 fn preprocess(&self, text: &str, cursor: &mut usize) -> String {
216 if self.config.tab_width > 0 {
217 expand_tabs(text, self.config.tab_width, cursor)
218 } else {
219 text.to_string()
220 }
221 }
224impl<'a> Printer for InteractivePrinter<'a> {
225 fn print_header(&mut self, handle: &mut dyn Write, file: InputFile) -> Result<()> {
226 if !self.config.output_components.header() {
227 if Some(ContentType::BINARY) == self.content_type && !self.config.show_nonprintable {
228 let input = match file {
229 InputFile::Ordinary(filename) => format!("file '{}'", filename.to_string_lossy()),
230 _ => "STDIN".into(),
231 };
233 writeln!(
234 handle,
235 "{}: Binary content from {} will not be printed to the terminal \
236 (but will be present if the output of 'bat' is piped). You can use 'bat -A' \
237 to show the binary file contents.",
238 Yellow.paint("[bat warning]"),
239 input
240 )?;
241 } else {
242 if self.config.output_components.grid() {
243 self.print_horizontal_line(handle, '┬')?;
244 }
245 }
246 return Ok(());
247 }
249 if self.config.output_components.grid() {
250 self.print_horizontal_line(handle, '┬')?;
252 write!(
253 handle,
254 "{}{}",
255 " ".repeat(self.panel_width),
256 self.colors
257 .grid
258 .paint(if self.panel_width > 0 { "│ " } else { "" }),
259 )?;
260 } else {
261 write!(handle, "{}", " ".repeat(self.panel_width))?;
262 }
264 let (prefix, name) = match file {
265 InputFile::Ordinary(filename) => ("File: ", filename.to_string_lossy()),
266 _ => ("", Cow::from("STDIN")),
267 };
269 let mode = match self.content_type {
270 Some(ContentType::BINARY) => " <BINARY>",
271 Some(ContentType::UTF_16LE) => " <UTF-16LE>",
272 Some(ContentType::UTF_16BE) => " <UTF-16BE>",
273 None => " <EMPTY>",
274 _ => "",
275 };
277 writeln!(
278 handle,
279 "{}{}{}",
280 prefix,
281 self.colors.filename.paint(name),
282 mode
283 )?;
285 if self.config.output_components.grid() {
286 if self.content_type.map_or(false, |c| c.is_text()) || self.config.show_nonprintable {
287 self.print_horizontal_line(handle, '┼')?;
288 } else {
289 self.print_horizontal_line(handle, '┴')?;
290 }
291 }
293 Ok(())
294 }
296 fn print_footer(&mut self, handle: &mut dyn Write) -> Result<()> {
297 if self.config.output_components.grid()
298 && (self.content_type.map_or(false, |c| c.is_text()) || self.config.show_nonprintable)
299 {
300 self.print_horizontal_line(handle, '┴')
301 } else {
302 Ok(())
303 }
304 }
306 fn print_snip(&mut self, handle: &mut dyn Write) -> Result<()> {
307 let panel = self.create_fake_panel(" ...");
308 let panel_count = panel.chars().count();
310 let title = "8<";
311 let title_count = title.chars().count();
313 let snip_left = "─ ".repeat((self.config.term_width - panel_count - (title_count / 2)) / 4);
314 let snip_left_count = snip_left.chars().count(); // Can't use .len() with Unicode.
316 let snip_right =
317 " ─".repeat((self.config.term_width - panel_count - snip_left_count - title_count) / 2);
319 write!(
320 handle,
321 "{}\n",
322 self.colors
323 .grid
324 .paint(format!("{}{}{}{}", panel, snip_left, title, snip_right))
325 )?;
327 Ok(())
328 }
330 fn print_line(
331 &mut self,
332 out_of_range: bool,
333 handle: &mut dyn Write,
334 line_number: usize,
335 line_buffer: &[u8],
336 ) -> Result<()> {
337 let line = if self.config.show_nonprintable {
338 replace_nonprintable(&line_buffer, self.config.tab_width)
339 } else {
340 match self.content_type {
341 Some(ContentType::BINARY) | None => {
342 return Ok(());
343 }
344 Some(ContentType::UTF_16LE) => UTF_16LE
345 .decode(&line_buffer, DecoderTrap::Replace)
346 .map_err(|_| "Invalid UTF-16LE")?,
347 Some(ContentType::UTF_16BE) => UTF_16BE
348 .decode(&line_buffer, DecoderTrap::Replace)
349 .map_err(|_| "Invalid UTF-16BE")?,
350 _ => String::from_utf8_lossy(&line_buffer).to_string(),
351 }
352 };
354 let regions = {
355 let highlighter = match self.highlighter {
356 Some(ref mut highlighter) => highlighter,
357 _ => {
358 return Ok(());
359 }
360 };
361 highlighter.highlight(line.as_ref(), self.syntax_set)
362 };
364 if out_of_range {
365 return Ok(());
366 }
368 let mut cursor: usize = 0;
369 let mut cursor_max: usize = self.config.term_width;
370 let mut cursor_total: usize = 0;
371 let mut panel_wrap: Option<String> = None;
373 // Line highlighting
374 let highlight_this_line =
375 self.config.highlight_lines.check(line_number) == RangeCheckResult::InRange;
377 let background_color = self
378 .background_color_highlight
379 .filter(|_| highlight_this_line);
381 // Line decorations.
382 if self.panel_width > 0 {
383 let decorations = self
384 .decorations
385 .iter()
386 .map(|ref d| d.generate(line_number, false, self))
387 .collect::<Vec<_>>();
389 for deco in decorations {
390 write!(handle, "{} ", deco.text)?;
391 cursor_max -= deco.width + 1;
392 }
393 }
395 // Line contents.
396 if self.config.output_wrap == OutputWrap::None {
397 let true_color = self.config.true_color;
398 let colored_output = self.config.colored_output;
399 let italics = self.config.use_italic_text;
401 for &(style, region) in regions.iter() {
402 let text = &*self.preprocess(region, &mut cursor_total);
403 let text_trimmed = text.trim_end_matches(|c| c == '\r' || c == '\n');
404 write!(
405 handle,
406 "{}",
407 as_terminal_escaped(
408 style,
409 text_trimmed,
410 true_color,
411 colored_output,
412 italics,
413 background_color
414 )
415 )?;
417 if text.len() != text_trimmed.len() {
418 if let Some(background_color) = background_color {
419 let mut ansi_style = Style::default();
420 ansi_style.background = Some(to_ansi_color(background_color, true_color));
421 let width = if cursor_total <= cursor_max {
422 cursor_max - cursor_total + 1
423 } else {
424 0
425 };
426 write!(handle, "{}", ansi_style.paint(" ".repeat(width)))?;
427 }
428 write!(handle, "{}", &text[text_trimmed.len()..])?;
429 }
430 }
432 if line.bytes().next_back() != Some(b'\n') {
433 writeln!(handle)?;
434 }
435 } else {
436 for &(style, region) in regions.iter() {
437 let ansi_iterator = AnsiCodeIterator::new(region);
438 let mut ansi_prefix: String = String::new();
439 for chunk in ansi_iterator {
440 match chunk {
441 // ANSI escape passthrough.
442 (text, true) => {
443 let is_ansi_csi = text.starts_with("\x1B[");
445 if is_ansi_csi && text.ends_with('m') {
446 // It's an ANSI SGR sequence.
447 // We should be mostly safe to just append these together.
448 ansi_prefix.push_str(text);
449 if text == "\x1B[0m" {
450 self.ansi_prefix_sgr = "\x1B[0m".to_owned();
451 } else {
452 self.ansi_prefix_sgr.push_str(text);
453 }
454 } else if is_ansi_csi {
455 // It's a regular CSI sequence.
456 // We should be mostly safe to just append these together.
457 ansi_prefix.push_str(text);
458 } else {
459 // It's probably a VT100 code.
460 // Passing it through is the safest bet.
461 write!(handle, "{}", text)?;
462 }
463 }
465 // Regular text.
466 (text, false) => {
467 let text = self.preprocess(
468 text.trim_end_matches(|c| c == '\r' || c == '\n'),
469 &mut cursor_total,
470 );
472 let mut chars = text.chars();
473 let mut remaining = text.chars().count();
475 while remaining > 0 {
476 let available = cursor_max - cursor;
478 // It fits.
479 if remaining <= available {
480 let text = chars.by_ref().take(remaining).collect::<String>();
481 cursor += remaining;
483 write!(
484 handle,
485 "{}",
486 as_terminal_escaped(
487 style,
488 &*format!(
489 "{}{}{}",
490 self.ansi_prefix_sgr, ansi_prefix, text
491 ),
492 self.config.true_color,
493 self.config.colored_output,
494 self.config.use_italic_text,
495 background_color
496 )
497 )?;
498 break;
499 }
501 // Generate wrap padding if not already generated.
502 if panel_wrap.is_none() {
503 panel_wrap = if self.panel_width > 0 {
504 Some(format!(
505 "{} ",
506 self.decorations
507 .iter()
508 .map(|ref d| d
509 .generate(line_number, true, self)
510 .text)
511 .collect::<Vec<String>>()
512 .join(" ")
513 ))
514 } else {
515 Some("".to_string())
516 }
517 }
519 // It wraps.
520 let text = chars.by_ref().take(available).collect::<String>();
521 cursor = 0;
522 remaining -= available;
524 write!(
525 handle,
526 "{}\n{}",
527 as_terminal_escaped(
528 style,
529 &*format!(
530 "{}{}{}",
531 self.ansi_prefix_sgr, ansi_prefix, text
532 ),
533 self.config.true_color,
534 self.config.colored_output,
535 self.config.use_italic_text,
536 background_color
537 ),
538 panel_wrap.clone().unwrap()
539 )?;
540 }
542 // Clear the ANSI prefix buffer.
543 ansi_prefix.clear();
544 }
545 }
546 }
547 }
549 if let Some(background_color) = background_color {
550 let mut ansi_style = Style::default();
551 ansi_style.background =
552 Some(to_ansi_color(background_color, self.config.true_color));
554 write!(
555 handle,
556 "{}",
557 ansi_style.paint(" ".repeat(cursor_max - cursor))
558 )?;
559 }
560 writeln!(handle)?;
561 }
563 Ok(())
564 }
567const DEFAULT_GUTTER_COLOR: u8 = 238;
569#[derive(Debug, Default)]
570pub struct Colors {
571 pub grid: Style,
572 pub filename: Style,
573 pub git_added: Style,
574 pub git_removed: Style,
575 pub git_modified: Style,
576 pub line_number: Style,
579impl Colors {
580 fn plain() -> Self {
581 Colors::default()
582 }
584 fn colored(theme: &Theme, true_color: bool) -> Self {
585 let gutter_color = theme
586 .settings
587 .gutter_foreground
588 .map(|c| to_ansi_color(c, true_color))
589 .unwrap_or(Fixed(DEFAULT_GUTTER_COLOR));
591 Colors {
592 grid: gutter_color.normal(),
593 filename: Style::new().bold(),
594 git_added: Green.normal(),
595 git_removed: Red.normal(),
596 git_modified: Yellow.normal(),
597 line_number: gutter_color.normal(),
598 }
599 }