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;
58 pub fn new() -> Self {
63impl Printer for SimplePrinter {
66 _handle: &mut dyn Write,
68 _add_header_padding: bool,
73 fn print_footer(&mut self, _handle: &mut dyn Write, _input: &OpenedInput) -> Result<()> {
77 fn print_snip(&mut self, _handle: &mut dyn Write) -> Result<()> {
84 handle: &mut dyn Write,
89 handle.write_all(line_buffer)?;
95pub(crate) struct InteractivePrinter<'a> {
97 config: &'a Config<'a>,
98 decorations: Vec<Box<dyn Decoration>>,
100 ansi_prefix_sgr: String,
101 content_type: Option<ContentType>,
102 #[cfg(feature = "git")]
103 pub line_changes: &'a Option<LineChanges>,
104 highlighter: Option<HighlightLines<'a>>,
105 syntax_set: &'a SyntaxSet,
106 background_color_highlight: Option<Color>,
109impl<'a> InteractivePrinter<'a> {
112 assets: &'a HighlightingAssets,
113 input: &mut OpenedInput,
114 #[cfg(feature = "git")] line_changes: &'a Option<LineChanges>,
116 let theme = assets.get_theme(&config.theme);
118 let background_color_highlight = theme.settings.line_highlight;
120 let colors = if config.colored_output {
121 Colors::colored(theme, config.true_color)
126 // Create decorations.
127 let mut decorations: Vec<Box<dyn Decoration>> = Vec::new();
129 if config.style_components.numbers() {
130 decorations.push(Box::new(LineNumberDecoration::new(&colors)));
133 #[cfg(feature = "git")]
135 if config.style_components.changes() {
136 decorations.push(Box::new(LineChangesDecoration::new(&colors)));
140 let mut panel_width: usize =
141 decorations.len() + decorations.iter().fold(0, |a, x| a + x.width());
143 // The grid border decoration isn't added until after the panel_width calculation, since the
144 // print_horizontal_line, print_header, and print_footer functions all assume the panel
145 // width is without the grid border.
146 if config.style_components.grid() && !decorations.is_empty() {
147 decorations.push(Box::new(GridBorderDecoration::new(&colors)));
150 // Disable the panel if the terminal is too small (i.e. can't fit 5 characters with the
153 < (decorations.len() + decorations.iter().fold(0, |a, x| a + x.width())) + 5
159 let highlighter = if input
162 .map_or(false, |c| c.is_binary() && !config.show_nonprintable)
166 // Determine the type of syntax for highlighting
167 let syntax = match assets.get_syntax(config.language, input, &config.syntax_mapping) {
168 Ok(syntax) => syntax,
169 Err(Error(ErrorKind::UndetectedSyntax(_), _)) => {
170 assets.syntax_set.find_syntax_plain_text()
172 Err(e) => return Err(e),
175 Some(HighlightLines::new(syntax, theme))
178 Ok(InteractivePrinter {
183 content_type: input.reader.content_type,
184 ansi_prefix_sgr: String::new(),
185 #[cfg(feature = "git")]
188 syntax_set: &assets.syntax_set,
189 background_color_highlight,
193 fn print_horizontal_line(&mut self, handle: &mut dyn Write, grid_char: char) -> Result<()> {
194 if self.panel_width == 0 {
198 self.colors.grid.paint("─".repeat(self.config.term_width))
201 let hline = "─".repeat(self.config.term_width - (self.panel_width + 1));
202 let hline = format!("{}{}{}", "─".repeat(self.panel_width), grid_char, hline);
203 writeln!(handle, "{}", self.colors.grid.paint(hline))?;
209 fn create_fake_panel(&self, text: &str) -> String {
210 if self.panel_width == 0 {
213 let text_truncated: String = text.chars().take(self.panel_width - 1).collect();
214 let text_filled: String = format!(
217 " ".repeat(self.panel_width - 1 - text_truncated.len())
219 if self.config.style_components.grid() {
220 format!("{} │ ", text_filled)
227 fn preprocess(&self, text: &str, cursor: &mut usize) -> String {
228 if self.config.tab_width > 0 {
229 expand_tabs(text, self.config.tab_width, cursor)
231 *cursor += text.len();
237impl<'a> Printer for InteractivePrinter<'a> {
240 handle: &mut dyn Write,
242 add_header_padding: bool,
244 if !self.config.style_components.header() {
245 if Some(ContentType::BINARY) == self.content_type && !self.config.show_nonprintable {
248 "{}: Binary content from {} will not be printed to the terminal \
249 (but will be present if the output of 'bat' is piped). You can use 'bat -A' \
250 to show the binary file contents.",
251 Yellow.paint("[bat warning]"),
252 input.description.summary(),
254 } else if self.config.style_components.grid() {
255 self.print_horizontal_line(handle, '┬')?;
260 if self.config.style_components.grid() {
261 self.print_horizontal_line(handle, '┬')?;
266 " ".repeat(self.panel_width),
269 .paint(if self.panel_width > 0 { "│ " } else { "" }),
272 if add_header_padding {
275 write!(handle, "{}", " ".repeat(self.panel_width))?;
278 let mode = match self.content_type {
279 Some(ContentType::BINARY) => " <BINARY>",
280 Some(ContentType::UTF_16LE) => " <UTF-16LE>",
281 Some(ContentType::UTF_16BE) => " <UTF-16BE>",
286 let description = &input.description;
293 .map(|kind| format!("{}: ", kind))
294 .unwrap_or("".into()),
295 self.colors.filename.paint(description.title()),
299 if self.config.style_components.grid() {
300 if self.content_type.map_or(false, |c| c.is_text()) || self.config.show_nonprintable {
301 self.print_horizontal_line(handle, '┼')?;
303 self.print_horizontal_line(handle, '┴')?;
310 fn print_footer(&mut self, handle: &mut dyn Write, _input: &OpenedInput) -> Result<()> {
311 if self.config.style_components.grid()
312 && (self.content_type.map_or(false, |c| c.is_text()) || self.config.show_nonprintable)
314 self.print_horizontal_line(handle, '┴')
320 fn print_snip(&mut self, handle: &mut dyn Write) -> Result<()> {
321 let panel = self.create_fake_panel(" ...");
322 let panel_count = panel.chars().count();
325 let title_count = title.chars().count();
327 let snip_left = "─ ".repeat((self.config.term_width - panel_count - (title_count / 2)) / 4);
328 let snip_left_count = snip_left.chars().count(); // Can't use .len() with Unicode.
331 " ─".repeat((self.config.term_width - panel_count - snip_left_count - title_count) / 2);
338 .paint(format!("{}{}{}{}", panel, snip_left, title, snip_right))
347 handle: &mut dyn Write,
351 let line = if self.config.show_nonprintable {
352 replace_nonprintable(&line_buffer, self.config.tab_width)
354 match self.content_type {
355 Some(ContentType::BINARY) | None => {
358 Some(ContentType::UTF_16LE) => UTF_16LE
359 .decode(&line_buffer, DecoderTrap::Replace)
360 .map_err(|_| "Invalid UTF-16LE")?,
361 Some(ContentType::UTF_16BE) => UTF_16BE
362 .decode(&line_buffer, DecoderTrap::Replace)
363 .map_err(|_| "Invalid UTF-16BE")?,
364 _ => String::from_utf8_lossy(&line_buffer).to_string(),
369 let highlighter = match self.highlighter {
370 Some(ref mut highlighter) => highlighter,
375 highlighter.highlight(line.as_ref(), self.syntax_set)
382 let mut cursor: usize = 0;
383 let mut cursor_max: usize = self.config.term_width;
384 let mut cursor_total: usize = 0;
385 let mut panel_wrap: Option<String> = None;
388 let highlight_this_line =
389 self.config.highlighted_lines.0.check(line_number) == RangeCheckResult::InRange;
391 let background_color = self
392 .background_color_highlight
393 .filter(|_| highlight_this_line);
396 if self.panel_width > 0 {
397 let decorations = self
400 .map(|ref d| d.generate(line_number, false, self))
401 .collect::<Vec<_>>();
403 for deco in decorations {
404 write!(handle, "{} ", deco.text)?;
405 cursor_max -= deco.width + 1;
410 if self.config.wrapping_mode == WrappingMode::NoWrapping {
411 let true_color = self.config.true_color;
412 let colored_output = self.config.colored_output;
413 let italics = self.config.use_italic_text;
415 for &(style, region) in regions.iter() {
416 let text = &*self.preprocess(region, &mut cursor_total);
417 let text_trimmed = text.trim_end_matches(|c| c == '\r' || c == '\n');
431 if text.len() != text_trimmed.len() {
432 if let Some(background_color) = background_color {
433 let mut ansi_style = Style::default();
434 ansi_style.background = Some(to_ansi_color(background_color, true_color));
435 let width = if cursor_total <= cursor_max {
436 cursor_max - cursor_total + 1
440 write!(handle, "{}", ansi_style.paint(" ".repeat(width)))?;
442 write!(handle, "{}", &text[text_trimmed.len()..])?;
446 if line.bytes().next_back() != Some(b'\n') {
450 for &(style, region) in regions.iter() {
451 let ansi_iterator = AnsiCodeIterator::new(region);
452 let mut ansi_prefix: String = String::new();
453 for chunk in ansi_iterator {
455 // ANSI escape passthrough.
457 let is_ansi_csi = text.starts_with("\x1B[");
459 if is_ansi_csi && text.ends_with('m') {
460 // It's an ANSI SGR sequence.
461 // We should be mostly safe to just append these together.
462 ansi_prefix.push_str(text);
463 if text == "\x1B[0m" {
464 self.ansi_prefix_sgr = "\x1B[0m".to_owned();
466 self.ansi_prefix_sgr.push_str(text);
468 } else if is_ansi_csi {
469 // It's a regular CSI sequence.
470 // We should be mostly safe to just append these together.
471 ansi_prefix.push_str(text);
473 // It's probably a VT100 code.
474 // Passing it through is the safest bet.
475 write!(handle, "{}", text)?;
481 let text = self.preprocess(
482 text.trim_end_matches(|c| c == '\r' || c == '\n'),
486 let mut max_width = cursor_max - cursor;
488 // line buffer (avoid calling write! for every character)
489 let mut line_buf = String::with_capacity(max_width * 4);
491 // Displayed width of line_buf
492 let mut current_width = 0;
494 for c in text.chars() {
495 // calculate the displayed width for next character
496 let cw = c.width().unwrap_or(0);
499 // if next character cannot be printed on this line,
501 if current_width > max_width {
502 // Generate wrap padding if not already generated.
503 if panel_wrap.is_none() {
504 panel_wrap = if self.panel_width > 0 {
510 .generate(line_number, true, self)
512 .collect::<Vec<String>>()
528 self.ansi_prefix_sgr, ansi_prefix, line_buf
530 self.config.true_color,
531 self.config.colored_output,
532 self.config.use_italic_text,
535 panel_wrap.clone().unwrap()
539 max_width = cursor_max;
549 cursor += current_width;
557 self.ansi_prefix_sgr, ansi_prefix, line_buf
559 self.config.true_color,
560 self.config.colored_output,
561 self.config.use_italic_text,
566 // Clear the ANSI prefix buffer.
573 if let Some(background_color) = background_color {
574 let mut ansi_style = Style::default();
575 ansi_style.background =
576 Some(to_ansi_color(background_color, self.config.true_color));
581 ansi_style.paint(" ".repeat(cursor_max - cursor))
591const DEFAULT_GUTTER_COLOR: u8 = 238;
593#[derive(Debug, Default)]
597 pub git_added: Style,
598 pub git_removed: Style,
599 pub git_modified: Style,
600 pub line_number: Style,
608 fn colored(theme: &Theme, true_color: bool) -> Self {
609 let gutter_color = theme
612 .map(|c| to_ansi_color(c, true_color))
613 .unwrap_or(Fixed(DEFAULT_GUTTER_COLOR));
616 grid: gutter_color.normal(),
617 filename: Style::new().bold(),
618 git_added: Green.normal(),
619 git_removed: Red.normal(),
620 git_modified: Yellow.normal(),
621 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