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