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