on v0.15.2 help sign in
bat/src/printer.rs
621 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().full,
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.prefix,
292 self.colors.filename.paint(&description.name),
293 mode
294 )?;
296 if self.config.style_components.grid() {
297 if self.content_type.map_or(false, |c| c.is_text()) || self.config.show_nonprintable {
298 self.print_horizontal_line(handle, '┼')?;
299 } else {
300 self.print_horizontal_line(handle, '┴')?;
301 }
302 }
304 Ok(())
305 }
307 fn print_footer(&mut self, handle: &mut dyn Write, _input: &OpenedInput) -> Result<()> {
308 if self.config.style_components.grid()
309 && (self.content_type.map_or(false, |c| c.is_text()) || self.config.show_nonprintable)
310 {
311 self.print_horizontal_line(handle, '┴')
312 } else {
313 Ok(())
314 }
315 }
317 fn print_snip(&mut self, handle: &mut dyn Write) -> Result<()> {
318 let panel = self.create_fake_panel(" ...");
319 let panel_count = panel.chars().count();
321 let title = "8<";
322 let title_count = title.chars().count();
324 let snip_left = "─ ".repeat((self.config.term_width - panel_count - (title_count / 2)) / 4);
325 let snip_left_count = snip_left.chars().count(); // Can't use .len() with Unicode.
327 let snip_right =
328 " ─".repeat((self.config.term_width - panel_count - snip_left_count - title_count) / 2);
330 writeln!(
331 handle,
332 "{}",
333 self.colors
334 .grid
335 .paint(format!("{}{}{}{}", panel, snip_left, title, snip_right))
336 )?;
338 Ok(())
339 }
341 fn print_line(
342 &mut self,
343 out_of_range: bool,
344 handle: &mut dyn Write,
345 line_number: usize,
346 line_buffer: &[u8],
347 ) -> Result<()> {
348 let line = if self.config.show_nonprintable {
349 replace_nonprintable(&line_buffer, self.config.tab_width)
350 } else {
351 match self.content_type {
352 Some(ContentType::BINARY) | None => {
353 return Ok(());
354 }
355 Some(ContentType::UTF_16LE) => UTF_16LE
356 .decode(&line_buffer, DecoderTrap::Replace)
357 .map_err(|_| "Invalid UTF-16LE")?,
358 Some(ContentType::UTF_16BE) => UTF_16BE
359 .decode(&line_buffer, DecoderTrap::Replace)
360 .map_err(|_| "Invalid UTF-16BE")?,
361 _ => String::from_utf8_lossy(&line_buffer).to_string(),
362 }
363 };
365 let regions = {
366 let highlighter = match self.highlighter {
367 Some(ref mut highlighter) => highlighter,
368 _ => {
369 return Ok(());
370 }
371 };
372 highlighter.highlight(line.as_ref(), self.syntax_set)
373 };
375 if out_of_range {
376 return Ok(());
377 }
379 let mut cursor: usize = 0;
380 let mut cursor_max: usize = self.config.term_width;
381 let mut cursor_total: usize = 0;
382 let mut panel_wrap: Option<String> = None;
384 // Line highlighting
385 let highlight_this_line =
386 self.config.highlighted_lines.0.check(line_number) == RangeCheckResult::InRange;
388 let background_color = self
389 .background_color_highlight
390 .filter(|_| highlight_this_line);
392 // Line decorations.
393 if self.panel_width > 0 {
394 let decorations = self
395 .decorations
396 .iter()
397 .map(|ref d| d.generate(line_number, false, self))
398 .collect::<Vec<_>>();
400 for deco in decorations {
401 write!(handle, "{} ", deco.text)?;
402 cursor_max -= deco.width + 1;
403 }
404 }
406 // Line contents.
407 if self.config.wrapping_mode == WrappingMode::NoWrapping {
408 let true_color = self.config.true_color;
409 let colored_output = self.config.colored_output;
410 let italics = self.config.use_italic_text;
412 for &(style, region) in regions.iter() {
413 let text = &*self.preprocess(region, &mut cursor_total);
414 let text_trimmed = text.trim_end_matches(|c| c == '\r' || c == '\n');
415 write!(
416 handle,
417 "{}",
418 as_terminal_escaped(
419 style,
420 text_trimmed,
421 true_color,
422 colored_output,
423 italics,
424 background_color
425 )
426 )?;
428 if text.len() != text_trimmed.len() {
429 if let Some(background_color) = background_color {
430 let mut ansi_style = Style::default();
431 ansi_style.background = Some(to_ansi_color(background_color, true_color));
432 let width = if cursor_total <= cursor_max {
433 cursor_max - cursor_total + 1
434 } else {
435 0
436 };
437 write!(handle, "{}", ansi_style.paint(" ".repeat(width)))?;
438 }
439 write!(handle, "{}", &text[text_trimmed.len()..])?;
440 }
441 }
443 if line.bytes().next_back() != Some(b'\n') {
444 writeln!(handle)?;
445 }
446 } else {
447 for &(style, region) in regions.iter() {
448 let ansi_iterator = AnsiCodeIterator::new(region);
449 let mut ansi_prefix: String = String::new();
450 for chunk in ansi_iterator {
451 match chunk {
452 // ANSI escape passthrough.
453 (text, true) => {
454 let is_ansi_csi = text.starts_with("\x1B[");
456 if is_ansi_csi && text.ends_with('m') {
457 // It's an ANSI SGR sequence.
458 // We should be mostly safe to just append these together.
459 ansi_prefix.push_str(text);
460 if text == "\x1B[0m" {
461 self.ansi_prefix_sgr = "\x1B[0m".to_owned();
462 } else {
463 self.ansi_prefix_sgr.push_str(text);
464 }
465 } else if is_ansi_csi {
466 // It's a regular CSI sequence.
467 // We should be mostly safe to just append these together.
468 ansi_prefix.push_str(text);
469 } else {
470 // It's probably a VT100 code.
471 // Passing it through is the safest bet.
472 write!(handle, "{}", text)?;
473 }
474 }
476 // Regular text.
477 (text, false) => {
478 let text = self.preprocess(
479 text.trim_end_matches(|c| c == '\r' || c == '\n'),
480 &mut cursor_total,
481 );
483 let mut max_width = cursor_max - cursor;
485 // line buffer (avoid calling write! for every character)
486 let mut line_buf = String::with_capacity(max_width * 4);
488 // Displayed width of line_buf
489 let mut current_width = 0;
491 for c in text.chars() {
492 // calculate the displayed width for next character
493 let cw = c.width().unwrap_or(0);
494 current_width += cw;
496 // if next character cannot be printed on this line,
497 // flush the buffer.
498 if current_width > max_width {
499 // Generate wrap padding if not already generated.
500 if panel_wrap.is_none() {
501 panel_wrap = if self.panel_width > 0 {
502 Some(format!(
503 "{} ",
504 self.decorations
505 .iter()
506 .map(|ref d| d
507 .generate(line_number, true, self)
508 .text)
509 .collect::<Vec<String>>()
510 .join(" ")
511 ))
512 } else {
513 Some("".to_string())
514 }
515 }
517 // It wraps.
518 write!(
519 handle,
520 "{}\n{}",
521 as_terminal_escaped(
522 style,
523 &*format!(
524 "{}{}{}",
525 self.ansi_prefix_sgr, ansi_prefix, line_buf
526 ),
527 self.config.true_color,
528 self.config.colored_output,
529 self.config.use_italic_text,
530 background_color
531 ),
532 panel_wrap.clone().unwrap()
533 )?;
535 cursor = 0;
536 max_width = cursor_max;
538 line_buf.clear();
539 current_width = cw;
540 }
542 line_buf.push(c);
543 }
545 // flush the buffer
546 cursor += current_width;
547 write!(
548 handle,
549 "{}",
550 as_terminal_escaped(
551 style,
552 &*format!(
553 "{}{}{}",
554 self.ansi_prefix_sgr, ansi_prefix, line_buf
555 ),
556 self.config.true_color,
557 self.config.colored_output,
558 self.config.use_italic_text,
559 background_color
560 )
561 )?;
563 // Clear the ANSI prefix buffer.
564 ansi_prefix.clear();
565 }
566 }
567 }
568 }
570 if let Some(background_color) = background_color {
571 let mut ansi_style = Style::default();
572 ansi_style.background =
573 Some(to_ansi_color(background_color, self.config.true_color));
575 write!(
576 handle,
577 "{}",
578 ansi_style.paint(" ".repeat(cursor_max - cursor))
579 )?;
580 }
581 writeln!(handle)?;
582 }
584 Ok(())
585 }
588const DEFAULT_GUTTER_COLOR: u8 = 238;
590#[derive(Debug, Default)]
591pub struct Colors {
592 pub grid: Style,
593 pub filename: Style,
594 pub git_added: Style,
595 pub git_removed: Style,
596 pub git_modified: Style,
597 pub line_number: Style,
600impl Colors {
601 fn plain() -> Self {
602 Colors::default()
603 }
605 fn colored(theme: &Theme, true_color: bool) -> Self {
606 let gutter_color = theme
607 .settings
608 .gutter_foreground
609 .map(|c| to_ansi_color(c, true_color))
610 .unwrap_or(Fixed(DEFAULT_GUTTER_COLOR));
612 Colors {
613 grid: gutter_color.normal(),
614 filename: Style::new().bold(),
615 git_added: Green.normal(),
616 git_removed: Red.normal(),
617 git_modified: Yellow.normal(),
618 line_number: gutter_color.normal(),
619 }
620 }