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::vscreen::AnsiStyle;
34use crate::wrapping::WrappingMode;
36pub(crate) trait Printer {
39 handle: &mut dyn Write,
41 add_header_padding: bool,
43 fn print_footer(&mut self, handle: &mut dyn Write, input: &OpenedInput) -> Result<()>;
45 fn print_snip(&mut self, handle: &mut dyn Write) -> Result<()>;
50 handle: &mut dyn Write,
56pub struct SimplePrinter<'a> {
57 config: &'a Config<'a>,
60impl<'a> SimplePrinter<'a> {
61 pub fn new(config: &'a Config) -> Self {
62 SimplePrinter { config }
66impl<'a> Printer for SimplePrinter<'a> {
69 _handle: &mut dyn Write,
71 _add_header_padding: bool,
76 fn print_footer(&mut self, _handle: &mut dyn Write, _input: &OpenedInput) -> Result<()> {
80 fn print_snip(&mut self, _handle: &mut dyn Write) -> Result<()> {
87 handle: &mut dyn Write,
92 if self.config.show_nonprintable {
93 let line = replace_nonprintable(line_buffer, self.config.tab_width);
94 write!(handle, "{}", line)?;
96 handle.write_all(line_buffer)?
103struct HighlighterFromSet<'a> {
104 highlighter: HighlightLines<'a>,
105 syntax_set: &'a SyntaxSet,
108impl<'a> HighlighterFromSet<'a> {
109 fn new(syntax_in_set: SyntaxReferenceInSet<'a>, theme: &'a Theme) -> Self {
111 highlighter: HighlightLines::new(syntax_in_set.syntax, theme),
112 syntax_set: syntax_in_set.syntax_set,
117pub(crate) struct InteractivePrinter<'a> {
119 config: &'a Config<'a>,
120 decorations: Vec<Box<dyn Decoration>>,
122 ansi_style: AnsiStyle,
123 content_type: Option<ContentType>,
124 #[cfg(feature = "git")]
125 pub line_changes: &'a Option<LineChanges>,
126 highlighter_from_set: Option<HighlighterFromSet<'a>>,
127 background_color_highlight: Option<Color>,
130impl<'a> InteractivePrinter<'a> {
133 assets: &'a HighlightingAssets,
134 input: &mut OpenedInput,
135 #[cfg(feature = "git")] line_changes: &'a Option<LineChanges>,
137 let theme = assets.get_theme(&config.theme);
139 let background_color_highlight = theme.settings.line_highlight;
141 let colors = if config.colored_output {
142 Colors::colored(theme, config.true_color)
147 // Create decorations.
148 let mut decorations: Vec<Box<dyn Decoration>> = Vec::new();
150 if config.style_components.numbers() {
151 decorations.push(Box::new(LineNumberDecoration::new(&colors)));
154 #[cfg(feature = "git")]
156 if config.style_components.changes() {
157 decorations.push(Box::new(LineChangesDecoration::new(&colors)));
161 let mut panel_width: usize =
162 decorations.len() + decorations.iter().fold(0, |a, x| a + x.width());
164 // The grid border decoration isn't added until after the panel_width calculation, since the
165 // print_horizontal_line, print_header, and print_footer functions all assume the panel
166 // width is without the grid border.
167 if config.style_components.grid() && !decorations.is_empty() {
168 decorations.push(Box::new(GridBorderDecoration::new(&colors)));
171 // Disable the panel if the terminal is too small (i.e. can't fit 5 characters with the
174 < (decorations.len() + decorations.iter().fold(0, |a, x| a + x.width())) + 5
180 let highlighter_from_set = if input
183 .map_or(false, |c| c.is_binary() && !config.show_nonprintable)
187 // Determine the type of syntax for highlighting
189 match assets.get_syntax(config.language, input, &config.syntax_mapping) {
190 Ok(syntax_in_set) => syntax_in_set,
191 Err(Error::UndetectedSyntax(_)) => assets
192 .find_syntax_by_name("Plain Text")?
193 .expect("A plain text syntax is available"),
194 Err(e) => return Err(e),
197 Some(HighlighterFromSet::new(syntax_in_set, theme))
200 Ok(InteractivePrinter {
205 content_type: input.reader.content_type,
206 ansi_style: AnsiStyle::new(),
207 #[cfg(feature = "git")]
209 highlighter_from_set,
210 background_color_highlight,
214 fn print_horizontal_line_term(&mut self, handle: &mut dyn Write, style: Style) -> Result<()> {
218 style.paint("─".repeat(self.config.term_width))
223 fn print_horizontal_line(&mut self, handle: &mut dyn Write, grid_char: char) -> Result<()> {
224 if self.panel_width == 0 {
225 self.print_horizontal_line_term(handle, self.colors.grid)?;
227 let hline = "─".repeat(self.config.term_width - (self.panel_width + 1));
228 let hline = format!("{}{}{}", "─".repeat(self.panel_width), grid_char, hline);
229 writeln!(handle, "{}", self.colors.grid.paint(hline))?;
235 fn create_fake_panel(&self, text: &str) -> String {
236 if self.panel_width == 0 {
237 return "".to_string();
240 let text_truncated: String = text.chars().take(self.panel_width - 1).collect();
241 let text_filled: String = format!(
244 " ".repeat(self.panel_width - 1 - text_truncated.len())
246 if self.config.style_components.grid() {
247 format!("{} │ ", text_filled)
253 fn preprocess(&self, text: &str, cursor: &mut usize) -> String {
254 if self.config.tab_width > 0 {
255 return expand_tabs(text, self.config.tab_width, cursor);
258 *cursor += text.len();
263impl<'a> Printer for InteractivePrinter<'a> {
266 handle: &mut dyn Write,
268 add_header_padding: bool,
270 if add_header_padding && self.config.style_components.rule() {
271 self.print_horizontal_line_term(handle, self.colors.rule)?;
274 if !self.config.style_components.header() {
275 if Some(ContentType::BINARY) == self.content_type && !self.config.show_nonprintable {
278 "{}: Binary content from {} will not be printed to the terminal \
279 (but will be present if the output of 'bat' is piped). You can use 'bat -A' \
280 to show the binary file contents.",
281 Yellow.paint("[bat warning]"),
282 input.description.summary(),
284 } else if self.config.style_components.grid() {
285 self.print_horizontal_line(handle, '┬')?;
290 if self.config.style_components.grid() {
291 self.print_horizontal_line(handle, '┬')?;
296 " ".repeat(self.panel_width),
299 .paint(if self.panel_width > 0 { "│ " } else { "" }),
302 // Only pad space between files, if we haven't already drawn a horizontal rule
303 if add_header_padding && !self.config.style_components.rule() {
306 write!(handle, "{}", " ".repeat(self.panel_width))?;
309 let mode = match self.content_type {
310 Some(ContentType::BINARY) => " <BINARY>",
311 Some(ContentType::UTF_16LE) => " <UTF-16LE>",
312 Some(ContentType::UTF_16BE) => " <UTF-16BE>",
317 let description = &input.description;
324 .map(|kind| format!("{}: ", kind))
325 .unwrap_or_else(|| "".into()),
326 self.colors.filename.paint(description.title()),
330 if self.config.style_components.grid() {
331 if self.content_type.map_or(false, |c| c.is_text()) || self.config.show_nonprintable {
332 self.print_horizontal_line(handle, '┼')?;
334 self.print_horizontal_line(handle, '┴')?;
341 fn print_footer(&mut self, handle: &mut dyn Write, _input: &OpenedInput) -> Result<()> {
342 if self.config.style_components.grid()
343 && (self.content_type.map_or(false, |c| c.is_text()) || self.config.show_nonprintable)
345 self.print_horizontal_line(handle, '┴')
351 fn print_snip(&mut self, handle: &mut dyn Write) -> Result<()> {
352 let panel = self.create_fake_panel(" ...");
353 let panel_count = panel.chars().count();
356 let title_count = title.chars().count();
358 let snip_left = "─ ".repeat((self.config.term_width - panel_count - (title_count / 2)) / 4);
359 let snip_left_count = snip_left.chars().count(); // Can't use .len() with Unicode.
362 " ─".repeat((self.config.term_width - panel_count - snip_left_count - title_count) / 2);
369 .paint(format!("{}{}{}{}", panel, snip_left, title, snip_right))
378 handle: &mut dyn Write,
382 let line = if self.config.show_nonprintable {
383 replace_nonprintable(line_buffer, self.config.tab_width)
385 match self.content_type {
386 Some(ContentType::BINARY) | None => {
389 Some(ContentType::UTF_16LE) => UTF_16LE
390 .decode(line_buffer, DecoderTrap::Replace)
391 .map_err(|_| "Invalid UTF-16LE")?,
392 Some(ContentType::UTF_16BE) => UTF_16BE
393 .decode(line_buffer, DecoderTrap::Replace)
394 .map_err(|_| "Invalid UTF-16BE")?,
395 _ => String::from_utf8_lossy(line_buffer).to_string(),
400 let highlighter_from_set = match self.highlighter_from_set {
401 Some(ref mut highlighter_from_set) => highlighter_from_set,
408 .highlight(&line, highlighter_from_set.syntax_set)
415 let mut cursor: usize = 0;
416 let mut cursor_max: usize = self.config.term_width;
417 let mut cursor_total: usize = 0;
418 let mut panel_wrap: Option<String> = None;
421 let highlight_this_line =
422 self.config.highlighted_lines.0.check(line_number) == RangeCheckResult::InRange;
424 let background_color = self
425 .background_color_highlight
426 .filter(|_| highlight_this_line);
429 if self.panel_width > 0 {
430 let decorations = self
433 .map(|d| d.generate(line_number, false, self));
435 for deco in decorations {
436 write!(handle, "{} ", deco.text)?;
437 cursor_max -= deco.width + 1;
442 if matches!(self.config.wrapping_mode, WrappingMode::NoWrapping(_)) {
443 let true_color = self.config.true_color;
444 let colored_output = self.config.colored_output;
445 let italics = self.config.use_italic_text;
447 for &(style, region) in ®ions {
448 let ansi_iterator = AnsiCodeIterator::new(region);
449 for chunk in ansi_iterator {
451 // ANSI escape passthrough.
453 self.ansi_style.update(ansi);
454 write!(handle, "{}", ansi)?;
459 let text = &*self.preprocess(text, &mut cursor_total);
460 let text_trimmed = text.trim_end_matches(|c| c == '\r' || c == '\n');
467 &format!("{}{}", self.ansi_style, text_trimmed),
475 if text.len() != text_trimmed.len() {
476 if let Some(background_color) = background_color {
477 let ansi_style = Style {
478 background: to_ansi_color(background_color, true_color),
482 let width = if cursor_total <= cursor_max {
483 cursor_max - cursor_total + 1
487 write!(handle, "{}", ansi_style.paint(" ".repeat(width)))?;
489 write!(handle, "{}", &text[text_trimmed.len()..])?;
496 if !self.config.style_components.plain() && line.bytes().next_back() != Some(b'\n') {
500 for &(style, region) in ®ions {
501 let ansi_iterator = AnsiCodeIterator::new(region);
502 for chunk in ansi_iterator {
504 // ANSI escape passthrough.
506 self.ansi_style.update(ansi);
507 write!(handle, "{}", ansi)?;
512 let text = self.preprocess(
513 text.trim_end_matches(|c| c == '\r' || c == '\n'),
517 let mut max_width = cursor_max - cursor;
519 // line buffer (avoid calling write! for every character)
520 let mut line_buf = String::with_capacity(max_width * 4);
522 // Displayed width of line_buf
523 let mut current_width = 0;
525 for c in text.chars() {
526 // calculate the displayed width for next character
527 let cw = c.width().unwrap_or(0);
530 // if next character cannot be printed on this line,
532 if current_width > max_width {
533 // Generate wrap padding if not already generated.
534 if panel_wrap.is_none() {
535 panel_wrap = if self.panel_width > 0 {
541 .generate(line_number, true, self)
543 .collect::<Vec<String>>()
557 &*format!("{}{}", self.ansi_style, line_buf),
558 self.config.true_color,
559 self.config.colored_output,
560 self.config.use_italic_text,
563 panel_wrap.clone().unwrap()
567 max_width = cursor_max;
577 cursor += current_width;
583 &*format!("{}{}", self.ansi_style, line_buf),
584 self.config.true_color,
585 self.config.colored_output,
586 self.config.use_italic_text,
595 if let Some(background_color) = background_color {
596 let ansi_style = Style {
597 background: to_ansi_color(background_color, self.config.true_color),
604 ansi_style.paint(" ".repeat(cursor_max - cursor))
614const DEFAULT_GUTTER_COLOR: u8 = 238;
616#[derive(Debug, Default)]
621 pub git_added: Style,
622 pub git_removed: Style,
623 pub git_modified: Style,
624 pub line_number: Style,
632 fn colored(theme: &Theme, true_color: bool) -> Self {
633 let gutter_style = Style {
634 foreground: match theme.settings.gutter_foreground {
635 // If the theme provides a gutter foreground color, use it.
636 // Note: It might be the special value #00000001, in which case
637 // to_ansi_color returns None and we use an empty Style
638 // (resulting in the terminal's default foreground color).
639 Some(c) => to_ansi_color(c, true_color),
640 // Otherwise, use a specific fallback color.
641 None => Some(Fixed(DEFAULT_GUTTER_COLOR)),
649 filename: Style::new().bold(),
650 git_added: Green.normal(),
651 git_removed: Red.normal(),
652 git_modified: Yellow.normal(),
653 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