4use ansi_term::Colour::{Fixed, Green, Red, Yellow};
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 crate::assets::HighlightingAssets;
20use crate::decorations::{
21 Decoration, GridBorderDecoration, LineChangesDecoration, LineNumberDecoration,
23use crate::diff::get_git_diff;
24use crate::diff::LineChanges;
26use crate::inputfile::{InputFile, InputFileReader};
27use crate::preprocessor::{expand_tabs, replace_nonprintable};
28use crate::style::OutputWrap;
29use crate::terminal::{as_terminal_escaped, to_ansi_color};
33 fn print_header(&mut self, handle: &mut dyn Write, file: InputFile) -> Result<()>;
34 fn print_footer(&mut self, handle: &mut dyn Write) -> Result<()>;
36 fn print_snip(&mut self, handle: &mut dyn Write) -> Result<()>;
41 handle: &mut dyn Write,
47pub struct SimplePrinter;
50 pub fn new() -> Self {
55impl Printer for SimplePrinter {
56 fn print_header(&mut self, _handle: &mut dyn Write, _file: InputFile) -> Result<()> {
60 fn print_footer(&mut self, _handle: &mut dyn Write) -> Result<()> {
64 fn print_snip(&mut self, _handle: &mut dyn Write) -> Result<()> {
71 handle: &mut dyn Write,
76 handle.write_all(line_buffer)?;
82pub struct InteractivePrinter<'a> {
84 config: &'a Config<'a>,
85 decorations: Vec<Box<dyn Decoration>>,
87 ansi_prefix_sgr: String,
88 content_type: Option<ContentType>,
89 pub line_changes: Option<LineChanges>,
90 highlighter: Option<HighlightLines<'a>>,
91 syntax_set: &'a SyntaxSet,
92 background_color_highlight: Option<Color>,
95impl<'a> InteractivePrinter<'a> {
98 assets: &'a HighlightingAssets,
100 reader: &mut InputFileReader,
102 let theme = assets.get_theme(&config.theme);
104 let background_color_highlight = theme.settings.line_highlight;
106 let colors = if config.colored_output {
107 Colors::colored(theme, config.true_color)
112 // Create decorations.
113 let mut decorations: Vec<Box<dyn Decoration>> = Vec::new();
115 if config.output_components.numbers() {
116 decorations.push(Box::new(LineNumberDecoration::new(&colors)));
119 if config.output_components.changes() {
120 decorations.push(Box::new(LineChangesDecoration::new(&colors)));
123 let mut panel_width: usize =
124 decorations.len() + decorations.iter().fold(0, |a, x| a + x.width());
126 // The grid border decoration isn't added until after the panel_width calculation, since the
127 // print_horizontal_line, print_header, and print_footer functions all assume the panel
128 // width is without the grid border.
129 if config.output_components.grid() && !decorations.is_empty() {
130 decorations.push(Box::new(GridBorderDecoration::new(&colors)));
133 // Disable the panel if the terminal is too small (i.e. can't fit 5 characters with the
136 < (decorations.len() + decorations.iter().fold(0, |a, x| a + x.width())) + 5
142 let mut line_changes = None;
144 let highlighter = if reader
146 .map_or(false, |c| c.is_binary() && !config.show_nonprintable)
150 // Get the Git modifications
151 line_changes = if config.output_components.changes() {
153 InputFile::Ordinary(filename) => get_git_diff(filename),
160 // Determine the type of syntax for highlighting
161 let syntax = assets.get_syntax(config.language, file, reader, &config.syntax_mapping);
162 Some(HighlightLines::new(syntax, theme))
170 content_type: reader.content_type,
171 ansi_prefix_sgr: String::new(),
174 syntax_set: &assets.syntax_set,
175 background_color_highlight,
179 fn print_horizontal_line(&mut self, handle: &mut dyn Write, grid_char: char) -> Result<()> {
180 if self.panel_width == 0 {
184 self.colors.grid.paint("─".repeat(self.config.term_width))
187 let hline = "─".repeat(self.config.term_width - (self.panel_width + 1));
188 let hline = format!("{}{}{}", "─".repeat(self.panel_width), grid_char, hline);
189 writeln!(handle, "{}", self.colors.grid.paint(hline))?;
195 fn create_fake_panel(&self, text: &str) -> String {
196 if self.panel_width == 0 {
199 let text_truncated: String = text.chars().take(self.panel_width - 1).collect();
200 let text_filled: String = format!(
203 " ".repeat(self.panel_width - 1 - text_truncated.len())
205 if self.config.output_components.grid() {
206 format!("{} │ ", text_filled)
208 format!("{}", text_filled)
213 fn preprocess(&self, text: &str, cursor: &mut usize) -> String {
214 if self.config.tab_width > 0 {
215 expand_tabs(text, self.config.tab_width, cursor)
222impl<'a> Printer for InteractivePrinter<'a> {
223 fn print_header(&mut self, handle: &mut dyn Write, file: InputFile) -> Result<()> {
224 if !self.config.output_components.header() {
225 if Some(ContentType::BINARY) == self.content_type && !self.config.show_nonprintable {
226 let input = match file {
227 InputFile::Ordinary(filename) => format!("file '{}'", filename),
233 "{}: Binary content from {} will not be printed to the terminal \
234 (but will be present if the output of 'bat' is piped). You can use 'bat -A' \
235 to show the binary file contents.",
236 Yellow.paint("[bat warning]"),
240 if self.config.output_components.grid() {
241 self.print_horizontal_line(handle, '┬')?;
247 if self.config.output_components.grid() {
248 self.print_horizontal_line(handle, '┬')?;
253 " ".repeat(self.panel_width),
256 .paint(if self.panel_width > 0 { "│ " } else { "" }),
259 write!(handle, "{}", " ".repeat(self.panel_width))?;
262 let (prefix, name) = match file {
263 InputFile::Ordinary(filename) => ("File: ", filename),
267 let mode = match self.content_type {
268 Some(ContentType::BINARY) => " <BINARY>",
269 Some(ContentType::UTF_16LE) => " <UTF-16LE>",
270 Some(ContentType::UTF_16BE) => " <UTF-16BE>",
279 self.colors.filename.paint(name),
283 if self.config.output_components.grid() {
284 if self.content_type.map_or(false, |c| c.is_text()) || self.config.show_nonprintable {
285 self.print_horizontal_line(handle, '┼')?;
287 self.print_horizontal_line(handle, '┴')?;
294 fn print_footer(&mut self, handle: &mut dyn Write) -> Result<()> {
295 if self.config.output_components.grid()
296 && (self.content_type.map_or(false, |c| c.is_text()) || self.config.show_nonprintable)
298 self.print_horizontal_line(handle, '┴')
304 fn print_snip(&mut self, handle: &mut dyn Write) -> Result<()> {
305 let panel = self.create_fake_panel(" ...");
306 let panel_count = panel.chars().count();
309 let title_count = title.chars().count();
311 let snip_left = "─ ".repeat((self.config.term_width - panel_count - (title_count / 2)) / 4);
312 let snip_left_count = snip_left.chars().count(); // Can't use .len() with Unicode.
315 " ─".repeat((self.config.term_width - panel_count - snip_left_count - title_count) / 2);
322 .paint(format!("{}{}{}{}", panel, snip_left, title, snip_right))
331 handle: &mut dyn Write,
335 let line = if self.config.show_nonprintable {
336 replace_nonprintable(&line_buffer, self.config.tab_width)
338 match self.content_type {
339 Some(ContentType::BINARY) | None => {
342 Some(ContentType::UTF_16LE) => UTF_16LE
343 .decode(&line_buffer, DecoderTrap::Replace)
344 .map_err(|_| "Invalid UTF-16LE")?,
345 Some(ContentType::UTF_16BE) => UTF_16BE
346 .decode(&line_buffer, DecoderTrap::Replace)
347 .map_err(|_| "Invalid UTF-16BE")?,
348 _ => String::from_utf8_lossy(&line_buffer).to_string(),
353 let highlighter = match self.highlighter {
354 Some(ref mut highlighter) => highlighter,
359 highlighter.highlight(line.as_ref(), self.syntax_set)
366 let mut cursor: usize = 0;
367 let mut cursor_max: usize = self.config.term_width;
368 let mut cursor_total: usize = 0;
369 let mut panel_wrap: Option<String> = None;
372 let highlight_this_line = self
376 .any(|&l| l == line_number);
378 let background_color = self
379 .background_color_highlight
380 .filter(|_| highlight_this_line);
383 if self.panel_width > 0 {
384 let decorations = self
387 .map(|ref d| d.generate(line_number, false, self))
388 .collect::<Vec<_>>();
390 for deco in decorations {
391 write!(handle, "{} ", deco.text)?;
392 cursor_max -= deco.width + 1;
397 if self.config.output_wrap == OutputWrap::None {
398 let true_color = self.config.true_color;
399 let colored_output = self.config.colored_output;
400 let italics = self.config.use_italic_text;
402 for &(style, region) in regions.iter() {
403 let text = &*self.preprocess(region, &mut cursor_total);
404 let text_trimmed = text.trim_end_matches(|c| c == '\r' || c == '\n');
418 if text.len() != text_trimmed.len() {
419 if let Some(background_color) = background_color {
420 let mut ansi_style = Style::default();
421 ansi_style.background = Some(to_ansi_color(background_color, true_color));
422 let width = if cursor_total <= cursor_max {
423 cursor_max - cursor_total + 1
427 write!(handle, "{}", ansi_style.paint(" ".repeat(width)))?;
429 write!(handle, "{}", &text[text_trimmed.len()..])?;
433 if line.bytes().next_back() != Some(b'\n') {
437 for &(style, region) in regions.iter() {
438 let ansi_iterator = AnsiCodeIterator::new(region);
439 let mut ansi_prefix: String = String::new();
440 for chunk in ansi_iterator {
442 // ANSI escape passthrough.
444 let is_ansi_csi = text.starts_with("\x1B[");
446 if is_ansi_csi && text.ends_with('m') {
447 // It's an ANSI SGR sequence.
448 // We should be mostly safe to just append these together.
449 ansi_prefix.push_str(text);
450 if text == "\x1B[0m" {
451 self.ansi_prefix_sgr = "\x1B[0m".to_owned();
453 self.ansi_prefix_sgr.push_str(text);
455 } else if is_ansi_csi {
456 // It's a regular CSI sequence.
457 // We should be mostly safe to just append these together.
458 ansi_prefix.push_str(text);
460 // It's probably a VT100 code.
461 // Passing it through is the safest bet.
462 write!(handle, "{}", text)?;
468 let text = self.preprocess(
469 text.trim_end_matches(|c| c == '\r' || c == '\n'),
473 let mut chars = text.chars();
474 let mut remaining = text.chars().count();
476 while remaining > 0 {
477 let available = cursor_max - cursor;
480 if remaining <= available {
481 let text = chars.by_ref().take(remaining).collect::<String>();
491 self.ansi_prefix_sgr, ansi_prefix, text
493 self.config.true_color,
494 self.config.colored_output,
495 self.config.use_italic_text,
502 // Generate wrap padding if not already generated.
503 if panel_wrap.is_none() {
504 panel_wrap = if self.panel_width > 0 {
510 .generate(line_number, true, self)
512 .collect::<Vec<String>>()
521 let text = chars.by_ref().take(available).collect::<String>();
523 remaining -= available;
532 self.ansi_prefix_sgr, ansi_prefix, text
534 self.config.true_color,
535 self.config.colored_output,
536 self.config.use_italic_text,
539 panel_wrap.clone().unwrap()
543 // Clear the ANSI prefix buffer.
550 if let Some(background_color) = background_color {
551 let mut ansi_style = Style::default();
552 ansi_style.background =
553 Some(to_ansi_color(background_color, self.config.true_color));
558 ansi_style.paint(" ".repeat(cursor_max - cursor))
568const DEFAULT_GUTTER_COLOR: u8 = 238;
570#[derive(Debug, Default)]
574 pub git_added: Style,
575 pub git_removed: Style,
576 pub git_modified: Style,
577 pub line_number: Style,
585 fn colored(theme: &Theme, true_color: bool) -> Self {
586 let gutter_color = theme
589 .map(|c| to_ansi_color(c, true_color))
590 .unwrap_or(Fixed(DEFAULT_GUTTER_COLOR));
593 grid: gutter_color.normal(),
594 filename: Style::new().bold(),
595 git_added: Green.normal(),
596 git_removed: Red.normal(),
597 git_modified: Yellow.normal(),
598 line_number: gutter_color.normal(),
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list