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 {
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)?;
94 if line_buffer.last() == Some(&b'\n') {
98 handle.write_all(line_buffer)?
105pub(crate) struct InteractivePrinter<'a> {
107 config: &'a Config<'a>,
108 decorations: Vec<Box<dyn Decoration>>,
110 ansi_prefix_sgr: String,
111 content_type: Option<ContentType>,
112 #[cfg(feature = "git")]
113 pub line_changes: &'a Option<LineChanges>,
114 highlighter: Option<HighlightLines<'a>>,
115 syntax_set: &'a SyntaxSet,
116 background_color_highlight: Option<Color>,
119impl<'a> InteractivePrinter<'a> {
122 assets: &'a HighlightingAssets,
123 input: &mut OpenedInput,
124 #[cfg(feature = "git")] line_changes: &'a Option<LineChanges>,
126 let theme = assets.get_theme(&config.theme);
128 let background_color_highlight = theme.settings.line_highlight;
130 let colors = if config.colored_output {
131 Colors::colored(theme, config.true_color)
136 // Create decorations.
137 let mut decorations: Vec<Box<dyn Decoration>> = Vec::new();
139 if config.style_components.numbers() {
140 decorations.push(Box::new(LineNumberDecoration::new(&colors)));
143 #[cfg(feature = "git")]
145 if config.style_components.changes() {
146 decorations.push(Box::new(LineChangesDecoration::new(&colors)));
150 let mut panel_width: usize =
151 decorations.len() + decorations.iter().fold(0, |a, x| a + x.width());
153 // The grid border decoration isn't added until after the panel_width calculation, since the
154 // print_horizontal_line, print_header, and print_footer functions all assume the panel
155 // width is without the grid border.
156 if config.style_components.grid() && !decorations.is_empty() {
157 decorations.push(Box::new(GridBorderDecoration::new(&colors)));
160 // Disable the panel if the terminal is too small (i.e. can't fit 5 characters with the
163 < (decorations.len() + decorations.iter().fold(0, |a, x| a + x.width())) + 5
169 let highlighter = if input
172 .map_or(false, |c| c.is_binary() && !config.show_nonprintable)
176 // Determine the type of syntax for highlighting
177 let syntax = match assets.get_syntax(config.language, input, &config.syntax_mapping) {
178 Ok(syntax) => syntax,
179 Err(Error(ErrorKind::UndetectedSyntax(_), _)) => {
180 assets.syntax_set.find_syntax_plain_text()
182 Err(e) => return Err(e),
185 Some(HighlightLines::new(syntax, theme))
188 Ok(InteractivePrinter {
193 content_type: input.reader.content_type,
194 ansi_prefix_sgr: String::new(),
195 #[cfg(feature = "git")]
198 syntax_set: &assets.syntax_set,
199 background_color_highlight,
203 fn print_horizontal_line_term(&mut self, handle: &mut dyn Write, style: Style) -> Result<()> {
207 style.paint("─".repeat(self.config.term_width))
212 fn print_horizontal_line(&mut self, handle: &mut dyn Write, grid_char: char) -> Result<()> {
213 if self.panel_width == 0 {
214 self.print_horizontal_line_term(handle, self.colors.grid)?;
216 let hline = "─".repeat(self.config.term_width - (self.panel_width + 1));
217 let hline = format!("{}{}{}", "─".repeat(self.panel_width), grid_char, hline);
218 writeln!(handle, "{}", self.colors.grid.paint(hline))?;
224 fn create_fake_panel(&self, text: &str) -> String {
225 if self.panel_width == 0 {
228 let text_truncated: String = text.chars().take(self.panel_width - 1).collect();
229 let text_filled: String = format!(
232 " ".repeat(self.panel_width - 1 - text_truncated.len())
234 if self.config.style_components.grid() {
235 format!("{} │ ", text_filled)
242 fn preprocess(&self, text: &str, cursor: &mut usize) -> String {
243 if self.config.tab_width > 0 {
244 expand_tabs(text, self.config.tab_width, cursor)
246 *cursor += text.len();
252impl<'a> Printer for InteractivePrinter<'a> {
255 handle: &mut dyn Write,
257 add_header_padding: bool,
259 if add_header_padding && self.config.style_components.rule() {
260 self.print_horizontal_line_term(handle, self.colors.rule)?;
263 if !self.config.style_components.header() {
264 if Some(ContentType::BINARY) == self.content_type && !self.config.show_nonprintable {
267 "{}: Binary content from {} will not be printed to the terminal \
268 (but will be present if the output of 'bat' is piped). You can use 'bat -A' \
269 to show the binary file contents.",
270 Yellow.paint("[bat warning]"),
271 input.description.summary(),
273 } else if self.config.style_components.grid() {
274 self.print_horizontal_line(handle, '┬')?;
279 if self.config.style_components.grid() {
280 self.print_horizontal_line(handle, '┬')?;
285 " ".repeat(self.panel_width),
288 .paint(if self.panel_width > 0 { "│ " } else { "" }),
291 // Only pad space between files, if we haven't already drawn a horizontal rule
292 if add_header_padding && !self.config.style_components.rule() {
295 write!(handle, "{}", " ".repeat(self.panel_width))?;
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>",
306 let description = &input.description;
313 .map(|kind| format!("{}: ", kind))
314 .unwrap_or_else(|| "".into()),
315 self.colors.filename.paint(description.title()),
319 if self.config.style_components.grid() {
320 if self.content_type.map_or(false, |c| c.is_text()) || self.config.show_nonprintable {
321 self.print_horizontal_line(handle, '┼')?;
323 self.print_horizontal_line(handle, '┴')?;
330 fn print_footer(&mut self, handle: &mut dyn Write, _input: &OpenedInput) -> Result<()> {
331 if self.config.style_components.grid()
332 && (self.content_type.map_or(false, |c| c.is_text()) || self.config.show_nonprintable)
334 self.print_horizontal_line(handle, '┴')
340 fn print_snip(&mut self, handle: &mut dyn Write) -> Result<()> {
341 let panel = self.create_fake_panel(" ...");
342 let panel_count = panel.chars().count();
345 let title_count = title.chars().count();
347 let snip_left = "─ ".repeat((self.config.term_width - panel_count - (title_count / 2)) / 4);
348 let snip_left_count = snip_left.chars().count(); // Can't use .len() with Unicode.
351 " ─".repeat((self.config.term_width - panel_count - snip_left_count - title_count) / 2);
358 .paint(format!("{}{}{}{}", panel, snip_left, title, snip_right))
367 handle: &mut dyn Write,
371 let line = if self.config.show_nonprintable {
372 replace_nonprintable(&line_buffer, self.config.tab_width)
374 match self.content_type {
375 Some(ContentType::BINARY) | None => {
378 Some(ContentType::UTF_16LE) => UTF_16LE
379 .decode(&line_buffer, DecoderTrap::Replace)
380 .map_err(|_| "Invalid UTF-16LE")?,
381 Some(ContentType::UTF_16BE) => UTF_16BE
382 .decode(&line_buffer, DecoderTrap::Replace)
383 .map_err(|_| "Invalid UTF-16BE")?,
384 _ => String::from_utf8_lossy(&line_buffer).to_string(),
389 let highlighter = match self.highlighter {
390 Some(ref mut highlighter) => highlighter,
395 highlighter.highlight(line.as_ref(), self.syntax_set)
402 let mut cursor: usize = 0;
403 let mut cursor_max: usize = self.config.term_width;
404 let mut cursor_total: usize = 0;
405 let mut panel_wrap: Option<String> = None;
408 let highlight_this_line =
409 self.config.highlighted_lines.0.check(line_number) == RangeCheckResult::InRange;
411 let background_color = self
412 .background_color_highlight
413 .filter(|_| highlight_this_line);
416 if self.panel_width > 0 {
417 let decorations = self
420 .map(|ref d| d.generate(line_number, false, self))
421 .collect::<Vec<_>>();
423 for deco in decorations {
424 write!(handle, "{} ", deco.text)?;
425 cursor_max -= deco.width + 1;
430 if self.config.wrapping_mode == WrappingMode::NoWrapping {
431 let true_color = self.config.true_color;
432 let colored_output = self.config.colored_output;
433 let italics = self.config.use_italic_text;
435 for &(style, region) in regions.iter() {
436 let text = &*self.preprocess(region, &mut cursor_total);
437 let text_trimmed = text.trim_end_matches(|c| c == '\r' || c == '\n');
451 if text.len() != text_trimmed.len() {
452 if let Some(background_color) = background_color {
453 let mut ansi_style = Style::default();
454 ansi_style.background = Some(to_ansi_color(background_color, true_color));
455 let width = if cursor_total <= cursor_max {
456 cursor_max - cursor_total + 1
460 write!(handle, "{}", ansi_style.paint(" ".repeat(width)))?;
462 write!(handle, "{}", &text[text_trimmed.len()..])?;
466 if line.bytes().next_back() != Some(b'\n') {
470 for &(style, region) in regions.iter() {
471 let ansi_iterator = AnsiCodeIterator::new(region);
472 let mut ansi_prefix: String = String::new();
473 for chunk in ansi_iterator {
475 // ANSI escape passthrough.
477 let is_ansi_csi = text.starts_with("\x1B[");
479 if is_ansi_csi && text.ends_with('m') {
480 // It's an ANSI SGR sequence.
481 // We should be mostly safe to just append these together.
482 ansi_prefix.push_str(text);
483 if text == "\x1B[0m" {
484 self.ansi_prefix_sgr = "\x1B[0m".to_owned();
486 self.ansi_prefix_sgr.push_str(text);
488 } else if is_ansi_csi {
489 // It's a regular CSI sequence.
490 // We should be mostly safe to just append these together.
491 ansi_prefix.push_str(text);
493 // It's probably a VT100 code.
494 // Passing it through is the safest bet.
495 write!(handle, "{}", text)?;
501 let text = self.preprocess(
502 text.trim_end_matches(|c| c == '\r' || c == '\n'),
506 let mut max_width = cursor_max - cursor;
508 // line buffer (avoid calling write! for every character)
509 let mut line_buf = String::with_capacity(max_width * 4);
511 // Displayed width of line_buf
512 let mut current_width = 0;
514 for c in text.chars() {
515 // calculate the displayed width for next character
516 let cw = c.width().unwrap_or(0);
519 // if next character cannot be printed on this line,
521 if current_width > max_width {
522 // Generate wrap padding if not already generated.
523 if panel_wrap.is_none() {
524 panel_wrap = if self.panel_width > 0 {
530 .generate(line_number, true, self)
532 .collect::<Vec<String>>()
548 self.ansi_prefix_sgr, ansi_prefix, line_buf
550 self.config.true_color,
551 self.config.colored_output,
552 self.config.use_italic_text,
555 panel_wrap.clone().unwrap()
559 max_width = cursor_max;
569 cursor += current_width;
577 self.ansi_prefix_sgr, ansi_prefix, line_buf
579 self.config.true_color,
580 self.config.colored_output,
581 self.config.use_italic_text,
586 // Clear the ANSI prefix buffer.
593 if let Some(background_color) = background_color {
594 let mut ansi_style = Style::default();
595 ansi_style.background =
596 Some(to_ansi_color(background_color, self.config.true_color));
601 ansi_style.paint(" ".repeat(cursor_max - cursor))
611const DEFAULT_GUTTER_COLOR: u8 = 238;
613#[derive(Debug, Default)]
618 pub git_added: Style,
619 pub git_removed: Style,
620 pub git_modified: Style,
621 pub line_number: Style,
629 fn colored(theme: &Theme, true_color: bool) -> Self {
630 let gutter_color = theme
633 .map(|c| to_ansi_color(c, true_color))
634 .unwrap_or(Fixed(DEFAULT_GUTTER_COLOR));
637 grid: gutter_color.normal(),
638 rule: gutter_color.normal(),
639 filename: Style::new().bold(),
640 git_added: Green.normal(),
641 git_removed: Red.normal(),
642 git_modified: Yellow.normal(),
643 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