on 0b63ad5 help sign in
bat/src/printer.rs
667 lines 24 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 unicode_width::UnicodeWidthChar;
21use crate::assets::{HighlightingAssets, SyntaxReferenceInSet};
22use crate::config::Config;
23#[cfg(feature = "git")]
24use crate::decorations::LineChangesDecoration;
25use crate::decorations::{Decoration, GridBorderDecoration, LineNumberDecoration};
26#[cfg(feature = "git")]
27use crate::diff::LineChanges;
28use crate::error::*;
29use crate::input::OpenedInput;
30use crate::line_range::RangeCheckResult;
31use crate::preprocessor::{expand_tabs, replace_nonprintable};
32use crate::terminal::{as_terminal_escaped, to_ansi_color};
33use crate::wrapping::WrappingMode;
35pub(crate) trait Printer {
36 fn print_header(
37 &mut self,
38 handle: &mut dyn Write,
39 input: &OpenedInput,
40 add_header_padding: bool,
41 ) -> Result<()>;
42 fn print_footer(&mut self, handle: &mut dyn Write, input: &OpenedInput) -> Result<()>;
44 fn print_snip(&mut self, handle: &mut dyn Write) -> Result<()>;
46 fn print_line(
47 &mut self,
48 out_of_range: bool,
49 handle: &mut dyn Write,
50 line_number: usize,
51 line_buffer: &[u8],
52 ) -> Result<()>;
55pub struct SimplePrinter<'a> {
56 config: &'a Config<'a>,
59impl<'a> SimplePrinter<'a> {
60 pub fn new(config: &'a Config) -> Self {
61 SimplePrinter { config }
62 }
65impl<'a> Printer for SimplePrinter<'a> {
66 fn print_header(
67 &mut self,
68 _handle: &mut dyn Write,
69 _input: &OpenedInput,
70 _add_header_padding: bool,
71 ) -> Result<()> {
72 Ok(())
73 }
75 fn print_footer(&mut self, _handle: &mut dyn Write, _input: &OpenedInput) -> Result<()> {
76 Ok(())
77 }
79 fn print_snip(&mut self, _handle: &mut dyn Write) -> Result<()> {
80 Ok(())
81 }
83 fn print_line(
84 &mut self,
85 out_of_range: bool,
86 handle: &mut dyn Write,
87 _line_number: usize,
88 line_buffer: &[u8],
89 ) -> Result<()> {
90 if !out_of_range {
91 if self.config.show_nonprintable {
92 let line = replace_nonprintable(line_buffer, self.config.tab_width);
93 write!(handle, "{}", line)?;
94 } else {
95 handle.write_all(line_buffer)?
96 };
97 }
98 Ok(())
99 }
102struct HighlighterFromSet<'a> {
103 highlighter: HighlightLines<'a>,
104 syntax_set: &'a SyntaxSet,
107impl<'a> HighlighterFromSet<'a> {
108 fn new(syntax_in_set: SyntaxReferenceInSet<'a>, theme: &'a Theme) -> Self {
109 Self {
110 highlighter: HighlightLines::new(syntax_in_set.syntax, theme),
111 syntax_set: syntax_in_set.syntax_set,
112 }
113 }
116pub(crate) struct InteractivePrinter<'a> {
117 colors: Colors,
118 config: &'a Config<'a>,
119 decorations: Vec<Box<dyn Decoration>>,
120 panel_width: usize,
121 ansi_prefix_sgr: String,
122 content_type: Option<ContentType>,
123 #[cfg(feature = "git")]
124 pub line_changes: &'a Option<LineChanges>,
125 highlighter_from_set: Option<HighlighterFromSet<'a>>,
126 background_color_highlight: Option<Color>,
129impl<'a> InteractivePrinter<'a> {
130 pub(crate) fn new(
131 config: &'a Config,
132 assets: &'a HighlightingAssets,
133 input: &mut OpenedInput,
134 #[cfg(feature = "git")] line_changes: &'a Option<LineChanges>,
135 ) -> Result<Self> {
136 let theme = assets.get_theme(&config.theme);
138 let background_color_highlight = theme.settings.line_highlight;
140 let colors = if config.colored_output {
141 Colors::colored(theme, config.true_color)
142 } else {
143 Colors::plain()
144 };
146 // Create decorations.
147 let mut decorations: Vec<Box<dyn Decoration>> = Vec::new();
149 if config.style_components.numbers() {
150 decorations.push(Box::new(LineNumberDecoration::new(&colors)));
151 }
153 #[cfg(feature = "git")]
154 {
155 if config.style_components.changes() {
156 decorations.push(Box::new(LineChangesDecoration::new(&colors)));
157 }
158 }
160 let mut panel_width: usize =
161 decorations.len() + decorations.iter().fold(0, |a, x| a + x.width());
163 // The grid border decoration isn't added until after the panel_width calculation, since the
164 // print_horizontal_line, print_header, and print_footer functions all assume the panel
165 // width is without the grid border.
166 if config.style_components.grid() && !decorations.is_empty() {
167 decorations.push(Box::new(GridBorderDecoration::new(&colors)));
168 }
170 // Disable the panel if the terminal is too small (i.e. can't fit 5 characters with the
171 // panel showing).
172 if config.term_width
173 < (decorations.len() + decorations.iter().fold(0, |a, x| a + x.width())) + 5
174 {
175 decorations.clear();
176 panel_width = 0;
177 }
179 let highlighter_from_set = if input
180 .reader
181 .content_type
182 .map_or(false, |c| c.is_binary() && !config.show_nonprintable)
183 {
184 None
185 } else {
186 // Determine the type of syntax for highlighting
187 let syntax_in_set =
188 match assets.get_syntax(config.language, input, &config.syntax_mapping) {
189 Ok(syntax_in_set) => syntax_in_set,
190 Err(Error::UndetectedSyntax(_)) => assets
191 .find_syntax_by_name("Plain Text")?
192 .expect("A plain text syntax is available"),
193 Err(e) => return Err(e),
194 };
196 Some(HighlighterFromSet::new(syntax_in_set, theme))
197 };
199 Ok(InteractivePrinter {
200 panel_width,
201 colors,
202 config,
203 decorations,
204 content_type: input.reader.content_type,
205 ansi_prefix_sgr: String::new(),
206 #[cfg(feature = "git")]
207 line_changes,
208 highlighter_from_set,
209 background_color_highlight,
210 })
211 }
213 fn print_horizontal_line_term(&mut self, handle: &mut dyn Write, style: Style) -> Result<()> {
214 writeln!(
215 handle,
216 "{}",
217 style.paint("─".repeat(self.config.term_width))
218 )?;
219 Ok(())
220 }
222 fn print_horizontal_line(&mut self, handle: &mut dyn Write, grid_char: char) -> Result<()> {
223 if self.panel_width == 0 {
224 self.print_horizontal_line_term(handle, self.colors.grid)?;
225 } else {
226 let hline = "─".repeat(self.config.term_width - (self.panel_width + 1));
227 let hline = format!("{}{}{}", "─".repeat(self.panel_width), grid_char, hline);
228 writeln!(handle, "{}", self.colors.grid.paint(hline))?;
229 }
231 Ok(())
232 }
234 fn create_fake_panel(&self, text: &str) -> String {
235 if self.panel_width == 0 {
236 return "".to_string();
237 }
239 let text_truncated: String = text.chars().take(self.panel_width - 1).collect();
240 let text_filled: String = format!(
241 "{}{}",
242 text_truncated,
243 " ".repeat(self.panel_width - 1 - text_truncated.len())
244 );
245 if self.config.style_components.grid() {
246 format!("{} │ ", text_filled)
247 } else {
248 text_filled
249 }
250 }
252 fn preprocess(&self, text: &str, cursor: &mut usize) -> String {
253 if self.config.tab_width > 0 {
254 return expand_tabs(text, self.config.tab_width, cursor);
255 }
257 *cursor += text.len();
258 text.to_string()
259 }
262impl<'a> Printer for InteractivePrinter<'a> {
263 fn print_header(
264 &mut self,
265 handle: &mut dyn Write,
266 input: &OpenedInput,
267 add_header_padding: bool,
268 ) -> Result<()> {
269 if add_header_padding && self.config.style_components.rule() {
270 self.print_horizontal_line_term(handle, self.colors.rule)?;
271 }
273 if !self.config.style_components.header() {
274 if Some(ContentType::BINARY) == self.content_type && !self.config.show_nonprintable {
275 writeln!(
276 handle,
277 "{}: Binary content from {} will not be printed to the terminal \
278 (but will be present if the output of 'bat' is piped). You can use 'bat -A' \
279 to show the binary file contents.",
280 Yellow.paint("[bat warning]"),
281 input.description.summary(),
282 )?;
283 } else if self.config.style_components.grid() {
284 self.print_horizontal_line(handle, '┬')?;
285 }
286 return Ok(());
287 }
289 if self.config.style_components.grid() {
290 self.print_horizontal_line(handle, '┬')?;
292 write!(
293 handle,
294 "{}{}",
295 " ".repeat(self.panel_width),
296 self.colors
297 .grid
298 .paint(if self.panel_width > 0 { "│ " } else { "" }),
299 )?;
300 } else {
301 // Only pad space between files, if we haven't already drawn a horizontal rule
302 if add_header_padding && !self.config.style_components.rule() {
303 writeln!(handle)?;
304 }
305 write!(handle, "{}", " ".repeat(self.panel_width))?;
306 }
308 let mode = match self.content_type {
309 Some(ContentType::BINARY) => " <BINARY>",
310 Some(ContentType::UTF_16LE) => " <UTF-16LE>",
311 Some(ContentType::UTF_16BE) => " <UTF-16BE>",
312 None => " <EMPTY>",
313 _ => "",
314 };
316 let description = &input.description;
318 writeln!(
319 handle,
320 "{}{}{}",
321 description
322 .kind()
323 .map(|kind| format!("{}: ", kind))
324 .unwrap_or_else(|| "".into()),
325 self.colors.filename.paint(description.title()),
326 mode
327 )?;
329 if self.config.style_components.grid() {
330 if self.content_type.map_or(false, |c| c.is_text()) || self.config.show_nonprintable {
331 self.print_horizontal_line(handle, '┼')?;
332 } else {
333 self.print_horizontal_line(handle, '┴')?;
334 }
335 }
337 Ok(())
338 }
340 fn print_footer(&mut self, handle: &mut dyn Write, _input: &OpenedInput) -> Result<()> {
341 if self.config.style_components.grid()
342 && (self.content_type.map_or(false, |c| c.is_text()) || self.config.show_nonprintable)
343 {
344 self.print_horizontal_line(handle, '┴')
345 } else {
346 Ok(())
347 }
348 }
350 fn print_snip(&mut self, handle: &mut dyn Write) -> Result<()> {
351 let panel = self.create_fake_panel(" ...");
352 let panel_count = panel.chars().count();
354 let title = "8<";
355 let title_count = title.chars().count();
357 let snip_left = "─ ".repeat((self.config.term_width - panel_count - (title_count / 2)) / 4);
358 let snip_left_count = snip_left.chars().count(); // Can't use .len() with Unicode.
360 let snip_right =
361 " ─".repeat((self.config.term_width - panel_count - snip_left_count - title_count) / 2);
363 writeln!(
364 handle,
365 "{}",
366 self.colors
367 .grid
368 .paint(format!("{}{}{}{}", panel, snip_left, title, snip_right))
369 )?;
371 Ok(())
372 }
374 fn print_line(
375 &mut self,
376 out_of_range: bool,
377 handle: &mut dyn Write,
378 line_number: usize,
379 line_buffer: &[u8],
380 ) -> Result<()> {
381 let line = if self.config.show_nonprintable {
382 replace_nonprintable(line_buffer, self.config.tab_width)
383 } else {
384 match self.content_type {
385 Some(ContentType::BINARY) | None => {
386 return Ok(());
387 }
388 Some(ContentType::UTF_16LE) => UTF_16LE
389 .decode(line_buffer, DecoderTrap::Replace)
390 .map_err(|_| "Invalid UTF-16LE")?,
391 Some(ContentType::UTF_16BE) => UTF_16BE
392 .decode(line_buffer, DecoderTrap::Replace)
393 .map_err(|_| "Invalid UTF-16BE")?,
394 _ => String::from_utf8_lossy(line_buffer).to_string(),
395 }
396 };
398 let regions = {
399 let highlighter_from_set = match self.highlighter_from_set {
400 Some(ref mut highlighter_from_set) => highlighter_from_set,
401 _ => {
402 return Ok(());
403 }
404 };
405 highlighter_from_set
406 .highlighter
407 .highlight(&line, highlighter_from_set.syntax_set)
408 };
410 if out_of_range {
411 return Ok(());
412 }
414 let mut cursor: usize = 0;
415 let mut cursor_max: usize = self.config.term_width;
416 let mut cursor_total: usize = 0;
417 let mut panel_wrap: Option<String> = None;
419 // Line highlighting
420 let highlight_this_line =
421 self.config.highlighted_lines.0.check(line_number) == RangeCheckResult::InRange;
423 let background_color = self
424 .background_color_highlight
425 .filter(|_| highlight_this_line);
427 // Line decorations.
428 if self.panel_width > 0 {
429 let decorations = self
430 .decorations
431 .iter()
432 .map(|d| d.generate(line_number, false, self));
434 for deco in decorations {
435 write!(handle, "{} ", deco.text)?;
436 cursor_max -= deco.width + 1;
437 }
438 }
440 // Line contents.
441 if matches!(self.config.wrapping_mode, WrappingMode::NoWrapping(_)) {
442 let true_color = self.config.true_color;
443 let colored_output = self.config.colored_output;
444 let italics = self.config.use_italic_text;
446 for &(style, region) in &regions {
447 let text = &*self.preprocess(region, &mut cursor_total);
448 let text_trimmed = text.trim_end_matches(|c| c == '\r' || c == '\n');
449 write!(
450 handle,
451 "{}",
452 as_terminal_escaped(
453 style,
454 text_trimmed,
455 true_color,
456 colored_output,
457 italics,
458 background_color
459 )
460 )?;
462 if text.len() != text_trimmed.len() {
463 if let Some(background_color) = background_color {
464 let ansi_style = Style {
465 background: to_ansi_color(background_color, true_color),
466 ..Default::default()
467 };
468 let width = if cursor_total <= cursor_max {
469 cursor_max - cursor_total + 1
470 } else {
471 0
472 };
473 write!(handle, "{}", ansi_style.paint(" ".repeat(width)))?;
474 }
475 write!(handle, "{}", &text[text_trimmed.len()..])?;
476 }
477 }
479 if !self.config.style_components.plain() && line.bytes().next_back() != Some(b'\n') {
480 writeln!(handle)?;
481 }
482 } else {
483 for &(style, region) in &regions {
484 let ansi_iterator = AnsiCodeIterator::new(region);
485 let mut ansi_prefix: String = String::new();
486 for chunk in ansi_iterator {
487 match chunk {
488 // ANSI escape passthrough.
489 (text, true) => {
490 let is_ansi_csi = text.starts_with("\x1B[");
492 if is_ansi_csi && text.ends_with('m') {
493 // It's an ANSI SGR sequence.
494 // We should be mostly safe to just append these together.
495 ansi_prefix.push_str(text);
496 if text == "\x1B[0m" {
497 self.ansi_prefix_sgr = "\x1B[0m".to_owned();
498 } else {
499 self.ansi_prefix_sgr.push_str(text);
500 }
501 } else if is_ansi_csi {
502 // It's a regular CSI sequence.
503 // We should be mostly safe to just append these together.
504 ansi_prefix.push_str(text);
505 } else {
506 // It's probably a VT100 code.
507 // Passing it through is the safest bet.
508 write!(handle, "{}", text)?;
509 }
510 }
512 // Regular text.
513 (text, false) => {
514 let text = self.preprocess(
515 text.trim_end_matches(|c| c == '\r' || c == '\n'),
516 &mut cursor_total,
517 );
519 let mut max_width = cursor_max - cursor;
521 // line buffer (avoid calling write! for every character)
522 let mut line_buf = String::with_capacity(max_width * 4);
524 // Displayed width of line_buf
525 let mut current_width = 0;
527 for c in text.chars() {
528 // calculate the displayed width for next character
529 let cw = c.width().unwrap_or(0);
530 current_width += cw;
532 // if next character cannot be printed on this line,
533 // flush the buffer.
534 if current_width > max_width {
535 // Generate wrap padding if not already generated.
536 if panel_wrap.is_none() {
537 panel_wrap = if self.panel_width > 0 {
538 Some(format!(
539 "{} ",
540 self.decorations
541 .iter()
542 .map(|d| d
543 .generate(line_number, true, self)
544 .text)
545 .collect::<Vec<String>>()
546 .join(" ")
547 ))
548 } else {
549 Some("".to_string())
550 }
551 }
553 // It wraps.
554 write!(
555 handle,
556 "{}\n{}",
557 as_terminal_escaped(
558 style,
559 &*format!(
560 "{}{}{}",
561 self.ansi_prefix_sgr, ansi_prefix, line_buf
562 ),
563 self.config.true_color,
564 self.config.colored_output,
565 self.config.use_italic_text,
566 background_color
567 ),
568 panel_wrap.clone().unwrap()
569 )?;
571 cursor = 0;
572 max_width = cursor_max;
574 line_buf.clear();
575 current_width = cw;
576 }
578 line_buf.push(c);
579 }
581 // flush the buffer
582 cursor += current_width;
583 write!(
584 handle,
585 "{}",
586 as_terminal_escaped(
587 style,
588 &*format!(
589 "{}{}{}",
590 self.ansi_prefix_sgr, ansi_prefix, line_buf
591 ),
592 self.config.true_color,
593 self.config.colored_output,
594 self.config.use_italic_text,
595 background_color
596 )
597 )?;
599 // Clear the ANSI prefix buffer.
600 ansi_prefix.clear();
601 }
602 }
603 }
604 }
606 if let Some(background_color) = background_color {
607 let ansi_style = Style {
608 background: to_ansi_color(background_color, self.config.true_color),
609 ..Default::default()
610 };
612 write!(
613 handle,
614 "{}",
615 ansi_style.paint(" ".repeat(cursor_max - cursor))
616 )?;
617 }
618 writeln!(handle)?;
619 }
621 Ok(())
622 }
625const DEFAULT_GUTTER_COLOR: u8 = 238;
627#[derive(Debug, Default)]
628pub struct Colors {
629 pub grid: Style,
630 pub rule: Style,
631 pub filename: Style,
632 pub git_added: Style,
633 pub git_removed: Style,
634 pub git_modified: Style,
635 pub line_number: Style,
638impl Colors {
639 fn plain() -> Self {
640 Colors::default()
641 }
643 fn colored(theme: &Theme, true_color: bool) -> Self {
644 let gutter_style = Style {
645 foreground: match theme.settings.gutter_foreground {
646 // If the theme provides a gutter foreground color, use it.
647 // Note: It might be the special value #00000001, in which case
648 // to_ansi_color returns None and we use an empty Style
649 // (resulting in the terminal's default foreground color).
650 Some(c) => to_ansi_color(c, true_color),
651 // Otherwise, use a specific fallback color.
652 None => Some(Fixed(DEFAULT_GUTTER_COLOR)),
653 },
654 ..Style::default()
655 };
657 Colors {
658 grid: gutter_style,
659 rule: gutter_style,
660 filename: Style::new().bold(),
661 git_added: Green.normal(),
662 git_removed: Red.normal(),
663 git_modified: Yellow.normal(),
664 line_number: gutter_style,
665 }
666 }