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)?
102struct HighlighterFromSet<'a> {
103 highlighter: HighlightLines<'a>,
104 syntax_set: &'a SyntaxSet,
107impl<'a> HighlighterFromSet<'a> {
108 fn new(syntax_in_set: SyntaxReferenceInSet<'a>, theme: &'a Theme) -> Self {
110 highlighter: HighlightLines::new(syntax_in_set.syntax, theme),
111 syntax_set: syntax_in_set.syntax_set,
116pub(crate) struct InteractivePrinter<'a> {
118 config: &'a Config<'a>,
119 decorations: Vec<Box<dyn Decoration>>,
121 ansi_prefix_sgr: String,
122 content_type: Option<ContentType>,
123 #[cfg(feature = "git")]
124 pub line_changes: &'a Option<LineChanges>,
125 highlighter_from_set: Option<HighlighterFromSet<'a>>,
126 background_color_highlight: Option<Color>,
129impl<'a> InteractivePrinter<'a> {
132 assets: &'a HighlightingAssets,
133 input: &mut OpenedInput,
134 #[cfg(feature = "git")] line_changes: &'a Option<LineChanges>,
136 let theme = assets.get_theme(&config.theme);
138 let background_color_highlight = theme.settings.line_highlight;
140 let colors = if config.colored_output {
141 Colors::colored(theme, config.true_color)
146 // Create decorations.
147 let mut decorations: Vec<Box<dyn Decoration>> = Vec::new();
149 if config.style_components.numbers() {
150 decorations.push(Box::new(LineNumberDecoration::new(&colors)));
153 #[cfg(feature = "git")]
155 if config.style_components.changes() {
156 decorations.push(Box::new(LineChangesDecoration::new(&colors)));
160 let mut panel_width: usize =
161 decorations.len() + decorations.iter().fold(0, |a, x| a + x.width());
163 // The grid border decoration isn't added until after the panel_width calculation, since the
164 // print_horizontal_line, print_header, and print_footer functions all assume the panel
165 // width is without the grid border.
166 if config.style_components.grid() && !decorations.is_empty() {
167 decorations.push(Box::new(GridBorderDecoration::new(&colors)));
170 // Disable the panel if the terminal is too small (i.e. can't fit 5 characters with the
173 < (decorations.len() + decorations.iter().fold(0, |a, x| a + x.width())) + 5
179 let highlighter_from_set = if input
182 .map_or(false, |c| c.is_binary() && !config.show_nonprintable)
186 // Determine the type of syntax for highlighting
188 match assets.get_syntax(config.language, input, &config.syntax_mapping) {
189 Ok(syntax_in_set) => syntax_in_set,
190 Err(Error::UndetectedSyntax(_)) => assets
191 .find_syntax_by_name("Plain Text")?
192 .expect("A plain text syntax is available"),
193 Err(e) => return Err(e),
196 Some(HighlighterFromSet::new(syntax_in_set, theme))
199 Ok(InteractivePrinter {
204 content_type: input.reader.content_type,
205 ansi_prefix_sgr: String::new(),
206 #[cfg(feature = "git")]
208 highlighter_from_set,
209 background_color_highlight,
213 fn print_horizontal_line_term(&mut self, handle: &mut dyn Write, style: Style) -> Result<()> {
217 style.paint("─".repeat(self.config.term_width))
222 fn print_horizontal_line(&mut self, handle: &mut dyn Write, grid_char: char) -> Result<()> {
223 if self.panel_width == 0 {
224 self.print_horizontal_line_term(handle, self.colors.grid)?;
226 let hline = "─".repeat(self.config.term_width - (self.panel_width + 1));
227 let hline = format!("{}{}{}", "─".repeat(self.panel_width), grid_char, hline);
228 writeln!(handle, "{}", self.colors.grid.paint(hline))?;
234 fn create_fake_panel(&self, text: &str) -> String {
235 if self.panel_width == 0 {
236 return "".to_string();
239 let text_truncated: String = text.chars().take(self.panel_width - 1).collect();
240 let text_filled: String = format!(
243 " ".repeat(self.panel_width - 1 - text_truncated.len())
245 if self.config.style_components.grid() {
246 format!("{} │ ", text_filled)
252 fn preprocess(&self, text: &str, cursor: &mut usize) -> String {
253 if self.config.tab_width > 0 {
254 return expand_tabs(text, self.config.tab_width, cursor);
257 *cursor += text.len();
262impl<'a> Printer for InteractivePrinter<'a> {
265 handle: &mut dyn Write,
267 add_header_padding: bool,
269 if add_header_padding && self.config.style_components.rule() {
270 self.print_horizontal_line_term(handle, self.colors.rule)?;
273 if !self.config.style_components.header() {
274 if Some(ContentType::BINARY) == self.content_type && !self.config.show_nonprintable {
277 "{}: Binary content from {} will not be printed to the terminal \
278 (but will be present if the output of 'bat' is piped). You can use 'bat -A' \
279 to show the binary file contents.",
280 Yellow.paint("[bat warning]"),
281 input.description.summary(),
283 } else if self.config.style_components.grid() {
284 self.print_horizontal_line(handle, '┬')?;
289 if self.config.style_components.grid() {
290 self.print_horizontal_line(handle, '┬')?;
295 " ".repeat(self.panel_width),
298 .paint(if self.panel_width > 0 { "│ " } else { "" }),
301 // Only pad space between files, if we haven't already drawn a horizontal rule
302 if add_header_padding && !self.config.style_components.rule() {
305 write!(handle, "{}", " ".repeat(self.panel_width))?;
308 let mode = match self.content_type {
309 Some(ContentType::BINARY) => " <BINARY>",
310 Some(ContentType::UTF_16LE) => " <UTF-16LE>",
311 Some(ContentType::UTF_16BE) => " <UTF-16BE>",
316 let description = &input.description;
323 .map(|kind| format!("{}: ", kind))
324 .unwrap_or_else(|| "".into()),
325 self.colors.filename.paint(description.title()),
329 if self.config.style_components.grid() {
330 if self.content_type.map_or(false, |c| c.is_text()) || self.config.show_nonprintable {
331 self.print_horizontal_line(handle, '┼')?;
333 self.print_horizontal_line(handle, '┴')?;
340 fn print_footer(&mut self, handle: &mut dyn Write, _input: &OpenedInput) -> Result<()> {
341 if self.config.style_components.grid()
342 && (self.content_type.map_or(false, |c| c.is_text()) || self.config.show_nonprintable)
344 self.print_horizontal_line(handle, '┴')
350 fn print_snip(&mut self, handle: &mut dyn Write) -> Result<()> {
351 let panel = self.create_fake_panel(" ...");
352 let panel_count = panel.chars().count();
355 let title_count = title.chars().count();
357 let snip_left = "─ ".repeat((self.config.term_width - panel_count - (title_count / 2)) / 4);
358 let snip_left_count = snip_left.chars().count(); // Can't use .len() with Unicode.
361 " ─".repeat((self.config.term_width - panel_count - snip_left_count - title_count) / 2);
368 .paint(format!("{}{}{}{}", panel, snip_left, title, snip_right))
377 handle: &mut dyn Write,
381 let line = if self.config.show_nonprintable {
382 replace_nonprintable(line_buffer, self.config.tab_width)
384 match self.content_type {
385 Some(ContentType::BINARY) | None => {
388 Some(ContentType::UTF_16LE) => UTF_16LE
389 .decode(line_buffer, DecoderTrap::Replace)
390 .map_err(|_| "Invalid UTF-16LE")?,
391 Some(ContentType::UTF_16BE) => UTF_16BE
392 .decode(line_buffer, DecoderTrap::Replace)
393 .map_err(|_| "Invalid UTF-16BE")?,
394 _ => String::from_utf8_lossy(line_buffer).to_string(),
399 let highlighter_from_set = match self.highlighter_from_set {
400 Some(ref mut highlighter_from_set) => highlighter_from_set,
407 .highlight(&line, highlighter_from_set.syntax_set)
414 let mut cursor: usize = 0;
415 let mut cursor_max: usize = self.config.term_width;
416 let mut cursor_total: usize = 0;
417 let mut panel_wrap: Option<String> = None;
420 let highlight_this_line =
421 self.config.highlighted_lines.0.check(line_number) == RangeCheckResult::InRange;
423 let background_color = self
424 .background_color_highlight
425 .filter(|_| highlight_this_line);
428 if self.panel_width > 0 {
429 let decorations = self
432 .map(|d| d.generate(line_number, false, self));
434 for deco in decorations {
435 write!(handle, "{} ", deco.text)?;
436 cursor_max -= deco.width + 1;
441 if matches!(self.config.wrapping_mode, WrappingMode::NoWrapping(_)) {
442 let true_color = self.config.true_color;
443 let colored_output = self.config.colored_output;
444 let italics = self.config.use_italic_text;
446 for &(style, region) in ®ions {
447 let text = &*self.preprocess(region, &mut cursor_total);
448 let text_trimmed = text.trim_end_matches(|c| c == '\r' || c == '\n');
462 if text.len() != text_trimmed.len() {
463 if let Some(background_color) = background_color {
464 let ansi_style = Style {
465 background: to_ansi_color(background_color, true_color),
468 let width = if cursor_total <= cursor_max {
469 cursor_max - cursor_total + 1
473 write!(handle, "{}", ansi_style.paint(" ".repeat(width)))?;
475 write!(handle, "{}", &text[text_trimmed.len()..])?;
479 if !self.config.style_components.plain() && line.bytes().next_back() != Some(b'\n') {
483 for &(style, region) in ®ions {
484 let ansi_iterator = AnsiCodeIterator::new(region);
485 let mut ansi_prefix: String = String::new();
486 for chunk in ansi_iterator {
488 // ANSI escape passthrough.
490 let is_ansi_csi = text.starts_with("\x1B[");
492 if is_ansi_csi && text.ends_with('m') {
493 // It's an ANSI SGR sequence.
494 // We should be mostly safe to just append these together.
495 ansi_prefix.push_str(text);
496 if text == "\x1B[0m" {
497 self.ansi_prefix_sgr = "\x1B[0m".to_owned();
499 self.ansi_prefix_sgr.push_str(text);
501 } else if is_ansi_csi {
502 // It's a regular CSI sequence.
503 // We should be mostly safe to just append these together.
504 ansi_prefix.push_str(text);
506 // It's probably a VT100 code.
507 // Passing it through is the safest bet.
508 write!(handle, "{}", text)?;
514 let text = self.preprocess(
515 text.trim_end_matches(|c| c == '\r' || c == '\n'),
519 let mut max_width = cursor_max - cursor;
521 // line buffer (avoid calling write! for every character)
522 let mut line_buf = String::with_capacity(max_width * 4);
524 // Displayed width of line_buf
525 let mut current_width = 0;
527 for c in text.chars() {
528 // calculate the displayed width for next character
529 let cw = c.width().unwrap_or(0);
532 // if next character cannot be printed on this line,
534 if current_width > max_width {
535 // Generate wrap padding if not already generated.
536 if panel_wrap.is_none() {
537 panel_wrap = if self.panel_width > 0 {
543 .generate(line_number, true, self)
545 .collect::<Vec<String>>()
561 self.ansi_prefix_sgr, ansi_prefix, line_buf
563 self.config.true_color,
564 self.config.colored_output,
565 self.config.use_italic_text,
568 panel_wrap.clone().unwrap()
572 max_width = cursor_max;
582 cursor += current_width;
590 self.ansi_prefix_sgr, ansi_prefix, line_buf
592 self.config.true_color,
593 self.config.colored_output,
594 self.config.use_italic_text,
599 // Clear the ANSI prefix buffer.
606 if let Some(background_color) = background_color {
607 let ansi_style = Style {
608 background: to_ansi_color(background_color, self.config.true_color),
615 ansi_style.paint(" ".repeat(cursor_max - cursor))
625const DEFAULT_GUTTER_COLOR: u8 = 238;
627#[derive(Debug, Default)]
632 pub git_added: Style,
633 pub git_removed: Style,
634 pub git_modified: Style,
635 pub line_number: Style,
643 fn colored(theme: &Theme, true_color: bool) -> Self {
644 let gutter_style = Style {
645 foreground: match theme.settings.gutter_foreground {
646 // If the theme provides a gutter foreground color, use it.
647 // Note: It might be the special value #00000001, in which case
648 // to_ansi_color returns None and we use an empty Style
649 // (resulting in the terminal's default foreground color).
650 Some(c) => to_ansi_color(c, true_color),
651 // Otherwise, use a specific fallback color.
652 None => Some(Fixed(DEFAULT_GUTTER_COLOR)),
660 filename: Style::new().bold(),
661 git_added: Green.normal(),
662 git_removed: Red.normal(),
663 git_modified: Yellow.normal(),
664 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