on v0.14.0 help sign in
bat/src/printer.rs
612 lines 22 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::{get_git_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(&mut self, handle: &mut dyn Write, input: &OpenedInput) -> Result<()>;
37 fn print_footer(&mut self, handle: &mut dyn Write, input: &OpenedInput) -> Result<()>;
39 fn print_snip(&mut self, handle: &mut dyn Write) -> Result<()>;
41 fn print_line(
42 &mut self,
43 out_of_range: bool,
44 handle: &mut dyn Write,
45 line_number: usize,
46 line_buffer: &[u8],
47 ) -> Result<()>;
50pub struct SimplePrinter;
52impl SimplePrinter {
53 pub fn new() -> Self {
54 SimplePrinter {}
55 }
58impl Printer for SimplePrinter {
59 fn print_header(&mut self, _handle: &mut dyn Write, _input: &OpenedInput) -> Result<()> {
60 Ok(())
61 }
63 fn print_footer(&mut self, _handle: &mut dyn Write, _input: &OpenedInput) -> Result<()> {
64 Ok(())
65 }
67 fn print_snip(&mut self, _handle: &mut dyn Write) -> Result<()> {
68 Ok(())
69 }
71 fn print_line(
72 &mut self,
73 out_of_range: bool,
74 handle: &mut dyn Write,
75 _line_number: usize,
76 line_buffer: &[u8],
77 ) -> Result<()> {
78 if !out_of_range {
79 handle.write_all(line_buffer)?;
80 }
81 Ok(())
82 }
85pub(crate) struct InteractivePrinter<'a> {
86 colors: Colors,
87 config: &'a Config<'a>,
88 decorations: Vec<Box<dyn Decoration>>,
89 panel_width: usize,
90 ansi_prefix_sgr: String,
91 content_type: Option<ContentType>,
92 #[cfg(feature = "git")]
93 pub line_changes: Option<LineChanges>,
94 highlighter: Option<HighlightLines<'a>>,
95 syntax_set: &'a SyntaxSet,
96 background_color_highlight: Option<Color>,
99impl<'a> InteractivePrinter<'a> {
100 pub(crate) fn new(
101 config: &'a Config,
102 assets: &'a HighlightingAssets,
103 input: &mut OpenedInput,
104 ) -> Self {
105 let theme = assets.get_theme(&config.theme);
107 let background_color_highlight = theme.settings.line_highlight;
109 let colors = if config.colored_output {
110 Colors::colored(theme, config.true_color)
111 } else {
112 Colors::plain()
113 };
115 // Create decorations.
116 let mut decorations: Vec<Box<dyn Decoration>> = Vec::new();
118 if config.style_components.numbers() {
119 decorations.push(Box::new(LineNumberDecoration::new(&colors)));
120 }
122 #[cfg(feature = "git")]
123 {
124 if config.style_components.changes() {
125 decorations.push(Box::new(LineChangesDecoration::new(&colors)));
126 }
127 }
129 let mut panel_width: usize =
130 decorations.len() + decorations.iter().fold(0, |a, x| a + x.width());
132 // The grid border decoration isn't added until after the panel_width calculation, since the
133 // print_horizontal_line, print_header, and print_footer functions all assume the panel
134 // width is without the grid border.
135 if config.style_components.grid() && !decorations.is_empty() {
136 decorations.push(Box::new(GridBorderDecoration::new(&colors)));
137 }
139 // Disable the panel if the terminal is too small (i.e. can't fit 5 characters with the
140 // panel showing).
141 if config.term_width
142 < (decorations.len() + decorations.iter().fold(0, |a, x| a + x.width())) + 5
143 {
144 decorations.clear();
145 panel_width = 0;
146 }
148 #[cfg(feature = "git")]
149 let mut line_changes = None;
151 let highlighter = if input
152 .reader
153 .content_type
154 .map_or(false, |c| c.is_binary() && !config.show_nonprintable)
155 {
156 None
157 } else {
158 // Get the Git modifications
159 #[cfg(feature = "git")]
160 {
161 use crate::input::OpenedInputKind;
163 if config.style_components.changes() {
164 if let OpenedInputKind::OrdinaryFile(ref path) = input.kind {
165 line_changes = get_git_diff(path);
166 }
167 }
168 }
170 // Determine the type of syntax for highlighting
171 let syntax = assets.get_syntax(config.language, input, &config.syntax_mapping);
172 Some(HighlightLines::new(syntax, theme))
173 };
175 InteractivePrinter {
176 panel_width,
177 colors,
178 config,
179 decorations,
180 content_type: input.reader.content_type,
181 ansi_prefix_sgr: String::new(),
182 #[cfg(feature = "git")]
183 line_changes,
184 highlighter,
185 syntax_set: &assets.syntax_set,
186 background_color_highlight,
187 }
188 }
190 fn print_horizontal_line(&mut self, handle: &mut dyn Write, grid_char: char) -> Result<()> {
191 if self.panel_width == 0 {
192 writeln!(
193 handle,
194 "{}",
195 self.colors.grid.paint("─".repeat(self.config.term_width))
196 )?;
197 } else {
198 let hline = "─".repeat(self.config.term_width - (self.panel_width + 1));
199 let hline = format!("{}{}{}", "─".repeat(self.panel_width), grid_char, hline);
200 writeln!(handle, "{}", self.colors.grid.paint(hline))?;
201 }
203 Ok(())
204 }
206 fn create_fake_panel(&self, text: &str) -> String {
207 if self.panel_width == 0 {
208 "".to_string()
209 } else {
210 let text_truncated: String = text.chars().take(self.panel_width - 1).collect();
211 let text_filled: String = format!(
212 "{}{}",
213 text_truncated,
214 " ".repeat(self.panel_width - 1 - text_truncated.len())
215 );
216 if self.config.style_components.grid() {
217 format!("{} │ ", text_filled)
218 } else {
219 format!("{}", text_filled)
220 }
221 }
222 }
224 fn preprocess(&self, text: &str, cursor: &mut usize) -> String {
225 if self.config.tab_width > 0 {
226 expand_tabs(text, self.config.tab_width, cursor)
227 } else {
228 *cursor += text.len();
229 text.to_string()
230 }
231 }
234impl<'a> Printer for InteractivePrinter<'a> {
235 fn print_header(&mut self, handle: &mut dyn Write, input: &OpenedInput) -> Result<()> {
236 if !self.config.style_components.header() {
237 if Some(ContentType::BINARY) == self.content_type && !self.config.show_nonprintable {
238 writeln!(
239 handle,
240 "{}: Binary content from {} will not be printed to the terminal \
241 (but will be present if the output of 'bat' is piped). You can use 'bat -A' \
242 to show the binary file contents.",
243 Yellow.paint("[bat warning]"),
244 input.description().full,
245 )?;
246 } else {
247 if self.config.style_components.grid() {
248 self.print_horizontal_line(handle, '┬')?;
249 }
250 }
251 return Ok(());
252 }
254 if self.config.style_components.grid() {
255 self.print_horizontal_line(handle, '┬')?;
257 write!(
258 handle,
259 "{}{}",
260 " ".repeat(self.panel_width),
261 self.colors
262 .grid
263 .paint(if self.panel_width > 0 { "│ " } else { "" }),
264 )?;
265 } else {
266 write!(handle, "{}", " ".repeat(self.panel_width))?;
267 }
269 let mode = match self.content_type {
270 Some(ContentType::BINARY) => " <BINARY>",
271 Some(ContentType::UTF_16LE) => " <UTF-16LE>",
272 Some(ContentType::UTF_16BE) => " <UTF-16BE>",
273 None => " <EMPTY>",
274 _ => "",
275 };
277 let description = input.description();
279 writeln!(
280 handle,
281 "{}{}{}",
282 description.prefix,
283 self.colors.filename.paint(&description.name),
284 mode
285 )?;
287 if self.config.style_components.grid() {
288 if self.content_type.map_or(false, |c| c.is_text()) || self.config.show_nonprintable {
289 self.print_horizontal_line(handle, '┼')?;
290 } else {
291 self.print_horizontal_line(handle, '┴')?;
292 }
293 }
295 Ok(())
296 }
298 fn print_footer(&mut self, handle: &mut dyn Write, _input: &OpenedInput) -> Result<()> {
299 if self.config.style_components.grid()
300 && (self.content_type.map_or(false, |c| c.is_text()) || self.config.show_nonprintable)
301 {
302 self.print_horizontal_line(handle, '┴')
303 } else {
304 Ok(())
305 }
306 }
308 fn print_snip(&mut self, handle: &mut dyn Write) -> Result<()> {
309 let panel = self.create_fake_panel(" ...");
310 let panel_count = panel.chars().count();
312 let title = "8<";
313 let title_count = title.chars().count();
315 let snip_left = "─ ".repeat((self.config.term_width - panel_count - (title_count / 2)) / 4);
316 let snip_left_count = snip_left.chars().count(); // Can't use .len() with Unicode.
318 let snip_right =
319 " ─".repeat((self.config.term_width - panel_count - snip_left_count - title_count) / 2);
321 write!(
322 handle,
323 "{}\n",
324 self.colors
325 .grid
326 .paint(format!("{}{}{}{}", panel, snip_left, title, snip_right))
327 )?;
329 Ok(())
330 }
332 fn print_line(
333 &mut self,
334 out_of_range: bool,
335 handle: &mut dyn Write,
336 line_number: usize,
337 line_buffer: &[u8],
338 ) -> Result<()> {
339 let line = if self.config.show_nonprintable {
340 replace_nonprintable(&line_buffer, self.config.tab_width)
341 } else {
342 match self.content_type {
343 Some(ContentType::BINARY) | None => {
344 return Ok(());
345 }
346 Some(ContentType::UTF_16LE) => UTF_16LE
347 .decode(&line_buffer, DecoderTrap::Replace)
348 .map_err(|_| "Invalid UTF-16LE")?,
349 Some(ContentType::UTF_16BE) => UTF_16BE
350 .decode(&line_buffer, DecoderTrap::Replace)
351 .map_err(|_| "Invalid UTF-16BE")?,
352 _ => String::from_utf8_lossy(&line_buffer).to_string(),
353 }
354 };
356 let regions = {
357 let highlighter = match self.highlighter {
358 Some(ref mut highlighter) => highlighter,
359 _ => {
360 return Ok(());
361 }
362 };
363 highlighter.highlight(line.as_ref(), self.syntax_set)
364 };
366 if out_of_range {
367 return Ok(());
368 }
370 let mut cursor: usize = 0;
371 let mut cursor_max: usize = self.config.term_width;
372 let mut cursor_total: usize = 0;
373 let mut panel_wrap: Option<String> = None;
375 // Line highlighting
376 let highlight_this_line =
377 self.config.highlighted_lines.0.check(line_number) == RangeCheckResult::InRange;
379 let background_color = self
380 .background_color_highlight
381 .filter(|_| highlight_this_line);
383 // Line decorations.
384 if self.panel_width > 0 {
385 let decorations = self
386 .decorations
387 .iter()
388 .map(|ref d| d.generate(line_number, false, self))
389 .collect::<Vec<_>>();
391 for deco in decorations {
392 write!(handle, "{} ", deco.text)?;
393 cursor_max -= deco.width + 1;
394 }
395 }
397 // Line contents.
398 if self.config.wrapping_mode == WrappingMode::NoWrapping {
399 let true_color = self.config.true_color;
400 let colored_output = self.config.colored_output;
401 let italics = self.config.use_italic_text;
403 for &(style, region) in regions.iter() {
404 let text = &*self.preprocess(region, &mut cursor_total);
405 let text_trimmed = text.trim_end_matches(|c| c == '\r' || c == '\n');
406 write!(
407 handle,
408 "{}",
409 as_terminal_escaped(
410 style,
411 text_trimmed,
412 true_color,
413 colored_output,
414 italics,
415 background_color
416 )
417 )?;
419 if text.len() != text_trimmed.len() {
420 if let Some(background_color) = background_color {
421 let mut ansi_style = Style::default();
422 ansi_style.background = Some(to_ansi_color(background_color, true_color));
423 let width = if cursor_total <= cursor_max {
424 cursor_max - cursor_total + 1
425 } else {
426 0
427 };
428 write!(handle, "{}", ansi_style.paint(" ".repeat(width)))?;
429 }
430 write!(handle, "{}", &text[text_trimmed.len()..])?;
431 }
432 }
434 if line.bytes().next_back() != Some(b'\n') {
435 writeln!(handle)?;
436 }
437 } else {
438 for &(style, region) in regions.iter() {
439 let ansi_iterator = AnsiCodeIterator::new(region);
440 let mut ansi_prefix: String = String::new();
441 for chunk in ansi_iterator {
442 match chunk {
443 // ANSI escape passthrough.
444 (text, true) => {
445 let is_ansi_csi = text.starts_with("\x1B[");
447 if is_ansi_csi && text.ends_with('m') {
448 // It's an ANSI SGR sequence.
449 // We should be mostly safe to just append these together.
450 ansi_prefix.push_str(text);
451 if text == "\x1B[0m" {
452 self.ansi_prefix_sgr = "\x1B[0m".to_owned();
453 } else {
454 self.ansi_prefix_sgr.push_str(text);
455 }
456 } else if is_ansi_csi {
457 // It's a regular CSI sequence.
458 // We should be mostly safe to just append these together.
459 ansi_prefix.push_str(text);
460 } else {
461 // It's probably a VT100 code.
462 // Passing it through is the safest bet.
463 write!(handle, "{}", text)?;
464 }
465 }
467 // Regular text.
468 (text, false) => {
469 let text = self.preprocess(
470 text.trim_end_matches(|c| c == '\r' || c == '\n'),
471 &mut cursor_total,
472 );
474 let mut max_width = cursor_max - cursor;
476 // line buffer (avoid calling write! for every character)
477 let mut line_buf = String::with_capacity(max_width * 4);
479 // Displayed width of line_buf
480 let mut current_width = 0;
482 for c in text.chars() {
483 // calculate the displayed width for next character
484 let cw = c.width().unwrap_or(0);
485 current_width += cw;
487 // if next character cannot be printed on this line,
488 // flush the buffer.
489 if current_width > max_width {
490 // Generate wrap padding if not already generated.
491 if panel_wrap.is_none() {
492 panel_wrap = if self.panel_width > 0 {
493 Some(format!(
494 "{} ",
495 self.decorations
496 .iter()
497 .map(|ref d| d
498 .generate(line_number, true, self)
499 .text)
500 .collect::<Vec<String>>()
501 .join(" ")
502 ))
503 } else {
504 Some("".to_string())
505 }
506 }
508 // It wraps.
509 write!(
510 handle,
511 "{}\n{}",
512 as_terminal_escaped(
513 style,
514 &*format!(
515 "{}{}{}",
516 self.ansi_prefix_sgr, ansi_prefix, line_buf
517 ),
518 self.config.true_color,
519 self.config.colored_output,
520 self.config.use_italic_text,
521 background_color
522 ),
523 panel_wrap.clone().unwrap()
524 )?;
526 cursor = 0;
527 max_width = cursor_max;
529 line_buf.clear();
530 current_width = cw;
531 }
533 line_buf.push(c);
534 }
536 // flush the buffer
537 cursor += current_width;
538 write!(
539 handle,
540 "{}",
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 )?;
554 // Clear the ANSI prefix buffer.
555 ansi_prefix.clear();
556 }
557 }
558 }
559 }
561 if let Some(background_color) = background_color {
562 let mut ansi_style = Style::default();
563 ansi_style.background =
564 Some(to_ansi_color(background_color, self.config.true_color));
566 write!(
567 handle,
568 "{}",
569 ansi_style.paint(" ".repeat(cursor_max - cursor))
570 )?;
571 }
572 writeln!(handle)?;
573 }
575 Ok(())
576 }
579const DEFAULT_GUTTER_COLOR: u8 = 238;
581#[derive(Debug, Default)]
582pub struct Colors {
583 pub grid: Style,
584 pub filename: Style,
585 pub git_added: Style,
586 pub git_removed: Style,
587 pub git_modified: Style,
588 pub line_number: Style,
591impl Colors {
592 fn plain() -> Self {
593 Colors::default()
594 }
596 fn colored(theme: &Theme, true_color: bool) -> Self {
597 let gutter_color = theme
598 .settings
599 .gutter_foreground
600 .map(|c| to_ansi_color(c, true_color))
601 .unwrap_or(Fixed(DEFAULT_GUTTER_COLOR));
603 Colors {
604 grid: gutter_color.normal(),
605 filename: Style::new().bold(),
606 git_added: Green.normal(),
607 git_removed: Red.normal(),
608 git_modified: Yellow.normal(),
609 line_number: gutter_color.normal(),
610 }
611 }