on 3d07dec help sign in
bat/src/printer.rs
649 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 } 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 = if input
167 .reader
168 .content_type
169 .map_or(false, |c| c.is_binary() && !config.show_nonprintable)
170 {
171 None
172 } else {
173 // Determine the type of syntax for highlighting
174 let syntax = match assets.get_syntax(config.language, input, &config.syntax_mapping) {
175 Ok(syntax) => syntax,
176 Err(Error(ErrorKind::UndetectedSyntax(_), _)) => {
177 assets.syntax_set.find_syntax_plain_text()
178 }
179 Err(e) => return Err(e),
180 };
182 Some(HighlightLines::new(syntax, theme))
183 };
185 Ok(InteractivePrinter {
186 panel_width,
187 colors,
188 config,
189 decorations,
190 content_type: input.reader.content_type,
191 ansi_prefix_sgr: String::new(),
192 #[cfg(feature = "git")]
193 line_changes,
194 highlighter,
195 syntax_set: &assets.syntax_set,
196 background_color_highlight,
197 })
198 }
200 fn print_horizontal_line_term(&mut self, handle: &mut dyn Write, style: Style) -> Result<()> {
201 writeln!(
202 handle,
203 "{}",
204 style.paint("─".repeat(self.config.term_width))
205 )?;
206 Ok(())
207 }
209 fn print_horizontal_line(&mut self, handle: &mut dyn Write, grid_char: char) -> Result<()> {
210 if self.panel_width == 0 {
211 self.print_horizontal_line_term(handle, self.colors.grid)?;
212 } else {
213 let hline = "─".repeat(self.config.term_width - (self.panel_width + 1));
214 let hline = format!("{}{}{}", "─".repeat(self.panel_width), grid_char, hline);
215 writeln!(handle, "{}", self.colors.grid.paint(hline))?;
216 }
218 Ok(())
219 }
221 fn create_fake_panel(&self, text: &str) -> String {
222 if self.panel_width == 0 {
223 "".to_string()
224 } else {
225 let text_truncated: String = text.chars().take(self.panel_width - 1).collect();
226 let text_filled: String = format!(
227 "{}{}",
228 text_truncated,
229 " ".repeat(self.panel_width - 1 - text_truncated.len())
230 );
231 if self.config.style_components.grid() {
232 format!("{} │ ", text_filled)
233 } else {
234 text_filled
235 }
236 }
237 }
239 fn preprocess(&self, text: &str, cursor: &mut usize) -> String {
240 if self.config.tab_width > 0 {
241 expand_tabs(text, self.config.tab_width, cursor)
242 } else {
243 *cursor += text.len();
244 text.to_string()
245 }
246 }
249impl<'a> Printer for InteractivePrinter<'a> {
250 fn print_header(
251 &mut self,
252 handle: &mut dyn Write,
253 input: &OpenedInput,
254 add_header_padding: bool,
255 ) -> Result<()> {
256 if add_header_padding && self.config.style_components.rule() {
257 self.print_horizontal_line_term(handle, self.colors.rule)?;
258 }
260 if !self.config.style_components.header() {
261 if Some(ContentType::BINARY) == self.content_type && !self.config.show_nonprintable {
262 writeln!(
263 handle,
264 "{}: Binary content from {} will not be printed to the terminal \
265 (but will be present if the output of 'bat' is piped). You can use 'bat -A' \
266 to show the binary file contents.",
267 Yellow.paint("[bat warning]"),
268 input.description.summary(),
269 )?;
270 } else if self.config.style_components.grid() {
271 self.print_horizontal_line(handle, '┬')?;
272 }
273 return Ok(());
274 }
276 if self.config.style_components.grid() {
277 self.print_horizontal_line(handle, '┬')?;
279 write!(
280 handle,
281 "{}{}",
282 " ".repeat(self.panel_width),
283 self.colors
284 .grid
285 .paint(if self.panel_width > 0 { "│ " } else { "" }),
286 )?;
287 } else {
288 // Only pad space between files, if we haven't already drawn a horizontal rule
289 if add_header_padding && !self.config.style_components.rule() {
290 writeln!(handle)?;
291 }
292 write!(handle, "{}", " ".repeat(self.panel_width))?;
293 }
295 let mode = match self.content_type {
296 Some(ContentType::BINARY) => " <BINARY>",
297 Some(ContentType::UTF_16LE) => " <UTF-16LE>",
298 Some(ContentType::UTF_16BE) => " <UTF-16BE>",
299 None => " <EMPTY>",
300 _ => "",
301 };
303 let description = &input.description;
305 writeln!(
306 handle,
307 "{}{}{}",
308 description
309 .kind()
310 .map(|kind| format!("{}: ", kind))
311 .unwrap_or_else(|| "".into()),
312 self.colors.filename.paint(description.title()),
313 mode
314 )?;
316 if self.config.style_components.grid() {
317 if self.content_type.map_or(false, |c| c.is_text()) || self.config.show_nonprintable {
318 self.print_horizontal_line(handle, '┼')?;
319 } else {
320 self.print_horizontal_line(handle, '┴')?;
321 }
322 }
324 Ok(())
325 }
327 fn print_footer(&mut self, handle: &mut dyn Write, _input: &OpenedInput) -> Result<()> {
328 if self.config.style_components.grid()
329 && (self.content_type.map_or(false, |c| c.is_text()) || self.config.show_nonprintable)
330 {
331 self.print_horizontal_line(handle, '┴')
332 } else {
333 Ok(())
334 }
335 }
337 fn print_snip(&mut self, handle: &mut dyn Write) -> Result<()> {
338 let panel = self.create_fake_panel(" ...");
339 let panel_count = panel.chars().count();
341 let title = "8<";
342 let title_count = title.chars().count();
344 let snip_left = "─ ".repeat((self.config.term_width - panel_count - (title_count / 2)) / 4);
345 let snip_left_count = snip_left.chars().count(); // Can't use .len() with Unicode.
347 let snip_right =
348 " ─".repeat((self.config.term_width - panel_count - snip_left_count - title_count) / 2);
350 writeln!(
351 handle,
352 "{}",
353 self.colors
354 .grid
355 .paint(format!("{}{}{}{}", panel, snip_left, title, snip_right))
356 )?;
358 Ok(())
359 }
361 fn print_line(
362 &mut self,
363 out_of_range: bool,
364 handle: &mut dyn Write,
365 line_number: usize,
366 line_buffer: &[u8],
367 ) -> Result<()> {
368 let line = if self.config.show_nonprintable {
369 replace_nonprintable(&line_buffer, self.config.tab_width)
370 } else {
371 match self.content_type {
372 Some(ContentType::BINARY) | None => {
373 return Ok(());
374 }
375 Some(ContentType::UTF_16LE) => UTF_16LE
376 .decode(&line_buffer, DecoderTrap::Replace)
377 .map_err(|_| "Invalid UTF-16LE")?,
378 Some(ContentType::UTF_16BE) => UTF_16BE
379 .decode(&line_buffer, DecoderTrap::Replace)
380 .map_err(|_| "Invalid UTF-16BE")?,
381 _ => String::from_utf8_lossy(&line_buffer).to_string(),
382 }
383 };
385 let regions = {
386 let highlighter = match self.highlighter {
387 Some(ref mut highlighter) => highlighter,
388 _ => {
389 return Ok(());
390 }
391 };
392 highlighter.highlight(line.as_ref(), self.syntax_set)
393 };
395 if out_of_range {
396 return Ok(());
397 }
399 let mut cursor: usize = 0;
400 let mut cursor_max: usize = self.config.term_width;
401 let mut cursor_total: usize = 0;
402 let mut panel_wrap: Option<String> = None;
404 // Line highlighting
405 let highlight_this_line =
406 self.config.highlighted_lines.0.check(line_number) == RangeCheckResult::InRange;
408 let background_color = self
409 .background_color_highlight
410 .filter(|_| highlight_this_line);
412 // Line decorations.
413 if self.panel_width > 0 {
414 let decorations = self
415 .decorations
416 .iter()
417 .map(|ref d| d.generate(line_number, false, self))
418 .collect::<Vec<_>>();
420 for deco in decorations {
421 write!(handle, "{} ", deco.text)?;
422 cursor_max -= deco.width + 1;
423 }
424 }
426 // Line contents.
427 if self.config.wrapping_mode == WrappingMode::NoWrapping {
428 let true_color = self.config.true_color;
429 let colored_output = self.config.colored_output;
430 let italics = self.config.use_italic_text;
432 for &(style, region) in regions.iter() {
433 let text = &*self.preprocess(region, &mut cursor_total);
434 let text_trimmed = text.trim_end_matches(|c| c == '\r' || c == '\n');
435 write!(
436 handle,
437 "{}",
438 as_terminal_escaped(
439 style,
440 text_trimmed,
441 true_color,
442 colored_output,
443 italics,
444 background_color
445 )
446 )?;
448 if text.len() != text_trimmed.len() {
449 if let Some(background_color) = background_color {
450 let mut ansi_style = Style::default();
451 ansi_style.background = to_ansi_color(background_color, true_color);
452 let width = if cursor_total <= cursor_max {
453 cursor_max - cursor_total + 1
454 } else {
455 0
456 };
457 write!(handle, "{}", ansi_style.paint(" ".repeat(width)))?;
458 }
459 write!(handle, "{}", &text[text_trimmed.len()..])?;
460 }
461 }
463 if !self.config.style_components.plain() && line.bytes().next_back() != Some(b'\n') {
464 writeln!(handle)?;
465 }
466 } else {
467 for &(style, region) in regions.iter() {
468 let ansi_iterator = AnsiCodeIterator::new(region);
469 let mut ansi_prefix: String = String::new();
470 for chunk in ansi_iterator {
471 match chunk {
472 // ANSI escape passthrough.
473 (text, true) => {
474 let is_ansi_csi = text.starts_with("\x1B[");
476 if is_ansi_csi && text.ends_with('m') {
477 // It's an ANSI SGR sequence.
478 // We should be mostly safe to just append these together.
479 ansi_prefix.push_str(text);
480 if text == "\x1B[0m" {
481 self.ansi_prefix_sgr = "\x1B[0m".to_owned();
482 } else {
483 self.ansi_prefix_sgr.push_str(text);
484 }
485 } else if is_ansi_csi {
486 // It's a regular CSI sequence.
487 // We should be mostly safe to just append these together.
488 ansi_prefix.push_str(text);
489 } else {
490 // It's probably a VT100 code.
491 // Passing it through is the safest bet.
492 write!(handle, "{}", text)?;
493 }
494 }
496 // Regular text.
497 (text, false) => {
498 let text = self.preprocess(
499 text.trim_end_matches(|c| c == '\r' || c == '\n'),
500 &mut cursor_total,
501 );
503 let mut max_width = cursor_max - cursor;
505 // line buffer (avoid calling write! for every character)
506 let mut line_buf = String::with_capacity(max_width * 4);
508 // Displayed width of line_buf
509 let mut current_width = 0;
511 for c in text.chars() {
512 // calculate the displayed width for next character
513 let cw = c.width().unwrap_or(0);
514 current_width += cw;
516 // if next character cannot be printed on this line,
517 // flush the buffer.
518 if current_width > max_width {
519 // Generate wrap padding if not already generated.
520 if panel_wrap.is_none() {
521 panel_wrap = if self.panel_width > 0 {
522 Some(format!(
523 "{} ",
524 self.decorations
525 .iter()
526 .map(|ref d| d
527 .generate(line_number, true, self)
528 .text)
529 .collect::<Vec<String>>()
530 .join(" ")
531 ))
532 } else {
533 Some("".to_string())
534 }
535 }
537 // It wraps.
538 write!(
539 handle,
540 "{}\n{}",
541 as_terminal_escaped(
542 style,
543 &*format!(
544 "{}{}{}",
545 self.ansi_prefix_sgr, ansi_prefix, line_buf
546 ),
547 self.config.true_color,
548 self.config.colored_output,
549 self.config.use_italic_text,
550 background_color
551 ),
552 panel_wrap.clone().unwrap()
553 )?;
555 cursor = 0;
556 max_width = cursor_max;
558 line_buf.clear();
559 current_width = cw;
560 }
562 line_buf.push(c);
563 }
565 // flush the buffer
566 cursor += current_width;
567 write!(
568 handle,
569 "{}",
570 as_terminal_escaped(
571 style,
572 &*format!(
573 "{}{}{}",
574 self.ansi_prefix_sgr, ansi_prefix, line_buf
575 ),
576 self.config.true_color,
577 self.config.colored_output,
578 self.config.use_italic_text,
579 background_color
580 )
581 )?;
583 // Clear the ANSI prefix buffer.
584 ansi_prefix.clear();
585 }
586 }
587 }
588 }
590 if let Some(background_color) = background_color {
591 let mut ansi_style = Style::default();
592 ansi_style.background = to_ansi_color(background_color, self.config.true_color);
594 write!(
595 handle,
596 "{}",
597 ansi_style.paint(" ".repeat(cursor_max - cursor))
598 )?;
599 }
600 writeln!(handle)?;
601 }
603 Ok(())
604 }
607const DEFAULT_GUTTER_COLOR: u8 = 238;
609#[derive(Debug, Default)]
610pub struct Colors {
611 pub grid: Style,
612 pub rule: Style,
613 pub filename: Style,
614 pub git_added: Style,
615 pub git_removed: Style,
616 pub git_modified: Style,
617 pub line_number: Style,
620impl Colors {
621 fn plain() -> Self {
622 Colors::default()
623 }
625 fn colored(theme: &Theme, true_color: bool) -> Self {
626 let gutter_style = Style {
627 foreground: match theme.settings.gutter_foreground {
628 // If the theme provides a gutter foreground color, use it.
629 // Note: It might be the special value #00000001, in which case
630 // to_ansi_color returns None and we use an empty Style
631 // (resulting in the terminal's default foreground color).
632 Some(c) => to_ansi_color(c, true_color),
633 // Otherwise, use a specific fallback color.
634 None => Some(Fixed(DEFAULT_GUTTER_COLOR)),
635 },
636 ..Style::default()
637 };
639 Colors {
640 grid: gutter_style,
641 rule: gutter_style,
642 filename: Style::new().bold(),
643 git_added: Green.normal(),
644 git_removed: Red.normal(),
645 git_modified: Yellow.normal(),
646 line_number: gutter_style,
647 }
648 }