on abf0229 help sign in
bat/src/printer.rs
515 lines 18 kB history raw
1use std::io::Write;
2use std::vec::Vec;
4use ansi_term::Colour::{Fixed, Green, Red, Yellow};
5use ansi_term::Style;
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 app::Config;
20use assets::HighlightingAssets;
21use decorations::{Decoration, GridBorderDecoration, LineChangesDecoration, LineNumberDecoration};
22use diff::get_git_diff;
23use diff::LineChanges;
24use errors::*;
25use inputfile::{InputFile, InputFileReader};
26use preprocessor::{expand_tabs, replace_nonprintable};
27use style::OutputWrap;
28use terminal::{as_terminal_escaped, to_ansi_color};
30pub trait Printer {
31 fn print_header(&mut self, handle: &mut Write, file: InputFile) -> Result<()>;
32 fn print_footer(&mut self, handle: &mut Write) -> Result<()>;
33 fn print_line(
34 &mut self,
35 out_of_range: bool,
36 handle: &mut Write,
37 line_number: usize,
38 line_buffer: &[u8],
39 ) -> Result<()>;
42pub struct SimplePrinter;
44impl SimplePrinter {
45 pub fn new() -> Self {
46 SimplePrinter {}
47 }
50impl Printer for SimplePrinter {
51 fn print_header(&mut self, _handle: &mut Write, _file: InputFile) -> Result<()> {
52 Ok(())
53 }
55 fn print_footer(&mut self, _handle: &mut Write) -> Result<()> {
56 Ok(())
57 }
59 fn print_line(
60 &mut self,
61 out_of_range: bool,
62 handle: &mut Write,
63 _line_number: usize,
64 line_buffer: &[u8],
65 ) -> Result<()> {
66 if !out_of_range {
67 handle.write(line_buffer)?;
68 }
69 Ok(())
70 }
73pub struct InteractivePrinter<'a> {
74 colors: Colors,
75 config: &'a Config<'a>,
76 decorations: Vec<Box<dyn Decoration>>,
77 panel_width: usize,
78 ansi_prefix_sgr: String,
79 content_type: ContentType,
80 pub line_changes: Option<LineChanges>,
81 highlighter: Option<HighlightLines<'a>>,
82 syntax_set: &'a SyntaxSet,
83 background_color_highlight: Option<Color>,
86impl<'a> InteractivePrinter<'a> {
87 pub fn new(
88 config: &'a Config,
89 assets: &'a HighlightingAssets,
90 file: InputFile,
91 reader: &mut InputFileReader,
92 ) -> Self {
93 let theme = assets.get_theme(&config.theme);
95 let background_color_highlight = theme.settings.line_highlight;
97 let colors = if config.colored_output {
98 Colors::colored(theme, config.true_color)
99 } else {
100 Colors::plain()
101 };
103 // Create decorations.
104 let mut decorations: Vec<Box<dyn Decoration>> = Vec::new();
106 if config.output_components.numbers() {
107 decorations.push(Box::new(LineNumberDecoration::new(&colors)));
108 }
110 if config.output_components.changes() {
111 decorations.push(Box::new(LineChangesDecoration::new(&colors)));
112 }
114 let mut panel_width: usize =
115 decorations.len() + decorations.iter().fold(0, |a, x| a + x.width());
117 // The grid border decoration isn't added until after the panel_width calculation, since the
118 // print_horizontal_line, print_header, and print_footer functions all assume the panel
119 // width is without the grid border.
120 if config.output_components.grid() && !decorations.is_empty() {
121 decorations.push(Box::new(GridBorderDecoration::new(&colors)));
122 }
124 // Disable the panel if the terminal is too small (i.e. can't fit 5 characters with the
125 // panel showing).
126 if config.term_width
127 < (decorations.len() + decorations.iter().fold(0, |a, x| a + x.width())) + 5
128 {
129 decorations.clear();
130 panel_width = 0;
131 }
133 let mut line_changes = None;
135 let highlighter = if reader.content_type.is_binary() {
136 None
137 } else {
138 // Get the Git modifications
139 line_changes = if config.output_components.changes() {
140 match file {
141 InputFile::Ordinary(filename) => get_git_diff(filename),
142 _ => None,
143 }
144 } else {
145 None
146 };
148 // Determine the type of syntax for highlighting
149 let syntax = assets.get_syntax(config.language, file, reader, &config.syntax_mapping);
150 Some(HighlightLines::new(syntax, theme))
151 };
153 InteractivePrinter {
154 panel_width,
155 colors,
156 config,
157 decorations,
158 content_type: reader.content_type,
159 ansi_prefix_sgr: String::new(),
160 line_changes,
161 highlighter,
162 syntax_set: &assets.syntax_set,
163 background_color_highlight,
164 }
165 }
167 fn print_horizontal_line(&mut self, handle: &mut Write, grid_char: char) -> Result<()> {
168 if self.panel_width == 0 {
169 writeln!(
170 handle,
171 "{}",
172 self.colors.grid.paint("─".repeat(self.config.term_width))
173 )?;
174 } else {
175 let hline = "─".repeat(self.config.term_width - (self.panel_width + 1));
176 let hline = format!("{}{}{}", "─".repeat(self.panel_width), grid_char, hline);
177 writeln!(handle, "{}", self.colors.grid.paint(hline))?;
178 }
180 Ok(())
181 }
183 fn preprocess(&self, text: &str, cursor: &mut usize) -> String {
184 if self.config.tab_width > 0 {
185 expand_tabs(text, self.config.tab_width, cursor)
186 } else {
187 text.to_string()
188 }
189 }
192impl<'a> Printer for InteractivePrinter<'a> {
193 fn print_header(&mut self, handle: &mut Write, file: InputFile) -> Result<()> {
194 if !self.config.output_components.header() {
195 return Ok(());
196 }
198 if self.config.output_components.grid() {
199 self.print_horizontal_line(handle, '┬')?;
201 write!(
202 handle,
203 "{}{}",
204 " ".repeat(self.panel_width),
205 self.colors
206 .grid
207 .paint(if self.panel_width > 0 { "│ " } else { "" }),
208 )?;
209 } else {
210 write!(handle, "{}", " ".repeat(self.panel_width))?;
211 }
213 let (prefix, name) = match file {
214 InputFile::Ordinary(filename) => ("File: ", filename),
215 _ => ("", "STDIN"),
216 };
218 let mode = match self.content_type {
219 ContentType::BINARY => " <BINARY>",
220 ContentType::UTF_16LE => " <UTF-16LE>",
221 ContentType::UTF_16BE => " <UTF-16BE>",
222 _ => "",
223 };
225 writeln!(
226 handle,
227 "{}{}{}",
228 prefix,
229 self.colors.filename.paint(name),
230 mode
231 )?;
233 if self.config.output_components.grid() {
234 if self.content_type.is_text() {
235 self.print_horizontal_line(handle, '┼')?;
236 } else {
237 self.print_horizontal_line(handle, '┴')?;
238 }
239 }
241 Ok(())
242 }
244 fn print_footer(&mut self, handle: &mut Write) -> Result<()> {
245 if self.config.output_components.grid() && self.content_type.is_text() {
246 self.print_horizontal_line(handle, '┴')
247 } else {
248 Ok(())
249 }
250 }
252 fn print_line(
253 &mut self,
254 out_of_range: bool,
255 handle: &mut Write,
256 line_number: usize,
257 line_buffer: &[u8],
258 ) -> Result<()> {
259 let mut line = match self.content_type {
260 ContentType::BINARY => {
261 return Ok(());
262 }
263 ContentType::UTF_16LE => UTF_16LE
264 .decode(&line_buffer, DecoderTrap::Strict)
265 .unwrap_or("Invalid UTF-16LE".into()),
266 ContentType::UTF_16BE => UTF_16BE
267 .decode(&line_buffer, DecoderTrap::Strict)
268 .unwrap_or("Invalid UTF-16BE".into()),
269 _ => String::from_utf8_lossy(&line_buffer).to_string(),
270 };
272 if self.config.show_nonprintable {
273 line = replace_nonprintable(&mut line, self.config.tab_width);
274 }
276 let regions = {
277 let highlighter = match self.highlighter {
278 Some(ref mut highlighter) => highlighter,
279 _ => {
280 return Ok(());
281 }
282 };
283 highlighter.highlight(line.as_ref(), self.syntax_set)
284 };
286 if out_of_range {
287 return Ok(());
288 }
290 let mut cursor: usize = 0;
291 let mut cursor_max: usize = self.config.term_width;
292 let mut cursor_total: usize = 0;
293 let mut panel_wrap: Option<String> = None;
295 // Line highlighting
296 let highlight_this_line = self
297 .config
298 .highlight_lines
299 .iter()
300 .any(|&l| l == line_number);
302 let background_color = self
303 .background_color_highlight
304 .filter(|_| highlight_this_line);
306 // Line decorations.
307 if self.panel_width > 0 {
308 let decorations = self
309 .decorations
310 .iter()
311 .map(|ref d| d.generate(line_number, false, self))
312 .collect::<Vec<_>>();
314 for deco in decorations {
315 write!(handle, "{} ", deco.text)?;
316 cursor_max -= deco.width + 1;
317 }
318 }
320 // Line contents.
321 if self.config.output_wrap == OutputWrap::None {
322 let true_color = self.config.true_color;
323 let colored_output = self.config.colored_output;
324 let italics = self.config.use_italic_text;
326 for &(style, region) in regions.iter() {
327 let text = &*self.preprocess(region, &mut cursor_total);
328 let text_trimmed = text.trim_end_matches(|c| c == '\r' || c == '\n');
329 write!(
330 handle,
331 "{}",
332 as_terminal_escaped(
333 style,
334 text_trimmed,
335 true_color,
336 colored_output,
337 italics,
338 background_color
339 )
340 )?;
342 if text.len() != text_trimmed.len() {
343 if let Some(background_color) = background_color {
344 let mut ansi_style = Style::default();
345 ansi_style.background = Some(to_ansi_color(background_color, true_color));
346 let width = if cursor_total <= cursor_max {
347 cursor_max - cursor_total + 1
348 } else {
349 0
350 };
351 write!(handle, "{}", ansi_style.paint(" ".repeat(width)))?;
352 }
353 write!(handle, "{}", &text[text_trimmed.len()..])?;
354 }
355 }
357 if line.bytes().next_back() != Some(b'\n') {
358 write!(handle, "\n")?;
359 }
360 } else {
361 for &(style, region) in regions.iter() {
362 let mut ansi_iterator = AnsiCodeIterator::new(region);
363 let mut ansi_prefix: String = String::new();
364 for chunk in ansi_iterator {
365 match chunk {
366 // ANSI escape passthrough.
367 (text, true) => {
368 if text.chars().last().map_or(false, |c| c == 'm') {
369 ansi_prefix.push_str(text);
370 if text == "\x1B[0m" {
371 self.ansi_prefix_sgr = "\x1B[0m".to_owned();
372 } else {
373 self.ansi_prefix_sgr.push_str(text);
374 }
375 } else {
376 ansi_prefix.push_str(text);
377 }
378 }
380 // Regular text.
381 (text, false) => {
382 let text = self.preprocess(
383 text.trim_end_matches(|c| c == '\r' || c == '\n'),
384 &mut cursor_total,
385 );
387 let mut chars = text.chars();
388 let mut remaining = text.chars().count();
390 while remaining > 0 {
391 let available = cursor_max - cursor;
393 // It fits.
394 if remaining <= available {
395 let text = chars.by_ref().take(remaining).collect::<String>();
396 cursor += remaining;
398 write!(
399 handle,
400 "{}",
401 as_terminal_escaped(
402 style,
403 &*format!(
404 "{}{}{}",
405 self.ansi_prefix_sgr, ansi_prefix, text
406 ),
407 self.config.true_color,
408 self.config.colored_output,
409 self.config.use_italic_text,
410 background_color
411 )
412 )?;
413 break;
414 }
416 // Generate wrap padding if not already generated.
417 if panel_wrap.is_none() {
418 panel_wrap = if self.panel_width > 0 {
419 Some(format!(
420 "{} ",
421 self.decorations
422 .iter()
423 .map(|ref d| d
424 .generate(line_number, true, self)
425 .text)
426 .collect::<Vec<String>>()
427 .join(" ")
428 ))
429 } else {
430 Some("".to_string())
431 }
432 }
434 // It wraps.
435 let text = chars.by_ref().take(available).collect::<String>();
436 cursor = 0;
437 remaining -= available;
439 write!(
440 handle,
441 "{}\n{}",
442 as_terminal_escaped(
443 style,
444 &*format!(
445 "{}{}{}",
446 self.ansi_prefix_sgr, ansi_prefix, text
447 ),
448 self.config.true_color,
449 self.config.colored_output,
450 self.config.use_italic_text,
451 background_color
452 ),
453 panel_wrap.clone().unwrap()
454 )?;
455 }
457 // Clear the ANSI prefix buffer.
458 ansi_prefix.clear();
459 }
460 }
461 }
462 }
464 if let Some(background_color) = background_color {
465 let mut ansi_style = Style::default();
466 ansi_style.background =
467 Some(to_ansi_color(background_color, self.config.true_color));
469 write!(
470 handle,
471 "{}",
472 ansi_style.paint(" ".repeat(cursor_max - cursor))
473 )?;
474 }
475 write!(handle, "\n")?;
476 }
478 Ok(())
479 }
482const DEFAULT_GUTTER_COLOR: u8 = 238;
484#[derive(Default)]
485pub struct Colors {
486 pub grid: Style,
487 pub filename: Style,
488 pub git_added: Style,
489 pub git_removed: Style,
490 pub git_modified: Style,
491 pub line_number: Style,
494impl Colors {
495 fn plain() -> Self {
496 Colors::default()
497 }
499 fn colored(theme: &Theme, true_color: bool) -> Self {
500 let gutter_color = theme
501 .settings
502 .gutter_foreground
503 .map(|c| to_ansi_color(c, true_color))
504 .unwrap_or(Fixed(DEFAULT_GUTTER_COLOR));
506 Colors {
507 grid: gutter_color.normal(),
508 filename: Style::new().bold(),
509 git_added: Green.normal(),
510 git_removed: Red.normal(),
511 git_modified: Yellow.normal(),
512 line_number: gutter_color.normal(),
513 }
514 }