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 unicode_width::UnicodeWidthChar;
21use crate::assets::{HighlightingAssets, SyntaxReferenceInSet};
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;
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 {
38 handle: &mut dyn Write,
40 add_header_padding: bool,
42 fn print_footer(&mut self, handle: &mut dyn Write, input: &OpenedInput) -> Result<()>;
44 fn print_snip(&mut self, handle: &mut dyn Write) -> Result<()>;
49 handle: &mut dyn Write,
55pub struct SimplePrinter<'a> {
56 config: &'a Config<'a>,
59impl<'a> SimplePrinter<'a> {
60 pub fn new(config: &'a Config) -> Self {
61 SimplePrinter { config }
65impl<'a> Printer for SimplePrinter<'a> {
68 _handle: &mut dyn Write,
70 _add_header_padding: bool,
75 fn print_footer(&mut self, _handle: &mut dyn Write, _input: &OpenedInput) -> Result<()> {
79 fn print_snip(&mut self, _handle: &mut dyn Write) -> Result<()> {
86 handle: &mut dyn Write,
91 if self.config.show_nonprintable {
92 let line = replace_nonprintable(line_buffer, self.config.tab_width);
93 write!(handle, "{}", line)?;
95 handle.write_all(line_buffer)?
102pub(crate) struct InteractivePrinter<'a> {
104 config: &'a Config<'a>,
105 decorations: Vec<Box<dyn Decoration>>,
107 ansi_prefix_sgr: String,
108 content_type: Option<ContentType>,
109 #[cfg(feature = "git")]
110 pub line_changes: &'a Option<LineChanges>,
111 highlighter: Option<HighlightLines<'a>>,
112 syntax_set: &'a SyntaxSet,
113 background_color_highlight: Option<Color>,
116impl<'a> InteractivePrinter<'a> {
119 assets: &'a HighlightingAssets,
120 input: &mut OpenedInput,
121 #[cfg(feature = "git")] line_changes: &'a Option<LineChanges>,
123 let theme = assets.get_theme(&config.theme);
125 let background_color_highlight = theme.settings.line_highlight;
127 let colors = if config.colored_output {
128 Colors::colored(theme, config.true_color)
133 // Create decorations.
134 let mut decorations: Vec<Box<dyn Decoration>> = Vec::new();
136 if config.style_components.numbers() {
137 decorations.push(Box::new(LineNumberDecoration::new(&colors)));
140 #[cfg(feature = "git")]
142 if config.style_components.changes() {
143 decorations.push(Box::new(LineChangesDecoration::new(&colors)));
147 let mut panel_width: usize =
148 decorations.len() + decorations.iter().fold(0, |a, x| a + x.width());
150 // The grid border decoration isn't added until after the panel_width calculation, since the
151 // print_horizontal_line, print_header, and print_footer functions all assume the panel
152 // width is without the grid border.
153 if config.style_components.grid() && !decorations.is_empty() {
154 decorations.push(Box::new(GridBorderDecoration::new(&colors)));
157 // Disable the panel if the terminal is too small (i.e. can't fit 5 characters with the
160 < (decorations.len() + decorations.iter().fold(0, |a, x| a + x.width())) + 5
166 let (highlighter, syntax_set) = if input
169 .map_or(false, |c| c.is_binary() && !config.show_nonprintable)
171 (None, assets.get_syntax_set()?)
173 // Determine the type of syntax for highlighting
175 match assets.get_syntax(config.language, input, &config.syntax_mapping) {
176 Ok(syntax_in_set) => syntax_in_set,
177 Err(Error(ErrorKind::UndetectedSyntax(_), _)) => {
178 let syntax_set = assets.get_syntax_set()?;
179 let syntax = syntax_set.find_syntax_plain_text();
180 SyntaxReferenceInSet { syntax, syntax_set }
182 Err(e) => return Err(e),
186 Some(HighlightLines::new(syntax_in_set.syntax, theme)),
187 syntax_in_set.syntax_set,
191 Ok(InteractivePrinter {
196 content_type: input.reader.content_type,
197 ansi_prefix_sgr: String::new(),
198 #[cfg(feature = "git")]
202 background_color_highlight,
206 fn print_horizontal_line_term(&mut self, handle: &mut dyn Write, style: Style) -> Result<()> {
210 style.paint("─".repeat(self.config.term_width))
215 fn print_horizontal_line(&mut self, handle: &mut dyn Write, grid_char: char) -> Result<()> {
216 if self.panel_width == 0 {
217 self.print_horizontal_line_term(handle, self.colors.grid)?;
219 let hline = "─".repeat(self.config.term_width - (self.panel_width + 1));
220 let hline = format!("{}{}{}", "─".repeat(self.panel_width), grid_char, hline);
221 writeln!(handle, "{}", self.colors.grid.paint(hline))?;
227 fn create_fake_panel(&self, text: &str) -> String {
228 if self.panel_width == 0 {
231 let text_truncated: String = text.chars().take(self.panel_width - 1).collect();
232 let text_filled: String = format!(
235 " ".repeat(self.panel_width - 1 - text_truncated.len())
237 if self.config.style_components.grid() {
238 format!("{} │ ", text_filled)
245 fn preprocess(&self, text: &str, cursor: &mut usize) -> String {
246 if self.config.tab_width > 0 {
247 expand_tabs(text, self.config.tab_width, cursor)
249 *cursor += text.len();
255impl<'a> Printer for InteractivePrinter<'a> {
258 handle: &mut dyn Write,
260 add_header_padding: bool,
262 if add_header_padding && self.config.style_components.rule() {
263 self.print_horizontal_line_term(handle, self.colors.rule)?;
266 if !self.config.style_components.header() {
267 if Some(ContentType::BINARY) == self.content_type && !self.config.show_nonprintable {
270 "{}: Binary content from {} will not be printed to the terminal \
271 (but will be present if the output of 'bat' is piped). You can use 'bat -A' \
272 to show the binary file contents.",
273 Yellow.paint("[bat warning]"),
274 input.description.summary(),
276 } else if self.config.style_components.grid() {
277 self.print_horizontal_line(handle, '┬')?;
282 if self.config.style_components.grid() {
283 self.print_horizontal_line(handle, '┬')?;
288 " ".repeat(self.panel_width),
291 .paint(if self.panel_width > 0 { "│ " } else { "" }),
294 // Only pad space between files, if we haven't already drawn a horizontal rule
295 if add_header_padding && !self.config.style_components.rule() {
298 write!(handle, "{}", " ".repeat(self.panel_width))?;
301 let mode = match self.content_type {
302 Some(ContentType::BINARY) => " <BINARY>",
303 Some(ContentType::UTF_16LE) => " <UTF-16LE>",
304 Some(ContentType::UTF_16BE) => " <UTF-16BE>",
309 let description = &input.description;
316 .map(|kind| format!("{}: ", kind))
317 .unwrap_or_else(|| "".into()),
318 self.colors.filename.paint(description.title()),
322 if self.config.style_components.grid() {
323 if self.content_type.map_or(false, |c| c.is_text()) || self.config.show_nonprintable {
324 self.print_horizontal_line(handle, '┼')?;
326 self.print_horizontal_line(handle, '┴')?;
333 fn print_footer(&mut self, handle: &mut dyn Write, _input: &OpenedInput) -> Result<()> {
334 if self.config.style_components.grid()
335 && (self.content_type.map_or(false, |c| c.is_text()) || self.config.show_nonprintable)
337 self.print_horizontal_line(handle, '┴')
343 fn print_snip(&mut self, handle: &mut dyn Write) -> Result<()> {
344 let panel = self.create_fake_panel(" ...");
345 let panel_count = panel.chars().count();
348 let title_count = title.chars().count();
350 let snip_left = "─ ".repeat((self.config.term_width - panel_count - (title_count / 2)) / 4);
351 let snip_left_count = snip_left.chars().count(); // Can't use .len() with Unicode.
354 " ─".repeat((self.config.term_width - panel_count - snip_left_count - title_count) / 2);
361 .paint(format!("{}{}{}{}", panel, snip_left, title, snip_right))
370 handle: &mut dyn Write,
374 let line = if self.config.show_nonprintable {
375 replace_nonprintable(&line_buffer, self.config.tab_width)
377 match self.content_type {
378 Some(ContentType::BINARY) | None => {
381 Some(ContentType::UTF_16LE) => UTF_16LE
382 .decode(&line_buffer, DecoderTrap::Replace)
383 .map_err(|_| "Invalid UTF-16LE")?,
384 Some(ContentType::UTF_16BE) => UTF_16BE
385 .decode(&line_buffer, DecoderTrap::Replace)
386 .map_err(|_| "Invalid UTF-16BE")?,
387 _ => String::from_utf8_lossy(&line_buffer).to_string(),
392 let highlighter = match self.highlighter {
393 Some(ref mut highlighter) => highlighter,
398 highlighter.highlight(line.as_ref(), self.syntax_set)
405 let mut cursor: usize = 0;
406 let mut cursor_max: usize = self.config.term_width;
407 let mut cursor_total: usize = 0;
408 let mut panel_wrap: Option<String> = None;
411 let highlight_this_line =
412 self.config.highlighted_lines.0.check(line_number) == RangeCheckResult::InRange;
414 let background_color = self
415 .background_color_highlight
416 .filter(|_| highlight_this_line);
419 if self.panel_width > 0 {
420 let decorations = self
423 .map(|ref d| d.generate(line_number, false, self))
424 .collect::<Vec<_>>();
426 for deco in decorations {
427 write!(handle, "{} ", deco.text)?;
428 cursor_max -= deco.width + 1;
433 if matches!(self.config.wrapping_mode, WrappingMode::NoWrapping(_)) {
434 let true_color = self.config.true_color;
435 let colored_output = self.config.colored_output;
436 let italics = self.config.use_italic_text;
438 for &(style, region) in regions.iter() {
439 let text = &*self.preprocess(region, &mut cursor_total);
440 let text_trimmed = text.trim_end_matches(|c| c == '\r' || c == '\n');
454 if text.len() != text_trimmed.len() {
455 if let Some(background_color) = background_color {
456 let ansi_style = Style {
457 background: to_ansi_color(background_color, true_color),
460 let width = if cursor_total <= cursor_max {
461 cursor_max - cursor_total + 1
465 write!(handle, "{}", ansi_style.paint(" ".repeat(width)))?;
467 write!(handle, "{}", &text[text_trimmed.len()..])?;
471 if !self.config.style_components.plain() && line.bytes().next_back() != Some(b'\n') {
475 for &(style, region) in regions.iter() {
476 let ansi_iterator = AnsiCodeIterator::new(region);
477 let mut ansi_prefix: String = String::new();
478 for chunk in ansi_iterator {
480 // ANSI escape passthrough.
482 let is_ansi_csi = text.starts_with("\x1B[");
484 if is_ansi_csi && text.ends_with('m') {
485 // It's an ANSI SGR sequence.
486 // We should be mostly safe to just append these together.
487 ansi_prefix.push_str(text);
488 if text == "\x1B[0m" {
489 self.ansi_prefix_sgr = "\x1B[0m".to_owned();
491 self.ansi_prefix_sgr.push_str(text);
493 } else if is_ansi_csi {
494 // It's a regular CSI sequence.
495 // We should be mostly safe to just append these together.
496 ansi_prefix.push_str(text);
498 // It's probably a VT100 code.
499 // Passing it through is the safest bet.
500 write!(handle, "{}", text)?;
506 let text = self.preprocess(
507 text.trim_end_matches(|c| c == '\r' || c == '\n'),
511 let mut max_width = cursor_max - cursor;
513 // line buffer (avoid calling write! for every character)
514 let mut line_buf = String::with_capacity(max_width * 4);
516 // Displayed width of line_buf
517 let mut current_width = 0;
519 for c in text.chars() {
520 // calculate the displayed width for next character
521 let cw = c.width().unwrap_or(0);
524 // if next character cannot be printed on this line,
526 if current_width > max_width {
527 // Generate wrap padding if not already generated.
528 if panel_wrap.is_none() {
529 panel_wrap = if self.panel_width > 0 {
535 .generate(line_number, true, self)
537 .collect::<Vec<String>>()
553 self.ansi_prefix_sgr, ansi_prefix, line_buf
555 self.config.true_color,
556 self.config.colored_output,
557 self.config.use_italic_text,
560 panel_wrap.clone().unwrap()
564 max_width = cursor_max;
574 cursor += current_width;
582 self.ansi_prefix_sgr, ansi_prefix, line_buf
584 self.config.true_color,
585 self.config.colored_output,
586 self.config.use_italic_text,
591 // Clear the ANSI prefix buffer.
598 if let Some(background_color) = background_color {
599 let ansi_style = Style {
600 background: to_ansi_color(background_color, self.config.true_color),
607 ansi_style.paint(" ".repeat(cursor_max - cursor))
617const DEFAULT_GUTTER_COLOR: u8 = 238;
619#[derive(Debug, Default)]
624 pub git_added: Style,
625 pub git_removed: Style,
626 pub git_modified: Style,
627 pub line_number: Style,
635 fn colored(theme: &Theme, true_color: bool) -> Self {
636 let gutter_style = Style {
637 foreground: match theme.settings.gutter_foreground {
638 // If the theme provides a gutter foreground color, use it.
639 // Note: It might be the special value #00000001, in which case
640 // to_ansi_color returns None and we use an empty Style
641 // (resulting in the terminal's default foreground color).
642 Some(c) => to_ansi_color(c, true_color),
643 // Otherwise, use a specific fallback color.
644 None => Some(Fixed(DEFAULT_GUTTER_COLOR)),
652 filename: Style::new().bold(),
653 git_added: Green.normal(),
654 git_removed: Red.normal(),
655 git_modified: Yellow.normal(),
656 line_number: gutter_style,
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