on a70efae help sign in
bat/src/printer.rs
634 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<'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(&mut self, handle: &mut dyn Write, grid_char: char) -> Result<()> {
204 if self.panel_width == 0 {
205 writeln!(
206 handle,
207 "{}",
208 self.colors.grid.paint("─".repeat(self.config.term_width))
209 )?;
210 } else {
211 let hline = "─".repeat(self.config.term_width - (self.panel_width + 1));
212 let hline = format!("{}{}{}", "─".repeat(self.panel_width), grid_char, hline);
213 writeln!(handle, "{}", self.colors.grid.paint(hline))?;
214 }
216 Ok(())
217 }
219 fn create_fake_panel(&self, text: &str) -> String {
220 if self.panel_width == 0 {
221 "".to_string()
222 } else {
223 let text_truncated: String = text.chars().take(self.panel_width - 1).collect();
224 let text_filled: String = format!(
225 "{}{}",
226 text_truncated,
227 " ".repeat(self.panel_width - 1 - text_truncated.len())
228 );
229 if self.config.style_components.grid() {
230 format!("{} │ ", text_filled)
231 } else {
232 text_filled
233 }
234 }
235 }
237 fn preprocess(&self, text: &str, cursor: &mut usize) -> String {
238 if self.config.tab_width > 0 {
239 expand_tabs(text, self.config.tab_width, cursor)
240 } else {
241 *cursor += text.len();
242 text.to_string()
243 }
244 }
247impl<'a> Printer for InteractivePrinter<'a> {
248 fn print_header(
249 &mut self,
250 handle: &mut dyn Write,
251 input: &OpenedInput,
252 add_header_padding: bool,
253 ) -> Result<()> {
254 if !self.config.style_components.header() {
255 if Some(ContentType::BINARY) == self.content_type && !self.config.show_nonprintable {
256 writeln!(
257 handle,
258 "{}: Binary content from {} will not be printed to the terminal \
259 (but will be present if the output of 'bat' is piped). You can use 'bat -A' \
260 to show the binary file contents.",
261 Yellow.paint("[bat warning]"),
262 input.description.summary(),
263 )?;
264 } else if self.config.style_components.grid() {
265 self.print_horizontal_line(handle, '┬')?;
266 }
267 return Ok(());
268 }
270 if self.config.style_components.grid() {
271 self.print_horizontal_line(handle, '┬')?;
273 write!(
274 handle,
275 "{}{}",
276 " ".repeat(self.panel_width),
277 self.colors
278 .grid
279 .paint(if self.panel_width > 0 { "│ " } else { "" }),
280 )?;
281 } else {
282 if add_header_padding {
283 writeln!(handle)?;
284 }
285 write!(handle, "{}", " ".repeat(self.panel_width))?;
286 }
288 let mode = match self.content_type {
289 Some(ContentType::BINARY) => " <BINARY>",
290 Some(ContentType::UTF_16LE) => " <UTF-16LE>",
291 Some(ContentType::UTF_16BE) => " <UTF-16BE>",
292 None => " <EMPTY>",
293 _ => "",
294 };
296 let description = &input.description;
298 writeln!(
299 handle,
300 "{}{}{}",
301 description
302 .kind()
303 .map(|kind| format!("{}: ", kind))
304 .unwrap_or("".into()),
305 self.colors.filename.paint(description.title()),
306 mode
307 )?;
309 if self.config.style_components.grid() {
310 if self.content_type.map_or(false, |c| c.is_text()) || self.config.show_nonprintable {
311 self.print_horizontal_line(handle, '┼')?;
312 } else {
313 self.print_horizontal_line(handle, '┴')?;
314 }
315 }
317 Ok(())
318 }
320 fn print_footer(&mut self, handle: &mut dyn Write, _input: &OpenedInput) -> Result<()> {
321 if self.config.style_components.grid()
322 && (self.content_type.map_or(false, |c| c.is_text()) || self.config.show_nonprintable)
323 {
324 self.print_horizontal_line(handle, '┴')
325 } else {
326 Ok(())
327 }
328 }
330 fn print_snip(&mut self, handle: &mut dyn Write) -> Result<()> {
331 let panel = self.create_fake_panel(" ...");
332 let panel_count = panel.chars().count();
334 let title = "8<";
335 let title_count = title.chars().count();
337 let snip_left = "─ ".repeat((self.config.term_width - panel_count - (title_count / 2)) / 4);
338 let snip_left_count = snip_left.chars().count(); // Can't use .len() with Unicode.
340 let snip_right =
341 " ─".repeat((self.config.term_width - panel_count - snip_left_count - title_count) / 2);
343 writeln!(
344 handle,
345 "{}",
346 self.colors
347 .grid
348 .paint(format!("{}{}{}{}", panel, snip_left, title, snip_right))
349 )?;
351 Ok(())
352 }
354 fn print_line(
355 &mut self,
356 out_of_range: bool,
357 handle: &mut dyn Write,
358 line_number: usize,
359 line_buffer: &[u8],
360 ) -> Result<()> {
361 let line = if self.config.show_nonprintable {
362 replace_nonprintable(&line_buffer, self.config.tab_width)
363 } else {
364 match self.content_type {
365 Some(ContentType::BINARY) | None => {
366 return Ok(());
367 }
368 Some(ContentType::UTF_16LE) => UTF_16LE
369 .decode(&line_buffer, DecoderTrap::Replace)
370 .map_err(|_| "Invalid UTF-16LE")?,
371 Some(ContentType::UTF_16BE) => UTF_16BE
372 .decode(&line_buffer, DecoderTrap::Replace)
373 .map_err(|_| "Invalid UTF-16BE")?,
374 _ => String::from_utf8_lossy(&line_buffer).to_string(),
375 }
376 };
378 let regions = {
379 let highlighter = match self.highlighter {
380 Some(ref mut highlighter) => highlighter,
381 _ => {
382 return Ok(());
383 }
384 };
385 highlighter.highlight(line.as_ref(), self.syntax_set)
386 };
388 if out_of_range {
389 return Ok(());
390 }
392 let mut cursor: usize = 0;
393 let mut cursor_max: usize = self.config.term_width;
394 let mut cursor_total: usize = 0;
395 let mut panel_wrap: Option<String> = None;
397 // Line highlighting
398 let highlight_this_line =
399 self.config.highlighted_lines.0.check(line_number) == RangeCheckResult::InRange;
401 let background_color = self
402 .background_color_highlight
403 .filter(|_| highlight_this_line);
405 // Line decorations.
406 if self.panel_width > 0 {
407 let decorations = self
408 .decorations
409 .iter()
410 .map(|ref d| d.generate(line_number, false, self))
411 .collect::<Vec<_>>();
413 for deco in decorations {
414 write!(handle, "{} ", deco.text)?;
415 cursor_max -= deco.width + 1;
416 }
417 }
419 // Line contents.
420 if self.config.wrapping_mode == WrappingMode::NoWrapping {
421 let true_color = self.config.true_color;
422 let colored_output = self.config.colored_output;
423 let italics = self.config.use_italic_text;
425 for &(style, region) in regions.iter() {
426 let text = &*self.preprocess(region, &mut cursor_total);
427 let text_trimmed = text.trim_end_matches(|c| c == '\r' || c == '\n');
428 write!(
429 handle,
430 "{}",
431 as_terminal_escaped(
432 style,
433 text_trimmed,
434 true_color,
435 colored_output,
436 italics,
437 background_color
438 )
439 )?;
441 if text.len() != text_trimmed.len() {
442 if let Some(background_color) = background_color {
443 let mut ansi_style = Style::default();
444 ansi_style.background = Some(to_ansi_color(background_color, true_color));
445 let width = if cursor_total <= cursor_max {
446 cursor_max - cursor_total + 1
447 } else {
448 0
449 };
450 write!(handle, "{}", ansi_style.paint(" ".repeat(width)))?;
451 }
452 write!(handle, "{}", &text[text_trimmed.len()..])?;
453 }
454 }
456 if line.bytes().next_back() != Some(b'\n') {
457 writeln!(handle)?;
458 }
459 } else {
460 for &(style, region) in regions.iter() {
461 let ansi_iterator = AnsiCodeIterator::new(region);
462 let mut ansi_prefix: String = String::new();
463 for chunk in ansi_iterator {
464 match chunk {
465 // ANSI escape passthrough.
466 (text, true) => {
467 let is_ansi_csi = text.starts_with("\x1B[");
469 if is_ansi_csi && text.ends_with('m') {
470 // It's an ANSI SGR sequence.
471 // We should be mostly safe to just append these together.
472 ansi_prefix.push_str(text);
473 if text == "\x1B[0m" {
474 self.ansi_prefix_sgr = "\x1B[0m".to_owned();
475 } else {
476 self.ansi_prefix_sgr.push_str(text);
477 }
478 } else if is_ansi_csi {
479 // It's a regular CSI sequence.
480 // We should be mostly safe to just append these together.
481 ansi_prefix.push_str(text);
482 } else {
483 // It's probably a VT100 code.
484 // Passing it through is the safest bet.
485 write!(handle, "{}", text)?;
486 }
487 }
489 // Regular text.
490 (text, false) => {
491 let text = self.preprocess(
492 text.trim_end_matches(|c| c == '\r' || c == '\n'),
493 &mut cursor_total,
494 );
496 let mut max_width = cursor_max - cursor;
498 // line buffer (avoid calling write! for every character)
499 let mut line_buf = String::with_capacity(max_width * 4);
501 // Displayed width of line_buf
502 let mut current_width = 0;
504 for c in text.chars() {
505 // calculate the displayed width for next character
506 let cw = c.width().unwrap_or(0);
507 current_width += cw;
509 // if next character cannot be printed on this line,
510 // flush the buffer.
511 if current_width > max_width {
512 // Generate wrap padding if not already generated.
513 if panel_wrap.is_none() {
514 panel_wrap = if self.panel_width > 0 {
515 Some(format!(
516 "{} ",
517 self.decorations
518 .iter()
519 .map(|ref d| d
520 .generate(line_number, true, self)
521 .text)
522 .collect::<Vec<String>>()
523 .join(" ")
524 ))
525 } else {
526 Some("".to_string())
527 }
528 }
530 // It wraps.
531 write!(
532 handle,
533 "{}\n{}",
534 as_terminal_escaped(
535 style,
536 &*format!(
537 "{}{}{}",
538 self.ansi_prefix_sgr, ansi_prefix, line_buf
539 ),
540 self.config.true_color,
541 self.config.colored_output,
542 self.config.use_italic_text,
543 background_color
544 ),
545 panel_wrap.clone().unwrap()
546 )?;
548 cursor = 0;
549 max_width = cursor_max;
551 line_buf.clear();
552 current_width = cw;
553 }
555 line_buf.push(c);
556 }
558 // flush the buffer
559 cursor += current_width;
560 write!(
561 handle,
562 "{}",
563 as_terminal_escaped(
564 style,
565 &*format!(
566 "{}{}{}",
567 self.ansi_prefix_sgr, ansi_prefix, line_buf
568 ),
569 self.config.true_color,
570 self.config.colored_output,
571 self.config.use_italic_text,
572 background_color
573 )
574 )?;
576 // Clear the ANSI prefix buffer.
577 ansi_prefix.clear();
578 }
579 }
580 }
581 }
583 if let Some(background_color) = background_color {
584 let mut ansi_style = Style::default();
585 ansi_style.background =
586 Some(to_ansi_color(background_color, self.config.true_color));
588 write!(
589 handle,
590 "{}",
591 ansi_style.paint(" ".repeat(cursor_max - cursor))
592 )?;
593 }
594 writeln!(handle)?;
595 }
597 Ok(())
598 }
601const DEFAULT_GUTTER_COLOR: u8 = 238;
603#[derive(Debug, Default)]
604pub struct Colors {
605 pub grid: Style,
606 pub filename: Style,
607 pub git_added: Style,
608 pub git_removed: Style,
609 pub git_modified: Style,
610 pub line_number: Style,
613impl Colors {
614 fn plain() -> Self {
615 Colors::default()
616 }
618 fn colored(theme: &Theme, true_color: bool) -> Self {
619 let gutter_color = theme
620 .settings
621 .gutter_foreground
622 .map(|c| to_ansi_color(c, true_color))
623 .unwrap_or(Fixed(DEFAULT_GUTTER_COLOR));
625 Colors {
626 grid: gutter_color.normal(),
627 filename: Style::new().bold(),
628 git_added: Green.normal(),
629 git_removed: Red.normal(),
630 git_modified: Yellow.normal(),
631 line_number: gutter_color.normal(),
632 }
633 }