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