on b68c5d8 help sign in
bat/src/printer.rs
466 lines 16 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::Theme;
11use syntect::parsing::SyntaxSet;
13use content_inspector::ContentType;
15use encoding::all::{UTF_16BE, UTF_16LE};
16use encoding::{DecoderTrap, Encoding};
18use app::Config;
19use assets::HighlightingAssets;
20use decorations::{Decoration, GridBorderDecoration, LineChangesDecoration, LineNumberDecoration};
21use diff::get_git_diff;
22use diff::LineChanges;
23use errors::*;
24use inputfile::{InputFile, InputFileReader};
25use preprocessor::{expand_tabs, replace_nonprintable};
26use style::OutputWrap;
27use terminal::{as_terminal_escaped, to_ansi_color};
29pub trait Printer {
30 fn print_header(&mut self, handle: &mut Write, file: InputFile) -> Result<()>;
31 fn print_footer(&mut self, handle: &mut Write) -> Result<()>;
32 fn print_line(
33 &mut self,
34 out_of_range: bool,
35 handle: &mut Write,
36 line_number: usize,
37 line_buffer: &[u8],
38 ) -> Result<()>;
41pub struct SimplePrinter;
43impl SimplePrinter {
44 pub fn new() -> Self {
45 SimplePrinter {}
46 }
49impl Printer for SimplePrinter {
50 fn print_header(&mut self, _handle: &mut Write, _file: InputFile) -> Result<()> {
51 Ok(())
52 }
54 fn print_footer(&mut self, _handle: &mut Write) -> Result<()> {
55 Ok(())
56 }
58 fn print_line(
59 &mut self,
60 out_of_range: bool,
61 handle: &mut Write,
62 _line_number: usize,
63 line_buffer: &[u8],
64 ) -> Result<()> {
65 if !out_of_range {
66 handle.write(line_buffer)?;
67 }
68 Ok(())
69 }
72pub struct InteractivePrinter<'a> {
73 colors: Colors,
74 config: &'a Config<'a>,
75 decorations: Vec<Box<dyn Decoration>>,
76 panel_width: usize,
77 ansi_prefix_sgr: String,
78 content_type: ContentType,
79 pub line_changes: Option<LineChanges>,
80 highlighter: Option<HighlightLines<'a>>,
81 syntax_set: &'a SyntaxSet,
84impl<'a> InteractivePrinter<'a> {
85 pub fn new(
86 config: &'a Config,
87 assets: &'a HighlightingAssets,
88 file: InputFile,
89 reader: &mut InputFileReader,
90 ) -> Self {
91 let theme = assets.get_theme(&config.theme);
93 let colors = if config.colored_output {
94 Colors::colored(theme, config.true_color)
95 } else {
96 Colors::plain()
97 };
99 // Create decorations.
100 let mut decorations: Vec<Box<dyn Decoration>> = Vec::new();
102 if config.output_components.numbers() {
103 decorations.push(Box::new(LineNumberDecoration::new(&colors)));
104 }
106 if config.output_components.changes() {
107 decorations.push(Box::new(LineChangesDecoration::new(&colors)));
108 }
110 let mut panel_width: usize =
111 decorations.len() + decorations.iter().fold(0, |a, x| a + x.width());
113 // The grid border decoration isn't added until after the panel_width calculation, since the
114 // print_horizontal_line, print_header, and print_footer functions all assume the panel
115 // width is without the grid border.
116 if config.output_components.grid() && !decorations.is_empty() {
117 decorations.push(Box::new(GridBorderDecoration::new(&colors)));
118 }
120 // Disable the panel if the terminal is too small (i.e. can't fit 5 characters with the
121 // panel showing).
122 if config.term_width
123 < (decorations.len() + decorations.iter().fold(0, |a, x| a + x.width())) + 5
124 {
125 decorations.clear();
126 panel_width = 0;
127 }
129 let mut line_changes = None;
131 let highlighter = if reader.content_type.is_binary() {
132 None
133 } else {
134 // Get the Git modifications
135 line_changes = if config.output_components.changes() {
136 match file {
137 InputFile::Ordinary(filename) => get_git_diff(filename),
138 _ => None,
139 }
140 } else {
141 None
142 };
144 // Determine the type of syntax for highlighting
145 let syntax = assets.get_syntax(config.language, file, reader, &config.syntax_mapping);
146 Some(HighlightLines::new(syntax, theme))
147 };
149 InteractivePrinter {
150 panel_width,
151 colors,
152 config,
153 decorations,
154 content_type: reader.content_type,
155 ansi_prefix_sgr: String::new(),
156 line_changes,
157 highlighter,
158 syntax_set: &assets.syntax_set,
159 }
160 }
162 fn print_horizontal_line(&mut self, handle: &mut Write, grid_char: char) -> Result<()> {
163 if self.panel_width == 0 {
164 writeln!(
165 handle,
166 "{}",
167 self.colors.grid.paint("─".repeat(self.config.term_width))
168 )?;
169 } else {
170 let hline = "─".repeat(self.config.term_width - (self.panel_width + 1));
171 let hline = format!("{}{}{}", "─".repeat(self.panel_width), grid_char, hline);
172 writeln!(handle, "{}", self.colors.grid.paint(hline))?;
173 }
175 Ok(())
176 }
178 fn preprocess(&self, text: &str, cursor: &mut usize) -> String {
179 if self.config.tab_width > 0 {
180 expand_tabs(text, self.config.tab_width, cursor)
181 } else {
182 text.to_string()
183 }
184 }
187impl<'a> Printer for InteractivePrinter<'a> {
188 fn print_header(&mut self, handle: &mut Write, file: InputFile) -> Result<()> {
189 if !self.config.output_components.header() {
190 return Ok(());
191 }
193 if self.config.output_components.grid() {
194 self.print_horizontal_line(handle, '┬')?;
196 write!(
197 handle,
198 "{}{}",
199 " ".repeat(self.panel_width),
200 self.colors
201 .grid
202 .paint(if self.panel_width > 0 { "│ " } else { "" }),
203 )?;
204 } else {
205 write!(handle, "{}", " ".repeat(self.panel_width))?;
206 }
208 let (prefix, name) = match file {
209 InputFile::Ordinary(filename) => ("File: ", filename),
210 _ => ("", "STDIN"),
211 };
213 let mode = match self.content_type {
214 ContentType::BINARY => " <BINARY>",
215 ContentType::UTF_16LE => " <UTF-16LE>",
216 ContentType::UTF_16BE => " <UTF-16BE>",
217 _ => "",
218 };
220 writeln!(
221 handle,
222 "{}{}{}",
223 prefix,
224 self.colors.filename.paint(name),
225 mode
226 )?;
228 if self.config.output_components.grid() {
229 if self.content_type.is_text() {
230 self.print_horizontal_line(handle, '┼')?;
231 } else {
232 self.print_horizontal_line(handle, '┴')?;
233 }
234 }
236 Ok(())
237 }
239 fn print_footer(&mut self, handle: &mut Write) -> Result<()> {
240 if self.config.output_components.grid() && self.content_type.is_text() {
241 self.print_horizontal_line(handle, '┴')
242 } else {
243 Ok(())
244 }
245 }
247 fn print_line(
248 &mut self,
249 out_of_range: bool,
250 handle: &mut Write,
251 line_number: usize,
252 line_buffer: &[u8],
253 ) -> Result<()> {
254 let mut line = match self.content_type {
255 ContentType::BINARY => {
256 return Ok(());
257 }
258 ContentType::UTF_16LE => UTF_16LE
259 .decode(&line_buffer, DecoderTrap::Strict)
260 .unwrap_or("Invalid UTF-16LE".into()),
261 ContentType::UTF_16BE => UTF_16BE
262 .decode(&line_buffer, DecoderTrap::Strict)
263 .unwrap_or("Invalid UTF-16BE".into()),
264 _ => String::from_utf8_lossy(&line_buffer).to_string(),
265 };
267 if self.config.show_nonprintable {
268 line = replace_nonprintable(&mut line, self.config.tab_width);
269 }
271 let regions = {
272 let highlighter = match self.highlighter {
273 Some(ref mut highlighter) => highlighter,
274 _ => {
275 return Ok(());
276 }
277 };
278 highlighter.highlight(line.as_ref(), self.syntax_set)
279 };
281 if out_of_range {
282 return Ok(());
283 }
285 let mut cursor: usize = 0;
286 let mut cursor_max: usize = self.config.term_width;
287 let mut cursor_total: usize = 0;
288 let mut panel_wrap: Option<String> = None;
290 // Line decorations.
291 if self.panel_width > 0 {
292 let decorations = self
293 .decorations
294 .iter()
295 .map(|ref d| d.generate(line_number, false, self))
296 .collect::<Vec<_>>();
298 for deco in decorations {
299 write!(handle, "{} ", deco.text)?;
300 cursor_max -= deco.width + 1;
301 }
302 }
304 // Line contents.
305 if self.config.output_wrap == OutputWrap::None {
306 let true_color = self.config.true_color;
307 let colored_output = self.config.colored_output;
308 let italics = self.config.use_italic_text;
310 for &(style, region) in regions.iter() {
311 let text = &*self.preprocess(region, &mut cursor_total);
312 let text_trimmed = text.trim_end_matches(|c| c == '\r' || c == '\n');
313 write!(
314 handle,
315 "{}",
316 as_terminal_escaped(style, text_trimmed, true_color, colored_output, italics,)
317 )?;
318 write!(handle, "{}", &text[text_trimmed.len()..])?;
319 }
321 if line.bytes().next_back() != Some(b'\n') {
322 write!(handle, "\n")?;
323 }
324 } else {
325 for &(style, region) in regions.iter() {
326 let mut ansi_iterator = AnsiCodeIterator::new(region);
327 let mut ansi_prefix: String = String::new();
328 for chunk in ansi_iterator {
329 match chunk {
330 // ANSI escape passthrough.
331 (text, true) => {
332 if text.chars().last().map_or(false, |c| c == 'm') {
333 ansi_prefix.push_str(text);
334 if text == "\x1B[0m" {
335 self.ansi_prefix_sgr = "\x1B[0m".to_owned();
336 } else {
337 self.ansi_prefix_sgr.push_str(text);
338 }
339 } else {
340 ansi_prefix.push_str(text);
341 }
342 }
344 // Regular text.
345 (text, false) => {
346 let text = self.preprocess(
347 text.trim_end_matches(|c| c == '\r' || c == '\n'),
348 &mut cursor_total,
349 );
351 let mut chars = text.chars();
352 let mut remaining = text.chars().count();
354 while remaining > 0 {
355 let available = cursor_max - cursor;
357 // It fits.
358 if remaining <= available {
359 let text = chars.by_ref().take(remaining).collect::<String>();
360 cursor += remaining;
362 write!(
363 handle,
364 "{}",
365 as_terminal_escaped(
366 style,
367 &*format!(
368 "{}{}{}",
369 self.ansi_prefix_sgr, ansi_prefix, text
370 ),
371 self.config.true_color,
372 self.config.colored_output,
373 self.config.use_italic_text
374 )
375 )?;
376 break;
377 }
379 // Generate wrap padding if not already generated.
380 if panel_wrap.is_none() {
381 panel_wrap = if self.panel_width > 0 {
382 Some(format!(
383 "{} ",
384 self.decorations
385 .iter()
386 .map(|ref d| d
387 .generate(line_number, true, self)
388 .text)
389 .collect::<Vec<String>>()
390 .join(" ")
391 ))
392 } else {
393 Some("".to_string())
394 }
395 }
397 // It wraps.
398 let text = chars.by_ref().take(available).collect::<String>();
399 cursor = 0;
400 remaining -= available;
402 write!(
403 handle,
404 "{}\n{}",
405 as_terminal_escaped(
406 style,
407 &*format!(
408 "{}{}{}",
409 self.ansi_prefix_sgr, ansi_prefix, text
410 ),
411 self.config.true_color,
412 self.config.colored_output,
413 self.config.use_italic_text
414 ),
415 panel_wrap.clone().unwrap()
416 )?;
417 }
419 // Clear the ANSI prefix buffer.
420 ansi_prefix.clear();
421 }
422 }
423 }
424 }
426 write!(handle, "\n")?;
427 }
429 Ok(())
430 }
433const DEFAULT_GUTTER_COLOR: u8 = 238;
435#[derive(Default)]
436pub struct Colors {
437 pub grid: Style,
438 pub filename: Style,
439 pub git_added: Style,
440 pub git_removed: Style,
441 pub git_modified: Style,
442 pub line_number: Style,
445impl Colors {
446 fn plain() -> Self {
447 Colors::default()
448 }
450 fn colored(theme: &Theme, true_color: bool) -> Self {
451 let gutter_color = theme
452 .settings
453 .gutter_foreground
454 .map(|c| to_ansi_color(c, true_color))
455 .unwrap_or(Fixed(DEFAULT_GUTTER_COLOR));
457 Colors {
458 grid: gutter_color.normal(),
459 filename: Style::new().bold(),
460 git_added: Green.normal(),
461 git_removed: Red.normal(),
462 git_modified: Yellow.normal(),
463 line_number: gutter_color.normal(),
464 }
465 }