on 6b92814 help sign in
bat/src/printer.rs
493 lines 17 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 background_color = if self
297 .config
298 .highlight_lines
299 .iter()
300 .find(|&&l| l == line_number)
301 .is_some()
302 {
303 self.background_color_highlight
304 } else {
305 None
306 };
308 // Line decorations.
309 if self.panel_width > 0 {
310 let decorations = self
311 .decorations
312 .iter()
313 .map(|ref d| d.generate(line_number, false, self))
314 .collect::<Vec<_>>();
316 for deco in decorations {
317 write!(handle, "{} ", deco.text)?;
318 cursor_max -= deco.width + 1;
319 }
320 }
322 // Line contents.
323 if self.config.output_wrap == OutputWrap::None {
324 let true_color = self.config.true_color;
325 let colored_output = self.config.colored_output;
326 let italics = self.config.use_italic_text;
328 for &(style, region) in regions.iter() {
329 let text = &*self.preprocess(region, &mut cursor_total);
330 let text_trimmed = text.trim_end_matches(|c| c == '\r' || c == '\n');
331 write!(
332 handle,
333 "{}",
334 as_terminal_escaped(
335 style,
336 text_trimmed,
337 true_color,
338 colored_output,
339 italics,
340 background_color
341 )
342 )?;
343 write!(handle, "{}", &text[text_trimmed.len()..])?;
344 }
346 if line.bytes().next_back() != Some(b'\n') {
347 write!(handle, "\n")?;
348 }
349 } else {
350 for &(style, region) in regions.iter() {
351 let mut ansi_iterator = AnsiCodeIterator::new(region);
352 let mut ansi_prefix: String = String::new();
353 for chunk in ansi_iterator {
354 match chunk {
355 // ANSI escape passthrough.
356 (text, true) => {
357 if text.chars().last().map_or(false, |c| c == 'm') {
358 ansi_prefix.push_str(text);
359 if text == "\x1B[0m" {
360 self.ansi_prefix_sgr = "\x1B[0m".to_owned();
361 } else {
362 self.ansi_prefix_sgr.push_str(text);
363 }
364 } else {
365 ansi_prefix.push_str(text);
366 }
367 }
369 // Regular text.
370 (text, false) => {
371 let text = self.preprocess(
372 text.trim_end_matches(|c| c == '\r' || c == '\n'),
373 &mut cursor_total,
374 );
376 let mut chars = text.chars();
377 let mut remaining = text.chars().count();
379 while remaining > 0 {
380 let available = cursor_max - cursor;
382 // It fits.
383 if remaining <= available {
384 let text = chars.by_ref().take(remaining).collect::<String>();
385 cursor += remaining;
387 write!(
388 handle,
389 "{}",
390 as_terminal_escaped(
391 style,
392 &*format!(
393 "{}{}{}",
394 self.ansi_prefix_sgr, ansi_prefix, text
395 ),
396 self.config.true_color,
397 self.config.colored_output,
398 self.config.use_italic_text,
399 background_color
400 )
401 )?;
402 break;
403 }
405 // Generate wrap padding if not already generated.
406 if panel_wrap.is_none() {
407 panel_wrap = if self.panel_width > 0 {
408 Some(format!(
409 "{} ",
410 self.decorations
411 .iter()
412 .map(|ref d| d
413 .generate(line_number, true, self)
414 .text)
415 .collect::<Vec<String>>()
416 .join(" ")
417 ))
418 } else {
419 Some("".to_string())
420 }
421 }
423 // It wraps.
424 let text = chars.by_ref().take(available).collect::<String>();
425 cursor = 0;
426 remaining -= available;
428 write!(
429 handle,
430 "{}\n{}",
431 as_terminal_escaped(
432 style,
433 &*format!(
434 "{}{}{}",
435 self.ansi_prefix_sgr, ansi_prefix, text
436 ),
437 self.config.true_color,
438 self.config.colored_output,
439 self.config.use_italic_text,
440 background_color
441 ),
442 panel_wrap.clone().unwrap()
443 )?;
444 }
446 // Clear the ANSI prefix buffer.
447 ansi_prefix.clear();
448 }
449 }
450 }
451 }
453 write!(handle, "\n")?;
454 }
456 Ok(())
457 }
460const DEFAULT_GUTTER_COLOR: u8 = 238;
462#[derive(Default)]
463pub struct Colors {
464 pub grid: Style,
465 pub filename: Style,
466 pub git_added: Style,
467 pub git_removed: Style,
468 pub git_modified: Style,
469 pub line_number: Style,
472impl Colors {
473 fn plain() -> Self {
474 Colors::default()
475 }
477 fn colored(theme: &Theme, true_color: bool) -> Self {
478 let gutter_color = theme
479 .settings
480 .gutter_foreground
481 .map(|c| to_ansi_color(c, true_color))
482 .unwrap_or(Fixed(DEFAULT_GUTTER_COLOR));
484 Colors {
485 grid: gutter_color.normal(),
486 filename: Style::new().bold(),
487 git_added: Green.normal(),
488 git_removed: Red.normal(),
489 git_modified: Yellow.normal(),
490 line_number: gutter_color.normal(),
491 }
492 }