on v0.19.0 help sign in
bat/src/printer.rs
656 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, 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::vscreen::AnsiStyle;
34use crate::wrapping::WrappingMode;
36pub(crate) trait Printer {
37 fn print_header(
38 &mut self,
39 handle: &mut dyn Write,
40 input: &OpenedInput,
41 add_header_padding: bool,
42 ) -> Result<()>;
43 fn print_footer(&mut self, handle: &mut dyn Write, input: &OpenedInput) -> Result<()>;
45 fn print_snip(&mut self, handle: &mut dyn Write) -> Result<()>;
47 fn print_line(
48 &mut self,
49 out_of_range: bool,
50 handle: &mut dyn Write,
51 line_number: usize,
52 line_buffer: &[u8],
53 ) -> Result<()>;
56pub struct SimplePrinter<'a> {
57 config: &'a Config<'a>,
60impl<'a> SimplePrinter<'a> {
61 pub fn new(config: &'a Config) -> Self {
62 SimplePrinter { config }
63 }
66impl<'a> Printer for SimplePrinter<'a> {
67 fn print_header(
68 &mut self,
69 _handle: &mut dyn Write,
70 _input: &OpenedInput,
71 _add_header_padding: bool,
72 ) -> Result<()> {
73 Ok(())
74 }
76 fn print_footer(&mut self, _handle: &mut dyn Write, _input: &OpenedInput) -> Result<()> {
77 Ok(())
78 }
80 fn print_snip(&mut self, _handle: &mut dyn Write) -> Result<()> {
81 Ok(())
82 }
84 fn print_line(
85 &mut self,
86 out_of_range: bool,
87 handle: &mut dyn Write,
88 _line_number: usize,
89 line_buffer: &[u8],
90 ) -> Result<()> {
91 if !out_of_range {
92 if self.config.show_nonprintable {
93 let line = replace_nonprintable(line_buffer, self.config.tab_width);
94 write!(handle, "{}", line)?;
95 } else {
96 handle.write_all(line_buffer)?
97 };
98 }
99 Ok(())
100 }
103struct HighlighterFromSet<'a> {
104 highlighter: HighlightLines<'a>,
105 syntax_set: &'a SyntaxSet,
108impl<'a> HighlighterFromSet<'a> {
109 fn new(syntax_in_set: SyntaxReferenceInSet<'a>, theme: &'a Theme) -> Self {
110 Self {
111 highlighter: HighlightLines::new(syntax_in_set.syntax, theme),
112 syntax_set: syntax_in_set.syntax_set,
113 }
114 }
117pub(crate) struct InteractivePrinter<'a> {
118 colors: Colors,
119 config: &'a Config<'a>,
120 decorations: Vec<Box<dyn Decoration>>,
121 panel_width: usize,
122 ansi_style: AnsiStyle,
123 content_type: Option<ContentType>,
124 #[cfg(feature = "git")]
125 pub line_changes: &'a Option<LineChanges>,
126 highlighter_from_set: Option<HighlighterFromSet<'a>>,
127 background_color_highlight: Option<Color>,
130impl<'a> InteractivePrinter<'a> {
131 pub(crate) fn new(
132 config: &'a Config,
133 assets: &'a HighlightingAssets,
134 input: &mut OpenedInput,
135 #[cfg(feature = "git")] line_changes: &'a Option<LineChanges>,
136 ) -> Result<Self> {
137 let theme = assets.get_theme(&config.theme);
139 let background_color_highlight = theme.settings.line_highlight;
141 let colors = if config.colored_output {
142 Colors::colored(theme, config.true_color)
143 } else {
144 Colors::plain()
145 };
147 // Create decorations.
148 let mut decorations: Vec<Box<dyn Decoration>> = Vec::new();
150 if config.style_components.numbers() {
151 decorations.push(Box::new(LineNumberDecoration::new(&colors)));
152 }
154 #[cfg(feature = "git")]
155 {
156 if config.style_components.changes() {
157 decorations.push(Box::new(LineChangesDecoration::new(&colors)));
158 }
159 }
161 let mut panel_width: usize =
162 decorations.len() + decorations.iter().fold(0, |a, x| a + x.width());
164 // The grid border decoration isn't added until after the panel_width calculation, since the
165 // print_horizontal_line, print_header, and print_footer functions all assume the panel
166 // width is without the grid border.
167 if config.style_components.grid() && !decorations.is_empty() {
168 decorations.push(Box::new(GridBorderDecoration::new(&colors)));
169 }
171 // Disable the panel if the terminal is too small (i.e. can't fit 5 characters with the
172 // panel showing).
173 if config.term_width
174 < (decorations.len() + decorations.iter().fold(0, |a, x| a + x.width())) + 5
175 {
176 decorations.clear();
177 panel_width = 0;
178 }
180 let highlighter_from_set = if input
181 .reader
182 .content_type
183 .map_or(false, |c| c.is_binary() && !config.show_nonprintable)
184 {
185 None
186 } else {
187 // Determine the type of syntax for highlighting
188 let syntax_in_set =
189 match assets.get_syntax(config.language, input, &config.syntax_mapping) {
190 Ok(syntax_in_set) => syntax_in_set,
191 Err(Error::UndetectedSyntax(_)) => assets
192 .find_syntax_by_name("Plain Text")?
193 .expect("A plain text syntax is available"),
194 Err(e) => return Err(e),
195 };
197 Some(HighlighterFromSet::new(syntax_in_set, theme))
198 };
200 Ok(InteractivePrinter {
201 panel_width,
202 colors,
203 config,
204 decorations,
205 content_type: input.reader.content_type,
206 ansi_style: AnsiStyle::new(),
207 #[cfg(feature = "git")]
208 line_changes,
209 highlighter_from_set,
210 background_color_highlight,
211 })
212 }
214 fn print_horizontal_line_term(&mut self, handle: &mut dyn Write, style: Style) -> Result<()> {
215 writeln!(
216 handle,
217 "{}",
218 style.paint("─".repeat(self.config.term_width))
219 )?;
220 Ok(())
221 }
223 fn print_horizontal_line(&mut self, handle: &mut dyn Write, grid_char: char) -> Result<()> {
224 if self.panel_width == 0 {
225 self.print_horizontal_line_term(handle, self.colors.grid)?;
226 } else {
227 let hline = "─".repeat(self.config.term_width - (self.panel_width + 1));
228 let hline = format!("{}{}{}", "─".repeat(self.panel_width), grid_char, hline);
229 writeln!(handle, "{}", self.colors.grid.paint(hline))?;
230 }
232 Ok(())
233 }
235 fn create_fake_panel(&self, text: &str) -> String {
236 if self.panel_width == 0 {
237 return "".to_string();
238 }
240 let text_truncated: String = text.chars().take(self.panel_width - 1).collect();
241 let text_filled: String = format!(
242 "{}{}",
243 text_truncated,
244 " ".repeat(self.panel_width - 1 - text_truncated.len())
245 );
246 if self.config.style_components.grid() {
247 format!("{} │ ", text_filled)
248 } else {
249 text_filled
250 }
251 }
253 fn preprocess(&self, text: &str, cursor: &mut usize) -> String {
254 if self.config.tab_width > 0 {
255 return expand_tabs(text, self.config.tab_width, cursor);
256 }
258 *cursor += text.len();
259 text.to_string()
260 }
263impl<'a> Printer for InteractivePrinter<'a> {
264 fn print_header(
265 &mut self,
266 handle: &mut dyn Write,
267 input: &OpenedInput,
268 add_header_padding: bool,
269 ) -> Result<()> {
270 if add_header_padding && self.config.style_components.rule() {
271 self.print_horizontal_line_term(handle, self.colors.rule)?;
272 }
274 if !self.config.style_components.header() {
275 if Some(ContentType::BINARY) == self.content_type && !self.config.show_nonprintable {
276 writeln!(
277 handle,
278 "{}: Binary content from {} will not be printed to the terminal \
279 (but will be present if the output of 'bat' is piped). You can use 'bat -A' \
280 to show the binary file contents.",
281 Yellow.paint("[bat warning]"),
282 input.description.summary(),
283 )?;
284 } else if self.config.style_components.grid() {
285 self.print_horizontal_line(handle, '┬')?;
286 }
287 return Ok(());
288 }
290 if self.config.style_components.grid() {
291 self.print_horizontal_line(handle, '┬')?;
293 write!(
294 handle,
295 "{}{}",
296 " ".repeat(self.panel_width),
297 self.colors
298 .grid
299 .paint(if self.panel_width > 0 { "│ " } else { "" }),
300 )?;
301 } else {
302 // Only pad space between files, if we haven't already drawn a horizontal rule
303 if add_header_padding && !self.config.style_components.rule() {
304 writeln!(handle)?;
305 }
306 write!(handle, "{}", " ".repeat(self.panel_width))?;
307 }
309 let mode = match self.content_type {
310 Some(ContentType::BINARY) => " <BINARY>",
311 Some(ContentType::UTF_16LE) => " <UTF-16LE>",
312 Some(ContentType::UTF_16BE) => " <UTF-16BE>",
313 None => " <EMPTY>",
314 _ => "",
315 };
317 let description = &input.description;
319 writeln!(
320 handle,
321 "{}{}{}",
322 description
323 .kind()
324 .map(|kind| format!("{}: ", kind))
325 .unwrap_or_else(|| "".into()),
326 self.colors.filename.paint(description.title()),
327 mode
328 )?;
330 if self.config.style_components.grid() {
331 if self.content_type.map_or(false, |c| c.is_text()) || self.config.show_nonprintable {
332 self.print_horizontal_line(handle, '┼')?;
333 } else {
334 self.print_horizontal_line(handle, '┴')?;
335 }
336 }
338 Ok(())
339 }
341 fn print_footer(&mut self, handle: &mut dyn Write, _input: &OpenedInput) -> Result<()> {
342 if self.config.style_components.grid()
343 && (self.content_type.map_or(false, |c| c.is_text()) || self.config.show_nonprintable)
344 {
345 self.print_horizontal_line(handle, '┴')
346 } else {
347 Ok(())
348 }
349 }
351 fn print_snip(&mut self, handle: &mut dyn Write) -> Result<()> {
352 let panel = self.create_fake_panel(" ...");
353 let panel_count = panel.chars().count();
355 let title = "8<";
356 let title_count = title.chars().count();
358 let snip_left = "─ ".repeat((self.config.term_width - panel_count - (title_count / 2)) / 4);
359 let snip_left_count = snip_left.chars().count(); // Can't use .len() with Unicode.
361 let snip_right =
362 " ─".repeat((self.config.term_width - panel_count - snip_left_count - title_count) / 2);
364 writeln!(
365 handle,
366 "{}",
367 self.colors
368 .grid
369 .paint(format!("{}{}{}{}", panel, snip_left, title, snip_right))
370 )?;
372 Ok(())
373 }
375 fn print_line(
376 &mut self,
377 out_of_range: bool,
378 handle: &mut dyn Write,
379 line_number: usize,
380 line_buffer: &[u8],
381 ) -> Result<()> {
382 let line = if self.config.show_nonprintable {
383 replace_nonprintable(line_buffer, self.config.tab_width)
384 } else {
385 match self.content_type {
386 Some(ContentType::BINARY) | None => {
387 return Ok(());
388 }
389 Some(ContentType::UTF_16LE) => UTF_16LE
390 .decode(line_buffer, DecoderTrap::Replace)
391 .map_err(|_| "Invalid UTF-16LE")?,
392 Some(ContentType::UTF_16BE) => UTF_16BE
393 .decode(line_buffer, DecoderTrap::Replace)
394 .map_err(|_| "Invalid UTF-16BE")?,
395 _ => String::from_utf8_lossy(line_buffer).to_string(),
396 }
397 };
399 let regions = {
400 let highlighter_from_set = match self.highlighter_from_set {
401 Some(ref mut highlighter_from_set) => highlighter_from_set,
402 _ => {
403 return Ok(());
404 }
405 };
406 highlighter_from_set
407 .highlighter
408 .highlight(&line, highlighter_from_set.syntax_set)
409 };
411 if out_of_range {
412 return Ok(());
413 }
415 let mut cursor: usize = 0;
416 let mut cursor_max: usize = self.config.term_width;
417 let mut cursor_total: usize = 0;
418 let mut panel_wrap: Option<String> = None;
420 // Line highlighting
421 let highlight_this_line =
422 self.config.highlighted_lines.0.check(line_number) == RangeCheckResult::InRange;
424 let background_color = self
425 .background_color_highlight
426 .filter(|_| highlight_this_line);
428 // Line decorations.
429 if self.panel_width > 0 {
430 let decorations = self
431 .decorations
432 .iter()
433 .map(|d| d.generate(line_number, false, self));
435 for deco in decorations {
436 write!(handle, "{} ", deco.text)?;
437 cursor_max -= deco.width + 1;
438 }
439 }
441 // Line contents.
442 if matches!(self.config.wrapping_mode, WrappingMode::NoWrapping(_)) {
443 let true_color = self.config.true_color;
444 let colored_output = self.config.colored_output;
445 let italics = self.config.use_italic_text;
447 for &(style, region) in &regions {
448 let ansi_iterator = AnsiCodeIterator::new(region);
449 for chunk in ansi_iterator {
450 match chunk {
451 // ANSI escape passthrough.
452 (ansi, true) => {
453 self.ansi_style.update(ansi);
454 write!(handle, "{}", ansi)?;
455 }
457 // Regular text.
458 (text, false) => {
459 let text = &*self.preprocess(text, &mut cursor_total);
460 let text_trimmed = text.trim_end_matches(|c| c == '\r' || c == '\n');
462 write!(
463 handle,
464 "{}",
465 as_terminal_escaped(
466 style,
467 &format!("{}{}", self.ansi_style, text_trimmed),
468 true_color,
469 colored_output,
470 italics,
471 background_color
472 )
473 )?;
475 if text.len() != text_trimmed.len() {
476 if let Some(background_color) = background_color {
477 let ansi_style = Style {
478 background: to_ansi_color(background_color, true_color),
479 ..Default::default()
480 };
482 let width = if cursor_total <= cursor_max {
483 cursor_max - cursor_total + 1
484 } else {
485 0
486 };
487 write!(handle, "{}", ansi_style.paint(" ".repeat(width)))?;
488 }
489 write!(handle, "{}", &text[text_trimmed.len()..])?;
490 }
491 }
492 }
493 }
494 }
496 if !self.config.style_components.plain() && line.bytes().next_back() != Some(b'\n') {
497 writeln!(handle)?;
498 }
499 } else {
500 for &(style, region) in &regions {
501 let ansi_iterator = AnsiCodeIterator::new(region);
502 for chunk in ansi_iterator {
503 match chunk {
504 // ANSI escape passthrough.
505 (ansi, true) => {
506 self.ansi_style.update(ansi);
507 write!(handle, "{}", ansi)?;
508 }
510 // Regular text.
511 (text, false) => {
512 let text = self.preprocess(
513 text.trim_end_matches(|c| c == '\r' || c == '\n'),
514 &mut cursor_total,
515 );
517 let mut max_width = cursor_max - cursor;
519 // line buffer (avoid calling write! for every character)
520 let mut line_buf = String::with_capacity(max_width * 4);
522 // Displayed width of line_buf
523 let mut current_width = 0;
525 for c in text.chars() {
526 // calculate the displayed width for next character
527 let cw = c.width().unwrap_or(0);
528 current_width += cw;
530 // if next character cannot be printed on this line,
531 // flush the buffer.
532 if current_width > max_width {
533 // Generate wrap padding if not already generated.
534 if panel_wrap.is_none() {
535 panel_wrap = if self.panel_width > 0 {
536 Some(format!(
537 "{} ",
538 self.decorations
539 .iter()
540 .map(|d| d
541 .generate(line_number, true, self)
542 .text)
543 .collect::<Vec<String>>()
544 .join(" ")
545 ))
546 } else {
547 Some("".to_string())
548 }
549 }
551 // It wraps.
552 write!(
553 handle,
554 "{}\n{}",
555 as_terminal_escaped(
556 style,
557 &*format!("{}{}", self.ansi_style, line_buf),
558 self.config.true_color,
559 self.config.colored_output,
560 self.config.use_italic_text,
561 background_color
562 ),
563 panel_wrap.clone().unwrap()
564 )?;
566 cursor = 0;
567 max_width = cursor_max;
569 line_buf.clear();
570 current_width = cw;
571 }
573 line_buf.push(c);
574 }
576 // flush the buffer
577 cursor += current_width;
578 write!(
579 handle,
580 "{}",
581 as_terminal_escaped(
582 style,
583 &*format!("{}{}", self.ansi_style, line_buf),
584 self.config.true_color,
585 self.config.colored_output,
586 self.config.use_italic_text,
587 background_color
588 )
589 )?;
590 }
591 }
592 }
593 }
595 if let Some(background_color) = background_color {
596 let ansi_style = Style {
597 background: to_ansi_color(background_color, self.config.true_color),
598 ..Default::default()
599 };
601 write!(
602 handle,
603 "{}",
604 ansi_style.paint(" ".repeat(cursor_max - cursor))
605 )?;
606 }
607 writeln!(handle)?;
608 }
610 Ok(())
611 }
614const DEFAULT_GUTTER_COLOR: u8 = 238;
616#[derive(Debug, Default)]
617pub struct Colors {
618 pub grid: Style,
619 pub rule: Style,
620 pub filename: Style,
621 pub git_added: Style,
622 pub git_removed: Style,
623 pub git_modified: Style,
624 pub line_number: Style,
627impl Colors {
628 fn plain() -> Self {
629 Colors::default()
630 }
632 fn colored(theme: &Theme, true_color: bool) -> Self {
633 let gutter_style = Style {
634 foreground: match theme.settings.gutter_foreground {
635 // If the theme provides a gutter foreground color, use it.
636 // Note: It might be the special value #00000001, in which case
637 // to_ansi_color returns None and we use an empty Style
638 // (resulting in the terminal's default foreground color).
639 Some(c) => to_ansi_color(c, true_color),
640 // Otherwise, use a specific fallback color.
641 None => Some(Fixed(DEFAULT_GUTTER_COLOR)),
642 },
643 ..Style::default()
644 };
646 Colors {
647 grid: gutter_style,
648 rule: gutter_style,
649 filename: Style::new().bold(),
650 git_added: Green.normal(),
651 git_removed: Red.normal(),
652 git_modified: Yellow.normal(),
653 line_number: gutter_style,
654 }
655 }