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