5use ansi_term::Colour::{Fixed, Green, Red, Yellow};
8use console::AnsiCodeIterator;
10use syntect::easy::HighlightLines;
11use syntect::highlighting::Color;
12use syntect::highlighting::Theme;
13use syntect::parsing::SyntaxSet;
15use content_inspector::ContentType;
17use encoding::all::{UTF_16BE, UTF_16LE};
18use encoding::{DecoderTrap, Encoding};
20use unicode_width::UnicodeWidthChar;
22use crate::assets::HighlightingAssets;
23use crate::config::Config;
24#[cfg(feature = "git")]
25use crate::decorations::LineChangesDecoration;
26use crate::decorations::{Decoration, GridBorderDecoration, LineNumberDecoration};
27#[cfg(feature = "git")]
28use crate::diff::{get_git_diff, LineChanges};
30use crate::inputfile::{InputFile, InputFileReader};
31use crate::line_range::RangeCheckResult;
32use crate::preprocessor::{expand_tabs, replace_nonprintable};
33use crate::terminal::{as_terminal_escaped, to_ansi_color};
34use crate::wrap::OutputWrap;
37 fn print_header(&mut self, handle: &mut dyn Write, file: InputFile) -> Result<()>;
38 fn print_footer(&mut self, handle: &mut dyn Write) -> Result<()>;
40 fn print_snip(&mut self, handle: &mut dyn Write) -> Result<()>;
45 handle: &mut dyn Write,
51pub struct SimplePrinter;
54 pub fn new() -> Self {
59impl Printer for SimplePrinter {
60 fn print_header(&mut self, _handle: &mut dyn Write, _file: InputFile) -> Result<()> {
64 fn print_footer(&mut self, _handle: &mut dyn Write) -> Result<()> {
68 fn print_snip(&mut self, _handle: &mut dyn Write) -> Result<()> {
75 handle: &mut dyn Write,
80 handle.write_all(line_buffer)?;
86pub struct InteractivePrinter<'a> {
88 config: &'a Config<'a>,
89 decorations: Vec<Box<dyn Decoration>>,
91 ansi_prefix_sgr: String,
92 content_type: Option<ContentType>,
93 #[cfg(feature = "git")]
94 pub line_changes: Option<LineChanges>,
95 highlighter: Option<HighlightLines<'a>>,
96 syntax_set: &'a SyntaxSet,
97 background_color_highlight: Option<Color>,
100impl<'a> InteractivePrinter<'a> {
103 assets: &'a HighlightingAssets,
105 reader: &mut InputFileReader,
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 #[cfg(feature = "git")]
151 let mut line_changes = None;
153 let highlighter = if reader
155 .map_or(false, |c| c.is_binary() && !config.show_nonprintable)
159 // Get the Git modifications
160 #[cfg(feature = "git")]
162 if config.style_components.changes() {
163 if let InputFile::Ordinary(ofile) = file {
164 line_changes = get_git_diff(ofile.filename());
169 // Determine the type of syntax for highlighting
170 let syntax = assets.get_syntax(config.language, file, reader, &config.syntax_mapping);
171 Some(HighlightLines::new(syntax, theme))
179 content_type: reader.content_type,
180 ansi_prefix_sgr: String::new(),
181 #[cfg(feature = "git")]
184 syntax_set: &assets.syntax_set,
185 background_color_highlight,
189 fn print_horizontal_line(&mut self, handle: &mut dyn Write, grid_char: char) -> Result<()> {
190 if self.panel_width == 0 {
194 self.colors.grid.paint("─".repeat(self.config.term_width))
197 let hline = "─".repeat(self.config.term_width - (self.panel_width + 1));
198 let hline = format!("{}{}{}", "─".repeat(self.panel_width), grid_char, hline);
199 writeln!(handle, "{}", self.colors.grid.paint(hline))?;
205 fn create_fake_panel(&self, text: &str) -> String {
206 if self.panel_width == 0 {
209 let text_truncated: String = text.chars().take(self.panel_width - 1).collect();
210 let text_filled: String = format!(
213 " ".repeat(self.panel_width - 1 - text_truncated.len())
215 if self.config.style_components.grid() {
216 format!("{} │ ", text_filled)
218 format!("{}", text_filled)
223 fn preprocess(&self, text: &str, cursor: &mut usize) -> String {
224 if self.config.tab_width > 0 {
225 expand_tabs(text, self.config.tab_width, cursor)
232impl<'a> Printer for InteractivePrinter<'a> {
233 fn print_header(&mut self, handle: &mut dyn Write, file: InputFile) -> Result<()> {
234 if !self.config.style_components.header() {
235 if Some(ContentType::BINARY) == self.content_type && !self.config.show_nonprintable {
236 let input = match file {
237 InputFile::Ordinary(ofile) => {
238 format!("file '{}'", &ofile.filename().to_string_lossy())
240 InputFile::StdIn(Some(name)) => name.to_str().unwrap().to_string(),
241 InputFile::StdIn(None) => "STDIN".to_owned(),
242 InputFile::ThemePreviewFile => "".to_owned(),
247 "{}: Binary content from {} will not be printed to the terminal \
248 (but will be present if the output of 'bat' is piped). You can use 'bat -A' \
249 to show the binary file contents.",
250 Yellow.paint("[bat warning]"),
254 if self.config.style_components.grid() {
255 self.print_horizontal_line(handle, '┬')?;
261 if self.config.style_components.grid() {
262 self.print_horizontal_line(handle, '┬')?;
267 " ".repeat(self.panel_width),
270 .paint(if self.panel_width > 0 { "│ " } else { "" }),
273 write!(handle, "{}", " ".repeat(self.panel_width))?;
276 let (prefix, name) = match file {
277 InputFile::Ordinary(ofile) => (
279 Cow::from(ofile.filename().to_string_lossy().to_owned()),
281 InputFile::StdIn(Some(name)) => {
282 ("File: ", Cow::from(name.to_string_lossy().to_owned()))
284 InputFile::StdIn(None) => ("File: ", Cow::from("STDIN".to_owned())),
285 InputFile::ThemePreviewFile => ("", Cow::from("")),
288 let mode = match self.content_type {
289 Some(ContentType::BINARY) => " <BINARY>",
290 Some(ContentType::UTF_16LE) => " <UTF-16LE>",
291 Some(ContentType::UTF_16BE) => " <UTF-16BE>",
300 self.colors.filename.paint(name),
304 if self.config.style_components.grid() {
305 if self.content_type.map_or(false, |c| c.is_text()) || self.config.show_nonprintable {
306 self.print_horizontal_line(handle, '┼')?;
308 self.print_horizontal_line(handle, '┴')?;
315 fn print_footer(&mut self, handle: &mut dyn Write) -> Result<()> {
316 if self.config.style_components.grid()
317 && (self.content_type.map_or(false, |c| c.is_text()) || self.config.show_nonprintable)
319 self.print_horizontal_line(handle, '┴')
325 fn print_snip(&mut self, handle: &mut dyn Write) -> Result<()> {
326 let panel = self.create_fake_panel(" ...");
327 let panel_count = panel.chars().count();
330 let title_count = title.chars().count();
332 let snip_left = "─ ".repeat((self.config.term_width - panel_count - (title_count / 2)) / 4);
333 let snip_left_count = snip_left.chars().count(); // Can't use .len() with Unicode.
336 " ─".repeat((self.config.term_width - panel_count - snip_left_count - title_count) / 2);
343 .paint(format!("{}{}{}{}", panel, snip_left, title, snip_right))
352 handle: &mut dyn Write,
356 let line = if self.config.show_nonprintable {
357 replace_nonprintable(&line_buffer, self.config.tab_width)
359 match self.content_type {
360 Some(ContentType::BINARY) | None => {
363 Some(ContentType::UTF_16LE) => UTF_16LE
364 .decode(&line_buffer, DecoderTrap::Replace)
365 .map_err(|_| "Invalid UTF-16LE")?,
366 Some(ContentType::UTF_16BE) => UTF_16BE
367 .decode(&line_buffer, DecoderTrap::Replace)
368 .map_err(|_| "Invalid UTF-16BE")?,
369 _ => String::from_utf8_lossy(&line_buffer).to_string(),
374 let highlighter = match self.highlighter {
375 Some(ref mut highlighter) => highlighter,
380 highlighter.highlight(line.as_ref(), self.syntax_set)
387 let mut cursor: usize = 0;
388 let mut cursor_max: usize = self.config.term_width;
389 let mut cursor_total: usize = 0;
390 let mut panel_wrap: Option<String> = None;
393 let highlight_this_line =
394 self.config.highlighted_lines.0.check(line_number) == RangeCheckResult::InRange;
396 let background_color = self
397 .background_color_highlight
398 .filter(|_| highlight_this_line);
401 if self.panel_width > 0 {
402 let decorations = self
405 .map(|ref d| d.generate(line_number, false, self))
406 .collect::<Vec<_>>();
408 for deco in decorations {
409 write!(handle, "{} ", deco.text)?;
410 cursor_max -= deco.width + 1;
415 if self.config.output_wrap == OutputWrap::None {
416 let true_color = self.config.true_color;
417 let colored_output = self.config.colored_output;
418 let italics = self.config.use_italic_text;
420 for &(style, region) in regions.iter() {
421 let text = &*self.preprocess(region, &mut cursor_total);
422 let text_trimmed = text.trim_end_matches(|c| c == '\r' || c == '\n');
436 if text.len() != text_trimmed.len() {
437 if let Some(background_color) = background_color {
438 let mut ansi_style = Style::default();
439 ansi_style.background = Some(to_ansi_color(background_color, true_color));
440 let width = if cursor_total <= cursor_max {
441 cursor_max - cursor_total + 1
445 write!(handle, "{}", ansi_style.paint(" ".repeat(width)))?;
447 write!(handle, "{}", &text[text_trimmed.len()..])?;
451 if line.bytes().next_back() != Some(b'\n') {
455 for &(style, region) in regions.iter() {
456 let ansi_iterator = AnsiCodeIterator::new(region);
457 let mut ansi_prefix: String = String::new();
458 for chunk in ansi_iterator {
460 // ANSI escape passthrough.
462 let is_ansi_csi = text.starts_with("\x1B[");
464 if is_ansi_csi && text.ends_with('m') {
465 // It's an ANSI SGR sequence.
466 // We should be mostly safe to just append these together.
467 ansi_prefix.push_str(text);
468 if text == "\x1B[0m" {
469 self.ansi_prefix_sgr = "\x1B[0m".to_owned();
471 self.ansi_prefix_sgr.push_str(text);
473 } else if is_ansi_csi {
474 // It's a regular CSI sequence.
475 // We should be mostly safe to just append these together.
476 ansi_prefix.push_str(text);
478 // It's probably a VT100 code.
479 // Passing it through is the safest bet.
480 write!(handle, "{}", text)?;
486 let text = self.preprocess(
487 text.trim_end_matches(|c| c == '\r' || c == '\n'),
491 let mut max_width = cursor_max - cursor;
493 // line buffer (avoid calling write! for every character)
494 let mut line_buf = String::with_capacity(max_width * 4);
496 // Displayed width of line_buf
497 let mut current_width = 0;
499 for c in text.chars() {
500 // calculate the displayed width for next character
501 let cw = c.width().unwrap_or(0);
504 // if next character cannot be printed on this line,
506 if current_width > max_width {
507 // Generate wrap padding if not already generated.
508 if panel_wrap.is_none() {
509 panel_wrap = if self.panel_width > 0 {
515 .generate(line_number, true, self)
517 .collect::<Vec<String>>()
533 self.ansi_prefix_sgr, ansi_prefix, line_buf
535 self.config.true_color,
536 self.config.colored_output,
537 self.config.use_italic_text,
540 panel_wrap.clone().unwrap()
544 max_width = cursor_max;
554 cursor += current_width;
562 self.ansi_prefix_sgr, ansi_prefix, line_buf
564 self.config.true_color,
565 self.config.colored_output,
566 self.config.use_italic_text,
571 // Clear the ANSI prefix buffer.
578 if let Some(background_color) = background_color {
579 let mut ansi_style = Style::default();
580 ansi_style.background =
581 Some(to_ansi_color(background_color, self.config.true_color));
586 ansi_style.paint(" ".repeat(cursor_max - cursor))
596const DEFAULT_GUTTER_COLOR: u8 = 238;
598#[derive(Debug, Default)]
602 pub git_added: Style,
603 pub git_removed: Style,
604 pub git_modified: Style,
605 pub line_number: Style,
613 fn colored(theme: &Theme, true_color: bool) -> Self {
614 let gutter_color = theme
617 .map(|c| to_ansi_color(c, true_color))
618 .unwrap_or(Fixed(DEFAULT_GUTTER_COLOR));
621 grid: gutter_color.normal(),
622 filename: Style::new().bold(),
623 git_added: Green.normal(),
624 git_removed: Red.normal(),
625 git_modified: Yellow.normal(),
626 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