on f5c1cb2 help sign in
bat/src/printer.rs
659 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 }
102pub(crate) struct InteractivePrinter<'a> {
103 colors: Colors,
104 config: &'a Config<'a>,
105 decorations: Vec<Box<dyn Decoration>>,
106 panel_width: usize,
107 ansi_prefix_sgr: String,
108 content_type: Option<ContentType>,
109 #[cfg(feature = "git")]
110 pub line_changes: &'a Option<LineChanges>,
111 highlighter: Option<HighlightLines<'a>>,
112 syntax_set: &'a SyntaxSet,
113 background_color_highlight: Option<Color>,
116impl<'a> InteractivePrinter<'a> {
117 pub(crate) fn new(
118 config: &'a Config,
119 assets: &'a HighlightingAssets,
120 input: &mut OpenedInput,
121 #[cfg(feature = "git")] line_changes: &'a Option<LineChanges>,
122 ) -> Result<Self> {
123 let theme = assets.get_theme(&config.theme);
125 let background_color_highlight = theme.settings.line_highlight;
127 let colors = if config.colored_output {
128 Colors::colored(theme, config.true_color)
129 } else {
130 Colors::plain()
131 };
133 // Create decorations.
134 let mut decorations: Vec<Box<dyn Decoration>> = Vec::new();
136 if config.style_components.numbers() {
137 decorations.push(Box::new(LineNumberDecoration::new(&colors)));
138 }
140 #[cfg(feature = "git")]
141 {
142 if config.style_components.changes() {
143 decorations.push(Box::new(LineChangesDecoration::new(&colors)));
144 }
145 }
147 let mut panel_width: usize =
148 decorations.len() + decorations.iter().fold(0, |a, x| a + x.width());
150 // The grid border decoration isn't added until after the panel_width calculation, since the
151 // print_horizontal_line, print_header, and print_footer functions all assume the panel
152 // width is without the grid border.
153 if config.style_components.grid() && !decorations.is_empty() {
154 decorations.push(Box::new(GridBorderDecoration::new(&colors)));
155 }
157 // Disable the panel if the terminal is too small (i.e. can't fit 5 characters with the
158 // panel showing).
159 if config.term_width
160 < (decorations.len() + decorations.iter().fold(0, |a, x| a + x.width())) + 5
161 {
162 decorations.clear();
163 panel_width = 0;
164 }
166 let (highlighter, syntax_set) = if input
167 .reader
168 .content_type
169 .map_or(false, |c| c.is_binary() && !config.show_nonprintable)
170 {
171 (None, assets.get_syntax_set()?)
172 } else {
173 // Determine the type of syntax for highlighting
174 let syntax_in_set =
175 match assets.get_syntax(config.language, input, &config.syntax_mapping) {
176 Ok(syntax_in_set) => syntax_in_set,
177 Err(Error(ErrorKind::UndetectedSyntax(_), _)) => {
178 let syntax_set = assets.get_syntax_set()?;
179 let syntax = syntax_set.find_syntax_plain_text();
180 SyntaxReferenceInSet { syntax, syntax_set }
181 }
182 Err(e) => return Err(e),
183 };
185 (
186 Some(HighlightLines::new(syntax_in_set.syntax, theme)),
187 syntax_in_set.syntax_set,
188 )
189 };
191 Ok(InteractivePrinter {
192 panel_width,
193 colors,
194 config,
195 decorations,
196 content_type: input.reader.content_type,
197 ansi_prefix_sgr: String::new(),
198 #[cfg(feature = "git")]
199 line_changes,
200 highlighter,
201 syntax_set,
202 background_color_highlight,
203 })
204 }
206 fn print_horizontal_line_term(&mut self, handle: &mut dyn Write, style: Style) -> Result<()> {
207 writeln!(
208 handle,
209 "{}",
210 style.paint("─".repeat(self.config.term_width))
211 )?;
212 Ok(())
213 }
215 fn print_horizontal_line(&mut self, handle: &mut dyn Write, grid_char: char) -> Result<()> {
216 if self.panel_width == 0 {
217 self.print_horizontal_line_term(handle, self.colors.grid)?;
218 } else {
219 let hline = "─".repeat(self.config.term_width - (self.panel_width + 1));
220 let hline = format!("{}{}{}", "─".repeat(self.panel_width), grid_char, hline);
221 writeln!(handle, "{}", self.colors.grid.paint(hline))?;
222 }
224 Ok(())
225 }
227 fn create_fake_panel(&self, text: &str) -> String {
228 if self.panel_width == 0 {
229 "".to_string()
230 } else {
231 let text_truncated: String = text.chars().take(self.panel_width - 1).collect();
232 let text_filled: String = format!(
233 "{}{}",
234 text_truncated,
235 " ".repeat(self.panel_width - 1 - text_truncated.len())
236 );
237 if self.config.style_components.grid() {
238 format!("{} │ ", text_filled)
239 } else {
240 text_filled
241 }
242 }
243 }
245 fn preprocess(&self, text: &str, cursor: &mut usize) -> String {
246 if self.config.tab_width > 0 {
247 expand_tabs(text, self.config.tab_width, cursor)
248 } else {
249 *cursor += text.len();
250 text.to_string()
251 }
252 }
255impl<'a> Printer for InteractivePrinter<'a> {
256 fn print_header(
257 &mut self,
258 handle: &mut dyn Write,
259 input: &OpenedInput,
260 add_header_padding: bool,
261 ) -> Result<()> {
262 if add_header_padding && self.config.style_components.rule() {
263 self.print_horizontal_line_term(handle, self.colors.rule)?;
264 }
266 if !self.config.style_components.header() {
267 if Some(ContentType::BINARY) == self.content_type && !self.config.show_nonprintable {
268 writeln!(
269 handle,
270 "{}: Binary content from {} will not be printed to the terminal \
271 (but will be present if the output of 'bat' is piped). You can use 'bat -A' \
272 to show the binary file contents.",
273 Yellow.paint("[bat warning]"),
274 input.description.summary(),
275 )?;
276 } else if self.config.style_components.grid() {
277 self.print_horizontal_line(handle, '┬')?;
278 }
279 return Ok(());
280 }
282 if self.config.style_components.grid() {
283 self.print_horizontal_line(handle, '┬')?;
285 write!(
286 handle,
287 "{}{}",
288 " ".repeat(self.panel_width),
289 self.colors
290 .grid
291 .paint(if self.panel_width > 0 { "│ " } else { "" }),
292 )?;
293 } else {
294 // Only pad space between files, if we haven't already drawn a horizontal rule
295 if add_header_padding && !self.config.style_components.rule() {
296 writeln!(handle)?;
297 }
298 write!(handle, "{}", " ".repeat(self.panel_width))?;
299 }
301 let mode = match self.content_type {
302 Some(ContentType::BINARY) => " <BINARY>",
303 Some(ContentType::UTF_16LE) => " <UTF-16LE>",
304 Some(ContentType::UTF_16BE) => " <UTF-16BE>",
305 None => " <EMPTY>",
306 _ => "",
307 };
309 let description = &input.description;
311 writeln!(
312 handle,
313 "{}{}{}",
314 description
315 .kind()
316 .map(|kind| format!("{}: ", kind))
317 .unwrap_or_else(|| "".into()),
318 self.colors.filename.paint(description.title()),
319 mode
320 )?;
322 if self.config.style_components.grid() {
323 if self.content_type.map_or(false, |c| c.is_text()) || self.config.show_nonprintable {
324 self.print_horizontal_line(handle, '┼')?;
325 } else {
326 self.print_horizontal_line(handle, '┴')?;
327 }
328 }
330 Ok(())
331 }
333 fn print_footer(&mut self, handle: &mut dyn Write, _input: &OpenedInput) -> Result<()> {
334 if self.config.style_components.grid()
335 && (self.content_type.map_or(false, |c| c.is_text()) || self.config.show_nonprintable)
336 {
337 self.print_horizontal_line(handle, '┴')
338 } else {
339 Ok(())
340 }
341 }
343 fn print_snip(&mut self, handle: &mut dyn Write) -> Result<()> {
344 let panel = self.create_fake_panel(" ...");
345 let panel_count = panel.chars().count();
347 let title = "8<";
348 let title_count = title.chars().count();
350 let snip_left = "─ ".repeat((self.config.term_width - panel_count - (title_count / 2)) / 4);
351 let snip_left_count = snip_left.chars().count(); // Can't use .len() with Unicode.
353 let snip_right =
354 " ─".repeat((self.config.term_width - panel_count - snip_left_count - title_count) / 2);
356 writeln!(
357 handle,
358 "{}",
359 self.colors
360 .grid
361 .paint(format!("{}{}{}{}", panel, snip_left, title, snip_right))
362 )?;
364 Ok(())
365 }
367 fn print_line(
368 &mut self,
369 out_of_range: bool,
370 handle: &mut dyn Write,
371 line_number: usize,
372 line_buffer: &[u8],
373 ) -> Result<()> {
374 let line = if self.config.show_nonprintable {
375 replace_nonprintable(&line_buffer, self.config.tab_width)
376 } else {
377 match self.content_type {
378 Some(ContentType::BINARY) | None => {
379 return Ok(());
380 }
381 Some(ContentType::UTF_16LE) => UTF_16LE
382 .decode(&line_buffer, DecoderTrap::Replace)
383 .map_err(|_| "Invalid UTF-16LE")?,
384 Some(ContentType::UTF_16BE) => UTF_16BE
385 .decode(&line_buffer, DecoderTrap::Replace)
386 .map_err(|_| "Invalid UTF-16BE")?,
387 _ => String::from_utf8_lossy(&line_buffer).to_string(),
388 }
389 };
391 let regions = {
392 let highlighter = match self.highlighter {
393 Some(ref mut highlighter) => highlighter,
394 _ => {
395 return Ok(());
396 }
397 };
398 highlighter.highlight(line.as_ref(), self.syntax_set)
399 };
401 if out_of_range {
402 return Ok(());
403 }
405 let mut cursor: usize = 0;
406 let mut cursor_max: usize = self.config.term_width;
407 let mut cursor_total: usize = 0;
408 let mut panel_wrap: Option<String> = None;
410 // Line highlighting
411 let highlight_this_line =
412 self.config.highlighted_lines.0.check(line_number) == RangeCheckResult::InRange;
414 let background_color = self
415 .background_color_highlight
416 .filter(|_| highlight_this_line);
418 // Line decorations.
419 if self.panel_width > 0 {
420 let decorations = self
421 .decorations
422 .iter()
423 .map(|ref d| d.generate(line_number, false, self))
424 .collect::<Vec<_>>();
426 for deco in decorations {
427 write!(handle, "{} ", deco.text)?;
428 cursor_max -= deco.width + 1;
429 }
430 }
432 // Line contents.
433 if matches!(self.config.wrapping_mode, WrappingMode::NoWrapping(_)) {
434 let true_color = self.config.true_color;
435 let colored_output = self.config.colored_output;
436 let italics = self.config.use_italic_text;
438 for &(style, region) in regions.iter() {
439 let text = &*self.preprocess(region, &mut cursor_total);
440 let text_trimmed = text.trim_end_matches(|c| c == '\r' || c == '\n');
441 write!(
442 handle,
443 "{}",
444 as_terminal_escaped(
445 style,
446 text_trimmed,
447 true_color,
448 colored_output,
449 italics,
450 background_color
451 )
452 )?;
454 if text.len() != text_trimmed.len() {
455 if let Some(background_color) = background_color {
456 let ansi_style = Style {
457 background: to_ansi_color(background_color, true_color),
458 ..Default::default()
459 };
460 let width = if cursor_total <= cursor_max {
461 cursor_max - cursor_total + 1
462 } else {
463 0
464 };
465 write!(handle, "{}", ansi_style.paint(" ".repeat(width)))?;
466 }
467 write!(handle, "{}", &text[text_trimmed.len()..])?;
468 }
469 }
471 if !self.config.style_components.plain() && line.bytes().next_back() != Some(b'\n') {
472 writeln!(handle)?;
473 }
474 } else {
475 for &(style, region) in regions.iter() {
476 let ansi_iterator = AnsiCodeIterator::new(region);
477 let mut ansi_prefix: String = String::new();
478 for chunk in ansi_iterator {
479 match chunk {
480 // ANSI escape passthrough.
481 (text, true) => {
482 let is_ansi_csi = text.starts_with("\x1B[");
484 if is_ansi_csi && text.ends_with('m') {
485 // It's an ANSI SGR sequence.
486 // We should be mostly safe to just append these together.
487 ansi_prefix.push_str(text);
488 if text == "\x1B[0m" {
489 self.ansi_prefix_sgr = "\x1B[0m".to_owned();
490 } else {
491 self.ansi_prefix_sgr.push_str(text);
492 }
493 } else if is_ansi_csi {
494 // It's a regular CSI sequence.
495 // We should be mostly safe to just append these together.
496 ansi_prefix.push_str(text);
497 } else {
498 // It's probably a VT100 code.
499 // Passing it through is the safest bet.
500 write!(handle, "{}", text)?;
501 }
502 }
504 // Regular text.
505 (text, false) => {
506 let text = self.preprocess(
507 text.trim_end_matches(|c| c == '\r' || c == '\n'),
508 &mut cursor_total,
509 );
511 let mut max_width = cursor_max - cursor;
513 // line buffer (avoid calling write! for every character)
514 let mut line_buf = String::with_capacity(max_width * 4);
516 // Displayed width of line_buf
517 let mut current_width = 0;
519 for c in text.chars() {
520 // calculate the displayed width for next character
521 let cw = c.width().unwrap_or(0);
522 current_width += cw;
524 // if next character cannot be printed on this line,
525 // flush the buffer.
526 if current_width > max_width {
527 // Generate wrap padding if not already generated.
528 if panel_wrap.is_none() {
529 panel_wrap = if self.panel_width > 0 {
530 Some(format!(
531 "{} ",
532 self.decorations
533 .iter()
534 .map(|ref d| d
535 .generate(line_number, true, self)
536 .text)
537 .collect::<Vec<String>>()
538 .join(" ")
539 ))
540 } else {
541 Some("".to_string())
542 }
543 }
545 // It wraps.
546 write!(
547 handle,
548 "{}\n{}",
549 as_terminal_escaped(
550 style,
551 &*format!(
552 "{}{}{}",
553 self.ansi_prefix_sgr, ansi_prefix, line_buf
554 ),
555 self.config.true_color,
556 self.config.colored_output,
557 self.config.use_italic_text,
558 background_color
559 ),
560 panel_wrap.clone().unwrap()
561 )?;
563 cursor = 0;
564 max_width = cursor_max;
566 line_buf.clear();
567 current_width = cw;
568 }
570 line_buf.push(c);
571 }
573 // flush the buffer
574 cursor += current_width;
575 write!(
576 handle,
577 "{}",
578 as_terminal_escaped(
579 style,
580 &*format!(
581 "{}{}{}",
582 self.ansi_prefix_sgr, ansi_prefix, line_buf
583 ),
584 self.config.true_color,
585 self.config.colored_output,
586 self.config.use_italic_text,
587 background_color
588 )
589 )?;
591 // Clear the ANSI prefix buffer.
592 ansi_prefix.clear();
593 }
594 }
595 }
596 }
598 if let Some(background_color) = background_color {
599 let ansi_style = Style {
600 background: to_ansi_color(background_color, self.config.true_color),
601 ..Default::default()
602 };
604 write!(
605 handle,
606 "{}",
607 ansi_style.paint(" ".repeat(cursor_max - cursor))
608 )?;
609 }
610 writeln!(handle)?;
611 }
613 Ok(())
614 }
617const DEFAULT_GUTTER_COLOR: u8 = 238;
619#[derive(Debug, Default)]
620pub struct Colors {
621 pub grid: Style,
622 pub rule: Style,
623 pub filename: Style,
624 pub git_added: Style,
625 pub git_removed: Style,
626 pub git_modified: Style,
627 pub line_number: Style,
630impl Colors {
631 fn plain() -> Self {
632 Colors::default()
633 }
635 fn colored(theme: &Theme, true_color: bool) -> Self {
636 let gutter_style = Style {
637 foreground: match theme.settings.gutter_foreground {
638 // If the theme provides a gutter foreground color, use it.
639 // Note: It might be the special value #00000001, in which case
640 // to_ansi_color returns None and we use an empty Style
641 // (resulting in the terminal's default foreground color).
642 Some(c) => to_ansi_color(c, true_color),
643 // Otherwise, use a specific fallback color.
644 None => Some(Fixed(DEFAULT_GUTTER_COLOR)),
645 },
646 ..Style::default()
647 };
649 Colors {
650 grid: gutter_style,
651 rule: gutter_style,
652 filename: Style::new().bold(),
653 git_added: Green.normal(),
654 git_removed: Red.normal(),
655 git_modified: Yellow.normal(),
656 line_number: gutter_style,
657 }
658 }