on v0.7.1 help sign in
bat/src/printer.rs
398 lines 13 kB history raw
1use std::boxed::Box;
2use std::io::Write;
3use std::vec::Vec;
5use ansi_term::Colour::{Fixed, Green, Red, Yellow};
6use ansi_term::Style;
8use console::AnsiCodeIterator;
10use syntect::easy::HighlightLines;
11use syntect::highlighting::Theme;
13use app::{Config, InputFile};
14use assets::HighlightingAssets;
15use decorations::{Decoration, GridBorderDecoration, LineChangesDecoration, LineNumberDecoration};
16use diff::get_git_diff;
17use diff::LineChanges;
18use errors::*;
19use preprocessor::expand;
20use style::OutputWrap;
21use terminal::{as_terminal_escaped, to_ansi_color};
23pub trait Printer {
24 fn print_header(&mut self, handle: &mut Write, file: InputFile) -> Result<()>;
25 fn print_footer(&mut self, handle: &mut Write) -> Result<()>;
26 fn print_line(
27 &mut self,
28 out_of_range: bool,
29 handle: &mut Write,
30 line_number: usize,
31 line_buffer: &[u8],
32 ) -> Result<()>;
35pub struct SimplePrinter;
37impl SimplePrinter {
38 pub fn new() -> Self {
39 SimplePrinter {}
40 }
43impl Printer for SimplePrinter {
44 fn print_header(&mut self, _handle: &mut Write, _file: InputFile) -> Result<()> {
45 Ok(())
46 }
48 fn print_footer(&mut self, _handle: &mut Write) -> Result<()> {
49 Ok(())
50 }
52 fn print_line(
53 &mut self,
54 out_of_range: bool,
55 handle: &mut Write,
56 _line_number: usize,
57 line_buffer: &[u8],
58 ) -> Result<()> {
59 if !out_of_range {
60 handle.write(line_buffer)?;
61 }
62 Ok(())
63 }
66pub struct InteractivePrinter<'a> {
67 colors: Colors,
68 config: &'a Config<'a>,
69 decorations: Vec<Box<Decoration>>,
70 panel_width: usize,
71 ansi_prefix_sgr: String,
72 pub line_changes: Option<LineChanges>,
73 highlighter: HighlightLines<'a>,
76impl<'a> InteractivePrinter<'a> {
77 pub fn new(config: &'a Config, assets: &'a HighlightingAssets, file: InputFile) -> Self {
78 let theme = assets.get_theme(&config.theme);
80 let colors = if config.colored_output {
81 Colors::colored(theme, config.true_color)
82 } else {
83 Colors::plain()
84 };
86 // Create decorations.
87 let mut decorations: Vec<Box<Decoration>> = Vec::new();
89 if config.output_components.numbers() {
90 decorations.push(Box::new(LineNumberDecoration::new(&colors)));
91 }
93 if config.output_components.changes() {
94 decorations.push(Box::new(LineChangesDecoration::new(&colors)));
95 }
97 let mut panel_width: usize =
98 decorations.len() + decorations.iter().fold(0, |a, x| a + x.width());
100 // The grid border decoration isn't added until after the panel_width calculation, since the
101 // print_horizontal_line, print_header, and print_footer functions all assume the panel
102 // width is without the grid border.
103 if config.output_components.grid() && !decorations.is_empty() {
104 decorations.push(Box::new(GridBorderDecoration::new(&colors)));
105 }
107 // Disable the panel if the terminal is too small (i.e. can't fit 5 characters with the
108 // panel showing).
109 if config.term_width
110 < (decorations.len() + decorations.iter().fold(0, |a, x| a + x.width())) + 5
111 {
112 decorations.clear();
113 panel_width = 0;
114 }
116 // Get the Git modifications
117 let line_changes = if config.output_components.changes() {
118 match file {
119 InputFile::Ordinary(filename) => get_git_diff(filename),
120 _ => None,
121 }
122 } else {
123 None
124 };
126 // Determine the type of syntax for highlighting
127 let syntax = assets.get_syntax(config.language, file);
128 let highlighter = HighlightLines::new(syntax, theme);
130 InteractivePrinter {
131 panel_width,
132 colors,
133 config,
134 decorations,
135 ansi_prefix_sgr: String::new(),
136 line_changes,
137 highlighter,
138 }
139 }
141 fn print_horizontal_line(&mut self, handle: &mut Write, grid_char: char) -> Result<()> {
142 if self.panel_width == 0 {
143 writeln!(
144 handle,
145 "{}",
146 self.colors.grid.paint("─".repeat(self.config.term_width))
147 )?;
148 } else {
149 let hline = "─".repeat(self.config.term_width - (self.panel_width + 1));
150 let hline = format!("{}{}{}", "─".repeat(self.panel_width), grid_char, hline);
151 writeln!(handle, "{}", self.colors.grid.paint(hline))?;
152 }
154 Ok(())
155 }
157 fn preprocess(&self, text: &str, cursor: &mut usize) -> String {
158 if self.config.tab_width > 0 {
159 expand(text, self.config.tab_width, cursor)
160 } else {
161 text.to_string()
162 }
163 }
166impl<'a> Printer for InteractivePrinter<'a> {
167 fn print_header(&mut self, handle: &mut Write, file: InputFile) -> Result<()> {
168 if !self.config.output_components.header() {
169 return Ok(());
170 }
172 if self.config.output_components.grid() {
173 self.print_horizontal_line(handle, '┬')?;
175 write!(
176 handle,
177 "{}{}",
178 " ".repeat(self.panel_width),
179 self.colors
180 .grid
181 .paint(if self.panel_width > 0 { "│ " } else { "" }),
182 )?;
183 } else {
184 write!(handle, "{}", " ".repeat(self.panel_width))?;
185 }
187 let (prefix, name) = match file {
188 InputFile::Ordinary(filename) => ("File: ", filename),
189 _ => ("", "STDIN"),
190 };
192 writeln!(handle, "{}{}", prefix, self.colors.filename.paint(name))?;
194 if self.config.output_components.grid() {
195 self.print_horizontal_line(handle, '┼')?;
196 }
198 Ok(())
199 }
201 fn print_footer(&mut self, handle: &mut Write) -> Result<()> {
202 if self.config.output_components.grid() {
203 self.print_horizontal_line(handle, '┴')
204 } else {
205 Ok(())
206 }
207 }
209 fn print_line(
210 &mut self,
211 out_of_range: bool,
212 handle: &mut Write,
213 line_number: usize,
214 line_buffer: &[u8],
215 ) -> Result<()> {
216 let line = String::from_utf8_lossy(&line_buffer).to_string();
217 let regions = self.highlighter.highlight(line.as_ref());
219 if out_of_range {
220 return Ok(());
221 }
223 let mut cursor: usize = 0;
224 let mut cursor_max: usize = self.config.term_width;
225 let mut cursor_total: usize = 0;
226 let mut panel_wrap: Option<String> = None;
228 // Line decorations.
229 if self.panel_width > 0 {
230 let decorations = self
231 .decorations
232 .iter()
233 .map(|ref d| d.generate(line_number, false, self))
234 .collect::<Vec<_>>();
236 for deco in decorations {
237 write!(handle, "{} ", deco.text)?;
238 cursor_max -= deco.width + 1;
239 }
240 }
242 // Line contents.
243 if self.config.output_wrap == OutputWrap::None {
244 let true_color = self.config.true_color;
245 let colored_output = self.config.colored_output;
247 for &(style, region) in regions.iter() {
248 let text = &*self.preprocess(region, &mut cursor_total);
249 write!(
250 handle,
251 "{}",
252 as_terminal_escaped(style, &*text, true_color, colored_output,)
253 )?;
254 }
256 if line.bytes().next_back() != Some(b'\n') {
257 write!(handle, "\n")?;
258 }
259 } else {
260 for &(style, region) in regions.iter() {
261 let mut ansi_iterator = AnsiCodeIterator::new(region);
262 let mut ansi_prefix: String = String::new();
263 for chunk in ansi_iterator {
264 match chunk {
265 // ANSI escape passthrough.
266 (text, true) => {
267 if text.chars().last().map_or(false, |c| c == 'm') {
268 ansi_prefix.push_str(text);
269 if text == "\x1B[0m" {
270 self.ansi_prefix_sgr = "\x1B[0m".to_owned();
271 } else {
272 self.ansi_prefix_sgr.push_str(text);
273 }
274 } else {
275 ansi_prefix.push_str(text);
276 }
277 }
279 // Regular text.
280 (text, false) => {
281 let text = self.preprocess(
282 text.trim_right_matches(|c| c == '\r' || c == '\n'),
283 &mut cursor_total,
284 );
286 let mut chars = text.chars();
287 let mut remaining = text.chars().count();
289 while remaining > 0 {
290 let available = cursor_max - cursor;
292 // It fits.
293 if remaining <= available {
294 let text = chars.by_ref().take(remaining).collect::<String>();
295 cursor += remaining;
297 write!(
298 handle,
299 "{}",
300 as_terminal_escaped(
301 style,
302 &*format!(
303 "{}{}{}",
304 self.ansi_prefix_sgr, ansi_prefix, text
305 ),
306 self.config.true_color,
307 self.config.colored_output,
308 )
309 )?;
310 break;
311 }
313 // Generate wrap padding if not already generated.
314 if panel_wrap.is_none() {
315 panel_wrap = if self.panel_width > 0 {
316 Some(format!(
317 "{} ",
318 self.decorations
319 .iter()
320 .map(|ref d| d
321 .generate(line_number, true, self)
322 .text).collect::<Vec<String>>()
323 .join(" ")
324 ))
325 } else {
326 Some("".to_string())
327 }
328 }
330 // It wraps.
331 let text = chars.by_ref().take(available).collect::<String>();
332 cursor = 0;
333 remaining -= available;
335 write!(
336 handle,
337 "{}\n{}",
338 as_terminal_escaped(
339 style,
340 &*format!(
341 "{}{}{}",
342 self.ansi_prefix_sgr, ansi_prefix, text
343 ),
344 self.config.true_color,
345 self.config.colored_output,
346 ),
347 panel_wrap.clone().unwrap()
348 )?;
349 }
351 // Clear the ANSI prefix buffer.
352 ansi_prefix.clear();
353 }
354 }
355 }
356 }
358 write!(handle, "\n")?;
359 }
361 Ok(())
362 }
365const DEFAULT_GUTTER_COLOR: u8 = 238;
367#[derive(Default)]
368pub struct Colors {
369 pub grid: Style,
370 pub filename: Style,
371 pub git_added: Style,
372 pub git_removed: Style,
373 pub git_modified: Style,
374 pub line_number: Style,
377impl Colors {
378 fn plain() -> Self {
379 Colors::default()
380 }
382 fn colored(theme: &Theme, true_color: bool) -> Self {
383 let gutter_color = theme
384 .settings
385 .gutter_foreground
386 .map(|c| to_ansi_color(c, true_color))
387 .unwrap_or(Fixed(DEFAULT_GUTTER_COLOR));
389 Colors {
390 grid: gutter_color.normal(),
391 filename: Style::new().bold(),
392 git_added: Green.normal(),
393 git_removed: Red.normal(),
394 git_modified: Yellow.normal(),
395 line_number: gutter_color.normal(),
396 }
397 }