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 unicode_width::UnicodeWidthChar;
22use crate::assets::HighlightingAssets;
23use crate::config::Config;
24#[cfg(feature = "git")]
25use crate::decorations::LineChangesDecoration;
26use crate::decorations::{Decoration, GridBorderDecoration, LineNumberDecoration};
27#[cfg(feature = "git")]
28use crate::diff::{get_git_diff, LineChanges};
30use crate::inputfile::{InputFile, InputFileReader};
31use crate::line_range::RangeCheckResult;
32use crate::preprocessor::{expand_tabs, replace_nonprintable};
33use crate::terminal::{as_terminal_escaped, to_ansi_color};
34use crate::wrap::OutputWrap;
37 fn print_header(&mut self, handle: &mut dyn Write, file: InputFile) -> Result<()>;
38 fn print_footer(&mut self, handle: &mut dyn Write) -> Result<()>;
40 fn print_snip(&mut self, handle: &mut dyn Write) -> Result<()>;
45 handle: &mut dyn Write,
51pub struct SimplePrinter;
54 pub fn new() -> Self {
59impl Printer for SimplePrinter {
60 fn print_header(&mut self, _handle: &mut dyn Write, _file: InputFile) -> Result<()> {
64 fn print_footer(&mut self, _handle: &mut dyn Write) -> Result<()> {
68 fn print_snip(&mut self, _handle: &mut dyn Write) -> Result<()> {
75 handle: &mut dyn Write,
80 handle.write_all(line_buffer)?;
86pub struct InteractivePrinter<'a> {
88 config: &'a Config<'a>,
89 decorations: Vec<Box<dyn Decoration>>,
91 ansi_prefix_sgr: String,
92 content_type: Option<ContentType>,
93 #[cfg(feature = "git")]
94 pub line_changes: Option<LineChanges>,
95 highlighter: Option<HighlightLines<'a>>,
96 syntax_set: &'a SyntaxSet,
97 background_color_highlight: Option<Color>,
100impl<'a> InteractivePrinter<'a> {
103 assets: &'a HighlightingAssets,
105 reader: &mut InputFileReader,
107 let theme = assets.get_theme(&config.theme);
109 let background_color_highlight = theme.settings.line_highlight;
111 let colors = if config.colored_output {
112 Colors::colored(theme, config.true_color)
117 // Create decorations.
118 let mut decorations: Vec<Box<dyn Decoration>> = Vec::new();
120 if config.style_components.numbers() {
121 decorations.push(Box::new(LineNumberDecoration::new(&colors)));
124 #[cfg(feature = "git")]
126 if config.style_components.changes() {
127 decorations.push(Box::new(LineChangesDecoration::new(&colors)));
131 let mut panel_width: usize =
132 decorations.len() + decorations.iter().fold(0, |a, x| a + x.width());
134 // The grid border decoration isn't added until after the panel_width calculation, since the
135 // print_horizontal_line, print_header, and print_footer functions all assume the panel
136 // width is without the grid border.
137 if config.style_components.grid() && !decorations.is_empty() {
138 decorations.push(Box::new(GridBorderDecoration::new(&colors)));
141 // Disable the panel if the terminal is too small (i.e. can't fit 5 characters with the
144 < (decorations.len() + decorations.iter().fold(0, |a, x| a + x.width())) + 5
150 #[cfg(feature = "git")]
151 let mut line_changes = None;
153 let highlighter = if reader
155 .map_or(false, |c| c.is_binary() && !config.show_nonprintable)
159 // Get the Git modifications
160 #[cfg(feature = "git")]
162 if config.style_components.changes() {
163 if let InputFile::Ordinary(ofile) = file {
164 line_changes = get_git_diff(ofile.provided_path());
169 // Determine the type of syntax for highlighting
170 let syntax = assets.get_syntax(config.language, file, reader, &config.syntax_mapping);
171 Some(HighlightLines::new(syntax, theme))
179 content_type: reader.content_type,
180 ansi_prefix_sgr: String::new(),
181 #[cfg(feature = "git")]
184 syntax_set: &assets.syntax_set,
185 background_color_highlight,
189 fn print_horizontal_line(&mut self, handle: &mut dyn Write, grid_char: char) -> Result<()> {
190 if self.panel_width == 0 {
194 self.colors.grid.paint("─".repeat(self.config.term_width))
197 let hline = "─".repeat(self.config.term_width - (self.panel_width + 1));
198 let hline = format!("{}{}{}", "─".repeat(self.panel_width), grid_char, hline);
199 writeln!(handle, "{}", self.colors.grid.paint(hline))?;
205 fn create_fake_panel(&self, text: &str) -> String {
206 if self.panel_width == 0 {
209 let text_truncated: String = text.chars().take(self.panel_width - 1).collect();
210 let text_filled: String = format!(
213 " ".repeat(self.panel_width - 1 - text_truncated.len())
215 if self.config.style_components.grid() {
216 format!("{} │ ", text_filled)
218 format!("{}", text_filled)
223 fn preprocess(&self, text: &str, cursor: &mut usize) -> String {
224 if self.config.tab_width > 0 {
225 expand_tabs(text, self.config.tab_width, cursor)
232impl<'a> Printer for InteractivePrinter<'a> {
233 fn print_header(&mut self, handle: &mut dyn Write, file: InputFile) -> Result<()> {
234 if !self.config.style_components.header() {
235 if Some(ContentType::BINARY) == self.content_type && !self.config.show_nonprintable {
236 let input = match file {
237 InputFile::Ordinary(ofile) => {
238 format!("file '{}'", &ofile.provided_path().to_string_lossy())
240 InputFile::StdIn(Some(name)) => format!(
241 "STDIN (with name '{}')",
242 name.to_string_lossy().into_owned()
244 InputFile::StdIn(None) => "STDIN".to_owned(),
245 InputFile::ThemePreviewFile => "".to_owned(),
250 "{}: Binary content from {} will not be printed to the terminal \
251 (but will be present if the output of 'bat' is piped). You can use 'bat -A' \
252 to show the binary file contents.",
253 Yellow.paint("[bat warning]"),
257 if self.config.style_components.grid() {
258 self.print_horizontal_line(handle, '┬')?;
264 if self.config.style_components.grid() {
265 self.print_horizontal_line(handle, '┬')?;
270 " ".repeat(self.panel_width),
273 .paint(if self.panel_width > 0 { "│ " } else { "" }),
276 write!(handle, "{}", " ".repeat(self.panel_width))?;
279 let (prefix, name) = match file {
280 InputFile::Ordinary(ofile) => (
282 Cow::from(ofile.provided_path().to_string_lossy().to_owned()),
284 InputFile::StdIn(Some(name)) => {
285 ("File: ", Cow::from(name.to_string_lossy().to_owned()))
287 InputFile::StdIn(None) => ("File: ", Cow::from("STDIN".to_owned())),
288 InputFile::ThemePreviewFile => ("", Cow::from("")),
291 let mode = match self.content_type {
292 Some(ContentType::BINARY) => " <BINARY>",
293 Some(ContentType::UTF_16LE) => " <UTF-16LE>",
294 Some(ContentType::UTF_16BE) => " <UTF-16BE>",
303 self.colors.filename.paint(name),
307 if self.config.style_components.grid() {
308 if self.content_type.map_or(false, |c| c.is_text()) || self.config.show_nonprintable {
309 self.print_horizontal_line(handle, '┼')?;
311 self.print_horizontal_line(handle, '┴')?;
318 fn print_footer(&mut self, handle: &mut dyn Write) -> Result<()> {
319 if self.config.style_components.grid()
320 && (self.content_type.map_or(false, |c| c.is_text()) || self.config.show_nonprintable)
322 self.print_horizontal_line(handle, '┴')
328 fn print_snip(&mut self, handle: &mut dyn Write) -> Result<()> {
329 let panel = self.create_fake_panel(" ...");
330 let panel_count = panel.chars().count();
333 let title_count = title.chars().count();
335 let snip_left = "─ ".repeat((self.config.term_width - panel_count - (title_count / 2)) / 4);
336 let snip_left_count = snip_left.chars().count(); // Can't use .len() with Unicode.
339 " ─".repeat((self.config.term_width - panel_count - snip_left_count - title_count) / 2);
346 .paint(format!("{}{}{}{}", panel, snip_left, title, snip_right))
355 handle: &mut dyn Write,
359 let line = if self.config.show_nonprintable {
360 replace_nonprintable(&line_buffer, self.config.tab_width)
362 match self.content_type {
363 Some(ContentType::BINARY) | None => {
366 Some(ContentType::UTF_16LE) => UTF_16LE
367 .decode(&line_buffer, DecoderTrap::Replace)
368 .map_err(|_| "Invalid UTF-16LE")?,
369 Some(ContentType::UTF_16BE) => UTF_16BE
370 .decode(&line_buffer, DecoderTrap::Replace)
371 .map_err(|_| "Invalid UTF-16BE")?,
372 _ => String::from_utf8_lossy(&line_buffer).to_string(),
377 let highlighter = match self.highlighter {
378 Some(ref mut highlighter) => highlighter,
383 highlighter.highlight(line.as_ref(), self.syntax_set)
390 let mut cursor: usize = 0;
391 let mut cursor_max: usize = self.config.term_width;
392 let mut cursor_total: usize = 0;
393 let mut panel_wrap: Option<String> = None;
396 let highlight_this_line =
397 self.config.highlighted_lines.0.check(line_number) == RangeCheckResult::InRange;
399 let background_color = self
400 .background_color_highlight
401 .filter(|_| highlight_this_line);
404 if self.panel_width > 0 {
405 let decorations = self
408 .map(|ref d| d.generate(line_number, false, self))
409 .collect::<Vec<_>>();
411 for deco in decorations {
412 write!(handle, "{} ", deco.text)?;
413 cursor_max -= deco.width + 1;
418 if self.config.output_wrap == OutputWrap::None {
419 let true_color = self.config.true_color;
420 let colored_output = self.config.colored_output;
421 let italics = self.config.use_italic_text;
423 for &(style, region) in regions.iter() {
424 let text = &*self.preprocess(region, &mut cursor_total);
425 let text_trimmed = text.trim_end_matches(|c| c == '\r' || c == '\n');
439 if text.len() != text_trimmed.len() {
440 if let Some(background_color) = background_color {
441 let mut ansi_style = Style::default();
442 ansi_style.background = Some(to_ansi_color(background_color, true_color));
443 let width = if cursor_total <= cursor_max {
444 cursor_max - cursor_total + 1
448 write!(handle, "{}", ansi_style.paint(" ".repeat(width)))?;
450 write!(handle, "{}", &text[text_trimmed.len()..])?;
454 if line.bytes().next_back() != Some(b'\n') {
458 for &(style, region) in regions.iter() {
459 let ansi_iterator = AnsiCodeIterator::new(region);
460 let mut ansi_prefix: String = String::new();
461 for chunk in ansi_iterator {
463 // ANSI escape passthrough.
465 let is_ansi_csi = text.starts_with("\x1B[");
467 if is_ansi_csi && text.ends_with('m') {
468 // It's an ANSI SGR sequence.
469 // We should be mostly safe to just append these together.
470 ansi_prefix.push_str(text);
471 if text == "\x1B[0m" {
472 self.ansi_prefix_sgr = "\x1B[0m".to_owned();
474 self.ansi_prefix_sgr.push_str(text);
476 } else if is_ansi_csi {
477 // It's a regular CSI sequence.
478 // We should be mostly safe to just append these together.
479 ansi_prefix.push_str(text);
481 // It's probably a VT100 code.
482 // Passing it through is the safest bet.
483 write!(handle, "{}", text)?;
489 let text = self.preprocess(
490 text.trim_end_matches(|c| c == '\r' || c == '\n'),
494 let mut max_width = cursor_max - cursor;
496 // line buffer (avoid calling write! for every character)
497 let mut line_buf = String::with_capacity(max_width * 4);
499 // Displayed width of line_buf
500 let mut current_width = 0;
502 for c in text.chars() {
503 // calculate the displayed width for next character
504 let cw = c.width().unwrap_or(0);
507 // if next character cannot be printed on this line,
509 if current_width > max_width {
510 // Generate wrap padding if not already generated.
511 if panel_wrap.is_none() {
512 panel_wrap = if self.panel_width > 0 {
518 .generate(line_number, true, self)
520 .collect::<Vec<String>>()
536 self.ansi_prefix_sgr, ansi_prefix, line_buf
538 self.config.true_color,
539 self.config.colored_output,
540 self.config.use_italic_text,
543 panel_wrap.clone().unwrap()
547 max_width = cursor_max;
557 cursor += current_width;
565 self.ansi_prefix_sgr, ansi_prefix, line_buf
567 self.config.true_color,
568 self.config.colored_output,
569 self.config.use_italic_text,
574 // Clear the ANSI prefix buffer.
581 if let Some(background_color) = background_color {
582 let mut ansi_style = Style::default();
583 ansi_style.background =
584 Some(to_ansi_color(background_color, self.config.true_color));
589 ansi_style.paint(" ".repeat(cursor_max - cursor))
599const DEFAULT_GUTTER_COLOR: u8 = 238;
601#[derive(Debug, Default)]
605 pub git_added: Style,
606 pub git_removed: Style,
607 pub git_modified: Style,
608 pub line_number: Style,
616 fn colored(theme: &Theme, true_color: bool) -> Self {
617 let gutter_color = theme
620 .map(|c| to_ansi_color(c, true_color))
621 .unwrap_or(Fixed(DEFAULT_GUTTER_COLOR));
624 grid: gutter_color.normal(),
625 filename: Style::new().bold(),
626 git_added: Green.normal(),
627 git_removed: Red.normal(),
628 git_modified: Yellow.normal(),
629 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