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;
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 {
36 fn print_header(&mut self, handle: &mut dyn Write, input: &OpenedInput) -> Result<()>;
37 fn print_footer(&mut self, handle: &mut dyn Write, input: &OpenedInput) -> Result<()>;
39 fn print_snip(&mut self, handle: &mut dyn Write) -> Result<()>;
44 handle: &mut dyn Write,
50pub struct SimplePrinter;
53 pub fn new() -> Self {
58impl Printer for SimplePrinter {
59 fn print_header(&mut self, _handle: &mut dyn Write, _input: &OpenedInput) -> Result<()> {
63 fn print_footer(&mut self, _handle: &mut dyn Write, _input: &OpenedInput) -> Result<()> {
67 fn print_snip(&mut self, _handle: &mut dyn Write) -> Result<()> {
74 handle: &mut dyn Write,
79 handle.write_all(line_buffer)?;
85pub(crate) struct InteractivePrinter<'a> {
87 config: &'a Config<'a>,
88 decorations: Vec<Box<dyn Decoration>>,
90 ansi_prefix_sgr: String,
91 content_type: Option<ContentType>,
92 #[cfg(feature = "git")]
93 pub line_changes: &'a Option<LineChanges>,
94 highlighter: Option<HighlightLines<'a>>,
95 syntax_set: &'a SyntaxSet,
96 background_color_highlight: Option<Color>,
99impl<'a> InteractivePrinter<'a> {
102 assets: &'a HighlightingAssets,
103 input: &mut OpenedInput,
104 #[cfg(feature = "git")]
105 line_changes: &'a Option<LineChanges>,
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 let highlighter = if input
153 .map_or(false, |c| c.is_binary() && !config.show_nonprintable)
157 // Determine the type of syntax for highlighting
158 let syntax = assets.get_syntax(config.language, input, &config.syntax_mapping);
159 Some(HighlightLines::new(syntax, theme))
167 content_type: input.reader.content_type,
168 ansi_prefix_sgr: String::new(),
169 #[cfg(feature = "git")]
172 syntax_set: &assets.syntax_set,
173 background_color_highlight,
177 fn print_horizontal_line(&mut self, handle: &mut dyn Write, grid_char: char) -> Result<()> {
178 if self.panel_width == 0 {
182 self.colors.grid.paint("─".repeat(self.config.term_width))
185 let hline = "─".repeat(self.config.term_width - (self.panel_width + 1));
186 let hline = format!("{}{}{}", "─".repeat(self.panel_width), grid_char, hline);
187 writeln!(handle, "{}", self.colors.grid.paint(hline))?;
193 fn create_fake_panel(&self, text: &str) -> String {
194 if self.panel_width == 0 {
197 let text_truncated: String = text.chars().take(self.panel_width - 1).collect();
198 let text_filled: String = format!(
201 " ".repeat(self.panel_width - 1 - text_truncated.len())
203 if self.config.style_components.grid() {
204 format!("{} │ ", text_filled)
211 fn preprocess(&self, text: &str, cursor: &mut usize) -> String {
212 if self.config.tab_width > 0 {
213 expand_tabs(text, self.config.tab_width, cursor)
215 *cursor += text.len();
221impl<'a> Printer for InteractivePrinter<'a> {
222 fn print_header(&mut self, handle: &mut dyn Write, input: &OpenedInput) -> Result<()> {
223 if !self.config.style_components.header() {
224 if Some(ContentType::BINARY) == self.content_type && !self.config.show_nonprintable {
227 "{}: Binary content from {} will not be printed to the terminal \
228 (but will be present if the output of 'bat' is piped). You can use 'bat -A' \
229 to show the binary file contents.",
230 Yellow.paint("[bat warning]"),
231 input.description().full,
233 } else if self.config.style_components.grid() {
234 self.print_horizontal_line(handle, '┬')?;
239 if self.config.style_components.grid() {
240 self.print_horizontal_line(handle, '┬')?;
245 " ".repeat(self.panel_width),
248 .paint(if self.panel_width > 0 { "│ " } else { "" }),
251 write!(handle, "{}", " ".repeat(self.panel_width))?;
254 let mode = match self.content_type {
255 Some(ContentType::BINARY) => " <BINARY>",
256 Some(ContentType::UTF_16LE) => " <UTF-16LE>",
257 Some(ContentType::UTF_16BE) => " <UTF-16BE>",
262 let description = input.description();
268 self.colors.filename.paint(&description.name),
272 if self.config.style_components.grid() {
273 if self.content_type.map_or(false, |c| c.is_text()) || self.config.show_nonprintable {
274 self.print_horizontal_line(handle, '┼')?;
276 self.print_horizontal_line(handle, '┴')?;
283 fn print_footer(&mut self, handle: &mut dyn Write, _input: &OpenedInput) -> Result<()> {
284 if self.config.style_components.grid()
285 && (self.content_type.map_or(false, |c| c.is_text()) || self.config.show_nonprintable)
287 self.print_horizontal_line(handle, '┴')
293 fn print_snip(&mut self, handle: &mut dyn Write) -> Result<()> {
294 let panel = self.create_fake_panel(" ...");
295 let panel_count = panel.chars().count();
298 let title_count = title.chars().count();
300 let snip_left = "─ ".repeat((self.config.term_width - panel_count - (title_count / 2)) / 4);
301 let snip_left_count = snip_left.chars().count(); // Can't use .len() with Unicode.
304 " ─".repeat((self.config.term_width - panel_count - snip_left_count - title_count) / 2);
311 .paint(format!("{}{}{}{}", panel, snip_left, title, snip_right))
320 handle: &mut dyn Write,
324 let line = if self.config.show_nonprintable {
325 replace_nonprintable(&line_buffer, self.config.tab_width)
327 match self.content_type {
328 Some(ContentType::BINARY) | None => {
331 Some(ContentType::UTF_16LE) => UTF_16LE
332 .decode(&line_buffer, DecoderTrap::Replace)
333 .map_err(|_| "Invalid UTF-16LE")?,
334 Some(ContentType::UTF_16BE) => UTF_16BE
335 .decode(&line_buffer, DecoderTrap::Replace)
336 .map_err(|_| "Invalid UTF-16BE")?,
337 _ => String::from_utf8_lossy(&line_buffer).to_string(),
342 let highlighter = match self.highlighter {
343 Some(ref mut highlighter) => highlighter,
348 highlighter.highlight(line.as_ref(), self.syntax_set)
355 let mut cursor: usize = 0;
356 let mut cursor_max: usize = self.config.term_width;
357 let mut cursor_total: usize = 0;
358 let mut panel_wrap: Option<String> = None;
361 let highlight_this_line =
362 self.config.highlighted_lines.0.check(line_number) == RangeCheckResult::InRange;
364 let background_color = self
365 .background_color_highlight
366 .filter(|_| highlight_this_line);
369 if self.panel_width > 0 {
370 let decorations = self
373 .map(|ref d| d.generate(line_number, false, self))
374 .collect::<Vec<_>>();
376 for deco in decorations {
377 write!(handle, "{} ", deco.text)?;
378 cursor_max -= deco.width + 1;
383 if self.config.wrapping_mode == WrappingMode::NoWrapping {
384 let true_color = self.config.true_color;
385 let colored_output = self.config.colored_output;
386 let italics = self.config.use_italic_text;
388 for &(style, region) in regions.iter() {
389 let text = &*self.preprocess(region, &mut cursor_total);
390 let text_trimmed = text.trim_end_matches(|c| c == '\r' || c == '\n');
404 if text.len() != text_trimmed.len() {
405 if let Some(background_color) = background_color {
406 let mut ansi_style = Style::default();
407 ansi_style.background = Some(to_ansi_color(background_color, true_color));
408 let width = if cursor_total <= cursor_max {
409 cursor_max - cursor_total + 1
413 write!(handle, "{}", ansi_style.paint(" ".repeat(width)))?;
415 write!(handle, "{}", &text[text_trimmed.len()..])?;
419 if line.bytes().next_back() != Some(b'\n') {
423 for &(style, region) in regions.iter() {
424 let ansi_iterator = AnsiCodeIterator::new(region);
425 let mut ansi_prefix: String = String::new();
426 for chunk in ansi_iterator {
428 // ANSI escape passthrough.
430 let is_ansi_csi = text.starts_with("\x1B[");
432 if is_ansi_csi && text.ends_with('m') {
433 // It's an ANSI SGR sequence.
434 // We should be mostly safe to just append these together.
435 ansi_prefix.push_str(text);
436 if text == "\x1B[0m" {
437 self.ansi_prefix_sgr = "\x1B[0m".to_owned();
439 self.ansi_prefix_sgr.push_str(text);
441 } else if is_ansi_csi {
442 // It's a regular CSI sequence.
443 // We should be mostly safe to just append these together.
444 ansi_prefix.push_str(text);
446 // It's probably a VT100 code.
447 // Passing it through is the safest bet.
448 write!(handle, "{}", text)?;
454 let text = self.preprocess(
455 text.trim_end_matches(|c| c == '\r' || c == '\n'),
459 let mut max_width = cursor_max - cursor;
461 // line buffer (avoid calling write! for every character)
462 let mut line_buf = String::with_capacity(max_width * 4);
464 // Displayed width of line_buf
465 let mut current_width = 0;
467 for c in text.chars() {
468 // calculate the displayed width for next character
469 let cw = c.width().unwrap_or(0);
472 // if next character cannot be printed on this line,
474 if current_width > max_width {
475 // Generate wrap padding if not already generated.
476 if panel_wrap.is_none() {
477 panel_wrap = if self.panel_width > 0 {
483 .generate(line_number, true, self)
485 .collect::<Vec<String>>()
501 self.ansi_prefix_sgr, ansi_prefix, line_buf
503 self.config.true_color,
504 self.config.colored_output,
505 self.config.use_italic_text,
508 panel_wrap.clone().unwrap()
512 max_width = cursor_max;
522 cursor += current_width;
530 self.ansi_prefix_sgr, ansi_prefix, line_buf
532 self.config.true_color,
533 self.config.colored_output,
534 self.config.use_italic_text,
539 // Clear the ANSI prefix buffer.
546 if let Some(background_color) = background_color {
547 let mut ansi_style = Style::default();
548 ansi_style.background =
549 Some(to_ansi_color(background_color, self.config.true_color));
554 ansi_style.paint(" ".repeat(cursor_max - cursor))
564const DEFAULT_GUTTER_COLOR: u8 = 238;
566#[derive(Debug, Default)]
570 pub git_added: Style,
571 pub git_removed: Style,
572 pub git_modified: Style,
573 pub line_number: Style,
581 fn colored(theme: &Theme, true_color: bool) -> Self {
582 let gutter_color = theme
585 .map(|c| to_ansi_color(c, true_color))
586 .unwrap_or(Fixed(DEFAULT_GUTTER_COLOR));
589 grid: gutter_color.normal(),
590 filename: Style::new().bold(),
591 git_added: Green.normal(),
592 git_removed: Red.normal(),
593 git_modified: Yellow.normal(),
594 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