5use ansi_term::Colour::{Fixed, Green, Red, Yellow};
8use console::AnsiCodeIterator;
10use syntect::easy::HighlightLines;
11use syntect::highlighting::Color;
12use syntect::highlighting::Theme;
13use syntect::parsing::SyntaxSet;
15use content_inspector::ContentType;
17use encoding::all::{UTF_16BE, UTF_16LE};
18use encoding::{DecoderTrap, Encoding};
20use crate::assets::HighlightingAssets;
21use crate::decorations::{
22 Decoration, GridBorderDecoration, LineChangesDecoration, LineNumberDecoration,
24use crate::diff::get_git_diff;
25use crate::diff::LineChanges;
27use crate::inputfile::{InputFile, InputFileReader};
28use crate::line_range::RangeCheckResult;
29use crate::preprocessor::{expand_tabs, replace_nonprintable};
30use crate::style::OutputWrap;
31use crate::terminal::{as_terminal_escaped, to_ansi_color};
35 fn print_header(&mut self, handle: &mut dyn Write, file: InputFile) -> Result<()>;
36 fn print_footer(&mut self, handle: &mut dyn Write) -> Result<()>;
38 fn print_snip(&mut self, handle: &mut dyn Write) -> Result<()>;
43 handle: &mut dyn Write,
49pub struct SimplePrinter;
52 pub fn new() -> Self {
57impl Printer for SimplePrinter {
58 fn print_header(&mut self, _handle: &mut dyn Write, _file: InputFile) -> Result<()> {
62 fn print_footer(&mut self, _handle: &mut dyn Write) -> Result<()> {
66 fn print_snip(&mut self, _handle: &mut dyn Write) -> Result<()> {
73 handle: &mut dyn Write,
78 handle.write_all(line_buffer)?;
84pub struct InteractivePrinter<'a> {
86 config: &'a Config<'a>,
87 decorations: Vec<Box<dyn Decoration>>,
89 ansi_prefix_sgr: String,
90 content_type: Option<ContentType>,
91 pub line_changes: Option<LineChanges>,
92 highlighter: Option<HighlightLines<'a>>,
93 syntax_set: &'a SyntaxSet,
94 background_color_highlight: Option<Color>,
97impl<'a> InteractivePrinter<'a> {
100 assets: &'a HighlightingAssets,
102 reader: &mut InputFileReader,
104 let theme = assets.get_theme(&config.theme);
106 let background_color_highlight = theme.settings.line_highlight;
108 let colors = if config.colored_output {
109 Colors::colored(theme, config.true_color)
114 // Create decorations.
115 let mut decorations: Vec<Box<dyn Decoration>> = Vec::new();
117 if config.output_components.numbers() {
118 decorations.push(Box::new(LineNumberDecoration::new(&colors)));
121 if config.output_components.changes() {
122 decorations.push(Box::new(LineChangesDecoration::new(&colors)));
125 let mut panel_width: usize =
126 decorations.len() + decorations.iter().fold(0, |a, x| a + x.width());
128 // The grid border decoration isn't added until after the panel_width calculation, since the
129 // print_horizontal_line, print_header, and print_footer functions all assume the panel
130 // width is without the grid border.
131 if config.output_components.grid() && !decorations.is_empty() {
132 decorations.push(Box::new(GridBorderDecoration::new(&colors)));
135 // Disable the panel if the terminal is too small (i.e. can't fit 5 characters with the
138 < (decorations.len() + decorations.iter().fold(0, |a, x| a + x.width())) + 5
144 let mut line_changes = None;
146 let highlighter = if reader
148 .map_or(false, |c| c.is_binary() && !config.show_nonprintable)
152 // Get the Git modifications
153 line_changes = if config.output_components.changes() {
155 InputFile::Ordinary(filename) => get_git_diff(filename),
162 // Determine the type of syntax for highlighting
163 let syntax = assets.get_syntax(config.language, file, reader, &config.syntax_mapping);
164 Some(HighlightLines::new(syntax, theme))
172 content_type: reader.content_type,
173 ansi_prefix_sgr: String::new(),
176 syntax_set: &assets.syntax_set,
177 background_color_highlight,
181 fn print_horizontal_line(&mut self, handle: &mut dyn Write, grid_char: char) -> Result<()> {
182 if self.panel_width == 0 {
186 self.colors.grid.paint("─".repeat(self.config.term_width))
189 let hline = "─".repeat(self.config.term_width - (self.panel_width + 1));
190 let hline = format!("{}{}{}", "─".repeat(self.panel_width), grid_char, hline);
191 writeln!(handle, "{}", self.colors.grid.paint(hline))?;
197 fn create_fake_panel(&self, text: &str) -> String {
198 if self.panel_width == 0 {
201 let text_truncated: String = text.chars().take(self.panel_width - 1).collect();
202 let text_filled: String = format!(
205 " ".repeat(self.panel_width - 1 - text_truncated.len())
207 if self.config.output_components.grid() {
208 format!("{} │ ", text_filled)
210 format!("{}", text_filled)
215 fn preprocess(&self, text: &str, cursor: &mut usize) -> String {
216 if self.config.tab_width > 0 {
217 expand_tabs(text, self.config.tab_width, cursor)
224impl<'a> Printer for InteractivePrinter<'a> {
225 fn print_header(&mut self, handle: &mut dyn Write, file: InputFile) -> Result<()> {
226 if !self.config.output_components.header() {
227 if Some(ContentType::BINARY) == self.content_type && !self.config.show_nonprintable {
228 let input = match file {
229 InputFile::Ordinary(filename) => format!("file '{}'", filename.to_string_lossy()),
235 "{}: Binary content from {} will not be printed to the terminal \
236 (but will be present if the output of 'bat' is piped). You can use 'bat -A' \
237 to show the binary file contents.",
238 Yellow.paint("[bat warning]"),
242 if self.config.output_components.grid() {
243 self.print_horizontal_line(handle, '┬')?;
249 if self.config.output_components.grid() {
250 self.print_horizontal_line(handle, '┬')?;
255 " ".repeat(self.panel_width),
258 .paint(if self.panel_width > 0 { "│ " } else { "" }),
261 write!(handle, "{}", " ".repeat(self.panel_width))?;
264 let (prefix, name) = match file {
265 InputFile::Ordinary(filename) => ("File: ", filename.to_string_lossy()),
266 _ => ("", Cow::from("STDIN")),
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>",
281 self.colors.filename.paint(name),
285 if self.config.output_components.grid() {
286 if self.content_type.map_or(false, |c| c.is_text()) || self.config.show_nonprintable {
287 self.print_horizontal_line(handle, '┼')?;
289 self.print_horizontal_line(handle, '┴')?;
296 fn print_footer(&mut self, handle: &mut dyn Write) -> Result<()> {
297 if self.config.output_components.grid()
298 && (self.content_type.map_or(false, |c| c.is_text()) || self.config.show_nonprintable)
300 self.print_horizontal_line(handle, '┴')
306 fn print_snip(&mut self, handle: &mut dyn Write) -> Result<()> {
307 let panel = self.create_fake_panel(" ...");
308 let panel_count = panel.chars().count();
311 let title_count = title.chars().count();
313 let snip_left = "─ ".repeat((self.config.term_width - panel_count - (title_count / 2)) / 4);
314 let snip_left_count = snip_left.chars().count(); // Can't use .len() with Unicode.
317 " ─".repeat((self.config.term_width - panel_count - snip_left_count - title_count) / 2);
324 .paint(format!("{}{}{}{}", panel, snip_left, title, snip_right))
333 handle: &mut dyn Write,
337 let line = if self.config.show_nonprintable {
338 replace_nonprintable(&line_buffer, self.config.tab_width)
340 match self.content_type {
341 Some(ContentType::BINARY) | None => {
344 Some(ContentType::UTF_16LE) => UTF_16LE
345 .decode(&line_buffer, DecoderTrap::Replace)
346 .map_err(|_| "Invalid UTF-16LE")?,
347 Some(ContentType::UTF_16BE) => UTF_16BE
348 .decode(&line_buffer, DecoderTrap::Replace)
349 .map_err(|_| "Invalid UTF-16BE")?,
350 _ => String::from_utf8_lossy(&line_buffer).to_string(),
355 let highlighter = match self.highlighter {
356 Some(ref mut highlighter) => highlighter,
361 highlighter.highlight(line.as_ref(), self.syntax_set)
368 let mut cursor: usize = 0;
369 let mut cursor_max: usize = self.config.term_width;
370 let mut cursor_total: usize = 0;
371 let mut panel_wrap: Option<String> = None;
374 let highlight_this_line =
375 self.config.highlight_lines.check(line_number) == RangeCheckResult::InRange;
377 let background_color = self
378 .background_color_highlight
379 .filter(|_| highlight_this_line);
382 if self.panel_width > 0 {
383 let decorations = self
386 .map(|ref d| d.generate(line_number, false, self))
387 .collect::<Vec<_>>();
389 for deco in decorations {
390 write!(handle, "{} ", deco.text)?;
391 cursor_max -= deco.width + 1;
396 if self.config.output_wrap == OutputWrap::None {
397 let true_color = self.config.true_color;
398 let colored_output = self.config.colored_output;
399 let italics = self.config.use_italic_text;
401 for &(style, region) in regions.iter() {
402 let text = &*self.preprocess(region, &mut cursor_total);
403 let text_trimmed = text.trim_end_matches(|c| c == '\r' || c == '\n');
417 if text.len() != text_trimmed.len() {
418 if let Some(background_color) = background_color {
419 let mut ansi_style = Style::default();
420 ansi_style.background = Some(to_ansi_color(background_color, true_color));
421 let width = if cursor_total <= cursor_max {
422 cursor_max - cursor_total + 1
426 write!(handle, "{}", ansi_style.paint(" ".repeat(width)))?;
428 write!(handle, "{}", &text[text_trimmed.len()..])?;
432 if line.bytes().next_back() != Some(b'\n') {
436 for &(style, region) in regions.iter() {
437 let ansi_iterator = AnsiCodeIterator::new(region);
438 let mut ansi_prefix: String = String::new();
439 for chunk in ansi_iterator {
441 // ANSI escape passthrough.
443 let is_ansi_csi = text.starts_with("\x1B[");
445 if is_ansi_csi && text.ends_with('m') {
446 // It's an ANSI SGR sequence.
447 // We should be mostly safe to just append these together.
448 ansi_prefix.push_str(text);
449 if text == "\x1B[0m" {
450 self.ansi_prefix_sgr = "\x1B[0m".to_owned();
452 self.ansi_prefix_sgr.push_str(text);
454 } else if is_ansi_csi {
455 // It's a regular CSI sequence.
456 // We should be mostly safe to just append these together.
457 ansi_prefix.push_str(text);
459 // It's probably a VT100 code.
460 // Passing it through is the safest bet.
461 write!(handle, "{}", text)?;
467 let text = self.preprocess(
468 text.trim_end_matches(|c| c == '\r' || c == '\n'),
472 let mut chars = text.chars();
473 let mut remaining = text.chars().count();
475 while remaining > 0 {
476 let available = cursor_max - cursor;
479 if remaining <= available {
480 let text = chars.by_ref().take(remaining).collect::<String>();
490 self.ansi_prefix_sgr, ansi_prefix, text
492 self.config.true_color,
493 self.config.colored_output,
494 self.config.use_italic_text,
501 // Generate wrap padding if not already generated.
502 if panel_wrap.is_none() {
503 panel_wrap = if self.panel_width > 0 {
509 .generate(line_number, true, self)
511 .collect::<Vec<String>>()
520 let text = chars.by_ref().take(available).collect::<String>();
522 remaining -= available;
531 self.ansi_prefix_sgr, ansi_prefix, text
533 self.config.true_color,
534 self.config.colored_output,
535 self.config.use_italic_text,
538 panel_wrap.clone().unwrap()
542 // Clear the ANSI prefix buffer.
549 if let Some(background_color) = background_color {
550 let mut ansi_style = Style::default();
551 ansi_style.background =
552 Some(to_ansi_color(background_color, self.config.true_color));
557 ansi_style.paint(" ".repeat(cursor_max - cursor))
567const DEFAULT_GUTTER_COLOR: u8 = 238;
569#[derive(Debug, Default)]
573 pub git_added: Style,
574 pub git_removed: Style,
575 pub git_modified: Style,
576 pub line_number: Style,
584 fn colored(theme: &Theme, true_color: bool) -> Self {
585 let gutter_color = theme
588 .map(|c| to_ansi_color(c, true_color))
589 .unwrap_or(Fixed(DEFAULT_GUTTER_COLOR));
592 grid: gutter_color.normal(),
593 filename: Style::new().bold(),
594 git_added: Green.normal(),
595 git_removed: Red.normal(),
596 git_modified: Yellow.normal(),
597 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