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