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;
24use crate::decorations::{Decoration, GridBorderDecoration, LineNumberDecoration};
25#[cfg(feature = "git")]
26use crate::decorations::LineChangesDecoration;
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;
39 handle: &mut dyn Write,
41 file_name: Option<&str>,
43 fn print_footer(&mut self, handle: &mut dyn Write) -> Result<()>;
45 fn print_snip(&mut self, handle: &mut dyn Write) -> Result<()>;
50 handle: &mut dyn Write,
56pub struct SimplePrinter;
59 pub fn new() -> Self {
64impl Printer for SimplePrinter {
67 _handle: &mut dyn Write,
69 _file_name: Option<&str>,
74 fn print_footer(&mut self, _handle: &mut dyn Write) -> Result<()> {
78 fn print_snip(&mut self, _handle: &mut dyn Write) -> Result<()> {
85 handle: &mut dyn Write,
90 handle.write_all(line_buffer)?;
96pub struct InteractivePrinter<'a> {
98 config: &'a Config<'a>,
99 decorations: Vec<Box<dyn Decoration>>,
101 ansi_prefix_sgr: String,
102 content_type: Option<ContentType>,
103 #[cfg(feature = "git")]
104 pub line_changes: Option<LineChanges>,
105 highlighter: Option<HighlightLines<'a>>,
106 syntax_set: &'a SyntaxSet,
107 background_color_highlight: Option<Color>,
110impl<'a> InteractivePrinter<'a> {
113 assets: &'a HighlightingAssets,
115 reader: &mut InputFileReader,
117 let theme = assets.get_theme(&config.theme);
119 let background_color_highlight = theme.settings.line_highlight;
121 let colors = if config.colored_output {
122 Colors::colored(theme, config.true_color)
127 // Create decorations.
128 let mut decorations: Vec<Box<dyn Decoration>> = Vec::new();
130 if config.style_components.numbers() {
131 decorations.push(Box::new(LineNumberDecoration::new(&colors)));
134 #[cfg(feature = "git")]
136 if config.style_components.changes() {
137 decorations.push(Box::new(LineChangesDecoration::new(&colors)));
141 let mut panel_width: usize =
142 decorations.len() + decorations.iter().fold(0, |a, x| a + x.width());
144 // The grid border decoration isn't added until after the panel_width calculation, since the
145 // print_horizontal_line, print_header, and print_footer functions all assume the panel
146 // width is without the grid border.
147 if config.style_components.grid() && !decorations.is_empty() {
148 decorations.push(Box::new(GridBorderDecoration::new(&colors)));
151 // Disable the panel if the terminal is too small (i.e. can't fit 5 characters with the
154 < (decorations.len() + decorations.iter().fold(0, |a, x| a + x.width())) + 5
160 #[cfg(feature = "git")]
161 let mut line_changes = None;
163 let highlighter = if reader
165 .map_or(false, |c| c.is_binary() && !config.show_nonprintable)
169 // Get the Git modifications
170 #[cfg(feature = "git")]
172 if config.style_components.changes() {
173 if let InputFile::Ordinary(filename) = file {
174 line_changes = get_git_diff(filename);
179 // Determine the type of syntax for highlighting
180 let syntax = assets.get_syntax(config.language, file, reader, &config.syntax_mapping);
181 Some(HighlightLines::new(syntax, theme))
189 content_type: reader.content_type,
190 ansi_prefix_sgr: String::new(),
191 #[cfg(feature = "git")]
194 syntax_set: &assets.syntax_set,
195 background_color_highlight,
199 fn print_horizontal_line(&mut self, handle: &mut dyn Write, grid_char: char) -> Result<()> {
200 if self.panel_width == 0 {
204 self.colors.grid.paint("─".repeat(self.config.term_width))
207 let hline = "─".repeat(self.config.term_width - (self.panel_width + 1));
208 let hline = format!("{}{}{}", "─".repeat(self.panel_width), grid_char, hline);
209 writeln!(handle, "{}", self.colors.grid.paint(hline))?;
215 fn create_fake_panel(&self, text: &str) -> String {
216 if self.panel_width == 0 {
219 let text_truncated: String = text.chars().take(self.panel_width - 1).collect();
220 let text_filled: String = format!(
223 " ".repeat(self.panel_width - 1 - text_truncated.len())
225 if self.config.style_components.grid() {
226 format!("{} │ ", text_filled)
228 format!("{}", text_filled)
233 fn preprocess(&self, text: &str, cursor: &mut usize) -> String {
234 if self.config.tab_width > 0 {
235 expand_tabs(text, self.config.tab_width, cursor)
242impl<'a> Printer for InteractivePrinter<'a> {
245 handle: &mut dyn Write,
247 file_name: Option<&str>,
249 if !self.config.style_components.header() {
250 if Some(ContentType::BINARY) == self.content_type && !self.config.show_nonprintable {
251 let input = match file {
252 InputFile::Ordinary(filename) => format!(
254 file_name.unwrap_or(&filename.to_string_lossy())
256 _ => file_name.unwrap_or("STDIN").to_owned(),
261 "{}: Binary content from {} will not be printed to the terminal \
262 (but will be present if the output of 'bat' is piped). You can use 'bat -A' \
263 to show the binary file contents.",
264 Yellow.paint("[bat warning]"),
268 if self.config.style_components.grid() {
269 self.print_horizontal_line(handle, '┬')?;
275 if self.config.style_components.grid() {
276 self.print_horizontal_line(handle, '┬')?;
281 " ".repeat(self.panel_width),
284 .paint(if self.panel_width > 0 { "│ " } else { "" }),
287 write!(handle, "{}", " ".repeat(self.panel_width))?;
290 let (prefix, name) = match file {
291 InputFile::Ordinary(filename) => (
293 Cow::from(file_name.unwrap_or(&filename.to_string_lossy()).to_owned()),
295 _ => ("File: ", Cow::from(file_name.unwrap_or("STDIN").to_owned())),
298 let mode = match self.content_type {
299 Some(ContentType::BINARY) => " <BINARY>",
300 Some(ContentType::UTF_16LE) => " <UTF-16LE>",
301 Some(ContentType::UTF_16BE) => " <UTF-16BE>",
310 self.colors.filename.paint(name),
314 if self.config.style_components.grid() {
315 if self.content_type.map_or(false, |c| c.is_text()) || self.config.show_nonprintable {
316 self.print_horizontal_line(handle, '┼')?;
318 self.print_horizontal_line(handle, '┴')?;
325 fn print_footer(&mut self, handle: &mut dyn Write) -> Result<()> {
326 if self.config.style_components.grid()
327 && (self.content_type.map_or(false, |c| c.is_text()) || self.config.show_nonprintable)
329 self.print_horizontal_line(handle, '┴')
335 fn print_snip(&mut self, handle: &mut dyn Write) -> Result<()> {
336 let panel = self.create_fake_panel(" ...");
337 let panel_count = panel.chars().count();
340 let title_count = title.chars().count();
342 let snip_left = "─ ".repeat((self.config.term_width - panel_count - (title_count / 2)) / 4);
343 let snip_left_count = snip_left.chars().count(); // Can't use .len() with Unicode.
346 " ─".repeat((self.config.term_width - panel_count - snip_left_count - title_count) / 2);
353 .paint(format!("{}{}{}{}", panel, snip_left, title, snip_right))
362 handle: &mut dyn Write,
366 let line = if self.config.show_nonprintable {
367 replace_nonprintable(&line_buffer, self.config.tab_width)
369 match self.content_type {
370 Some(ContentType::BINARY) | None => {
373 Some(ContentType::UTF_16LE) => UTF_16LE
374 .decode(&line_buffer, DecoderTrap::Replace)
375 .map_err(|_| "Invalid UTF-16LE")?,
376 Some(ContentType::UTF_16BE) => UTF_16BE
377 .decode(&line_buffer, DecoderTrap::Replace)
378 .map_err(|_| "Invalid UTF-16BE")?,
379 _ => String::from_utf8_lossy(&line_buffer).to_string(),
384 let highlighter = match self.highlighter {
385 Some(ref mut highlighter) => highlighter,
390 highlighter.highlight(line.as_ref(), self.syntax_set)
397 let mut cursor: usize = 0;
398 let mut cursor_max: usize = self.config.term_width;
399 let mut cursor_total: usize = 0;
400 let mut panel_wrap: Option<String> = None;
403 let highlight_this_line =
404 self.config.highlighted_lines.0.check(line_number) == RangeCheckResult::InRange;
406 let background_color = self
407 .background_color_highlight
408 .filter(|_| highlight_this_line);
411 if self.panel_width > 0 {
412 let decorations = self
415 .map(|ref d| d.generate(line_number, false, self))
416 .collect::<Vec<_>>();
418 for deco in decorations {
419 write!(handle, "{} ", deco.text)?;
420 cursor_max -= deco.width + 1;
425 if self.config.output_wrap == OutputWrap::None {
426 let true_color = self.config.true_color;
427 let colored_output = self.config.colored_output;
428 let italics = self.config.use_italic_text;
430 for &(style, region) in regions.iter() {
431 let text = &*self.preprocess(region, &mut cursor_total);
432 let text_trimmed = text.trim_end_matches(|c| c == '\r' || c == '\n');
446 if text.len() != text_trimmed.len() {
447 if let Some(background_color) = background_color {
448 let mut ansi_style = Style::default();
449 ansi_style.background = Some(to_ansi_color(background_color, true_color));
450 let width = if cursor_total <= cursor_max {
451 cursor_max - cursor_total + 1
455 write!(handle, "{}", ansi_style.paint(" ".repeat(width)))?;
457 write!(handle, "{}", &text[text_trimmed.len()..])?;
461 if line.bytes().next_back() != Some(b'\n') {
465 for &(style, region) in regions.iter() {
466 let ansi_iterator = AnsiCodeIterator::new(region);
467 let mut ansi_prefix: String = String::new();
468 for chunk in ansi_iterator {
470 // ANSI escape passthrough.
472 let is_ansi_csi = text.starts_with("\x1B[");
474 if is_ansi_csi && text.ends_with('m') {
475 // It's an ANSI SGR sequence.
476 // We should be mostly safe to just append these together.
477 ansi_prefix.push_str(text);
478 if text == "\x1B[0m" {
479 self.ansi_prefix_sgr = "\x1B[0m".to_owned();
481 self.ansi_prefix_sgr.push_str(text);
483 } else if is_ansi_csi {
484 // It's a regular CSI sequence.
485 // We should be mostly safe to just append these together.
486 ansi_prefix.push_str(text);
488 // It's probably a VT100 code.
489 // Passing it through is the safest bet.
490 write!(handle, "{}", text)?;
496 let text = self.preprocess(
497 text.trim_end_matches(|c| c == '\r' || c == '\n'),
501 let mut max_width = cursor_max - cursor;
503 // line buffer (avoid calling write! for every character)
504 let mut line_buf = String::with_capacity(max_width * 4);
506 // Displayed width of line_buf
507 let mut current_width = 0;
509 for c in text.chars() {
510 // calculate the displayed width for next character
511 let cw = c.width().unwrap_or(0);
514 // if next character cannot be printed on this line,
516 if current_width > max_width {
517 // Generate wrap padding if not already generated.
518 if panel_wrap.is_none() {
519 panel_wrap = if self.panel_width > 0 {
525 .generate(line_number, true, self)
527 .collect::<Vec<String>>()
543 self.ansi_prefix_sgr, ansi_prefix, line_buf
545 self.config.true_color,
546 self.config.colored_output,
547 self.config.use_italic_text,
550 panel_wrap.clone().unwrap()
554 max_width = cursor_max;
564 cursor += current_width;
572 self.ansi_prefix_sgr, ansi_prefix, line_buf
574 self.config.true_color,
575 self.config.colored_output,
576 self.config.use_italic_text,
581 // Clear the ANSI prefix buffer.
588 if let Some(background_color) = background_color {
589 let mut ansi_style = Style::default();
590 ansi_style.background =
591 Some(to_ansi_color(background_color, self.config.true_color));
596 ansi_style.paint(" ".repeat(cursor_max - cursor))
606const DEFAULT_GUTTER_COLOR: u8 = 238;
608#[derive(Debug, Default)]
612 pub git_added: Style,
613 pub git_removed: Style,
614 pub git_modified: Style,
615 pub line_number: Style,
623 fn colored(theme: &Theme, true_color: bool) -> Self {
624 let gutter_color = theme
627 .map(|c| to_ansi_color(c, true_color))
628 .unwrap_or(Fixed(DEFAULT_GUTTER_COLOR));
631 grid: gutter_color.normal(),
632 filename: Style::new().bold(),
633 git_added: Green.normal(),
634 git_removed: Red.normal(),
635 git_modified: Yellow.normal(),
636 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