on 3a89486 help sign in
bat/src/printer.rs
381 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 style::OutputWrap;
20use terminal::{as_terminal_escaped, to_ansi_color};
22pub trait Printer {
23 fn print_header(&mut self, handle: &mut Write, file: InputFile) -> Result<()>;
24 fn print_footer(&mut self, handle: &mut Write) -> Result<()>;
25 fn print_line(
26 &mut self,
27 out_of_range: bool,
28 handle: &mut Write,
29 line_number: usize,
30 line_buffer: &[u8],
31 ) -> Result<()>;
34pub struct SimplePrinter;
36impl SimplePrinter {
37 pub fn new() -> Self {
38 SimplePrinter {}
39 }
42impl Printer for SimplePrinter {
43 fn print_header(&mut self, _handle: &mut Write, _file: InputFile) -> Result<()> {
44 Ok(())
45 }
47 fn print_footer(&mut self, _handle: &mut Write) -> Result<()> {
48 Ok(())
49 }
51 fn print_line(
52 &mut self,
53 out_of_range: bool,
54 handle: &mut Write,
55 _line_number: usize,
56 line_buffer: &[u8],
57 ) -> Result<()> {
58 if !out_of_range {
59 handle.write(line_buffer)?;
60 }
61 Ok(())
62 }
65pub struct InteractivePrinter<'a> {
66 colors: Colors,
67 config: &'a Config<'a>,
68 decorations: Vec<Box<Decoration>>,
69 panel_width: usize,
70 ansi_prefix_sgr: String,
71 pub line_changes: Option<LineChanges>,
72 highlighter: HighlightLines<'a>,
75impl<'a> InteractivePrinter<'a> {
76 pub fn new(config: &'a Config, assets: &'a HighlightingAssets, file: InputFile) -> Self {
77 let theme = assets.get_theme(&config.theme);
79 let colors = if config.colored_output {
80 Colors::colored(theme, config.true_color)
81 } else {
82 Colors::plain()
83 };
85 // Create decorations.
86 let mut decorations: Vec<Box<Decoration>> = Vec::new();
88 if config.output_components.numbers() {
89 decorations.push(Box::new(LineNumberDecoration::new(&colors)));
90 }
92 if config.output_components.changes() {
93 decorations.push(Box::new(LineChangesDecoration::new(&colors)));
94 }
96 let mut panel_width: usize =
97 decorations.len() + decorations.iter().fold(0, |a, x| a + x.width());
99 // The grid border decoration isn't added until after the panel_width calculation, since the
100 // print_horizontal_line, print_header, and print_footer functions all assume the panel
101 // width is without the grid border.
102 if config.output_components.grid() && !decorations.is_empty() {
103 decorations.push(Box::new(GridBorderDecoration::new(&colors)));
104 }
106 // Disable the panel if the terminal is too small (i.e. can't fit 5 characters with the
107 // panel showing).
108 if config.term_width
109 < (decorations.len() + decorations.iter().fold(0, |a, x| a + x.width())) + 5
110 {
111 decorations.clear();
112 panel_width = 0;
113 }
115 // Get the Git modifications
116 let line_changes = match file {
117 InputFile::Ordinary(filename) => get_git_diff(filename),
118 _ => None,
119 };
121 // Determine the type of syntax for highlighting
122 let syntax = assets.get_syntax(config.language, file);
123 let highlighter = HighlightLines::new(syntax, theme);
125 InteractivePrinter {
126 panel_width,
127 colors,
128 config,
129 decorations,
130 ansi_prefix_sgr: String::new(),
131 line_changes,
132 highlighter,
133 }
134 }
136 fn print_horizontal_line(&mut self, handle: &mut Write, grid_char: char) -> Result<()> {
137 if self.panel_width == 0 {
138 writeln!(
139 handle,
140 "{}",
141 self.colors.grid.paint("─".repeat(self.config.term_width))
142 )?;
143 } else {
144 let hline = "─".repeat(self.config.term_width - (self.panel_width + 1));
145 let hline = format!("{}{}{}", "─".repeat(self.panel_width), grid_char, hline);
146 writeln!(handle, "{}", self.colors.grid.paint(hline))?;
147 }
149 Ok(())
150 }
153impl<'a> Printer for InteractivePrinter<'a> {
154 fn print_header(&mut self, handle: &mut Write, file: InputFile) -> Result<()> {
155 if !self.config.output_components.header() {
156 return Ok(());
157 }
159 if self.config.output_components.grid() {
160 self.print_horizontal_line(handle, '┬')?;
162 write!(
163 handle,
164 "{}{}",
165 " ".repeat(self.panel_width),
166 self.colors
167 .grid
168 .paint(if self.panel_width > 0 { "│ " } else { "" }),
169 )?;
170 } else {
171 write!(handle, "{}", " ".repeat(self.panel_width))?;
172 }
174 let (prefix, name) = match file {
175 InputFile::Ordinary(filename) => ("File: ", filename),
176 _ => ("", "STDIN"),
177 };
179 writeln!(handle, "{}{}", prefix, self.colors.filename.paint(name))?;
181 if self.config.output_components.grid() {
182 self.print_horizontal_line(handle, '┼')?;
183 }
185 Ok(())
186 }
188 fn print_footer(&mut self, handle: &mut Write) -> Result<()> {
189 if self.config.output_components.grid() {
190 self.print_horizontal_line(handle, '┴')
191 } else {
192 Ok(())
193 }
194 }
196 fn print_line(
197 &mut self,
198 out_of_range: bool,
199 handle: &mut Write,
200 line_number: usize,
201 line_buffer: &[u8],
202 ) -> Result<()> {
203 let line = String::from_utf8_lossy(&line_buffer);
204 let regions = self.highlighter.highlight(line.as_ref());
206 if out_of_range {
207 return Ok(());
208 }
210 let mut cursor: usize = 0;
211 let mut cursor_max: usize = self.config.term_width;
212 let mut panel_wrap: Option<String> = None;
214 // Line decorations.
215 if self.panel_width > 0 {
216 let decorations = self
217 .decorations
218 .iter()
219 .map(|ref d| d.generate(line_number, false, self))
220 .collect::<Vec<_>>();
222 for deco in decorations {
223 write!(handle, "{} ", deco.text)?;
224 cursor_max -= deco.width + 1;
225 }
226 }
228 // Line contents.
229 if self.config.output_wrap == OutputWrap::None {
230 let true_color = self.config.true_color;
231 let colored_output = self.config.colored_output;
233 write!(
234 handle,
235 "{}",
236 regions
237 .iter()
238 .map(|&(style, text)| as_terminal_escaped(
239 style,
240 text,
241 true_color,
242 colored_output,
243 )).collect::<Vec<_>>()
244 .join("")
245 )?;
246 } else {
247 for &(style, region) in regions.iter() {
248 let mut ansi_iterator = AnsiCodeIterator::new(region);
249 let mut ansi_prefix: String = String::new();
250 for chunk in ansi_iterator {
251 match chunk {
252 // ANSI escape passthrough.
253 (text, true) => {
254 if text.chars().last().map_or(false, |c| c == 'm') {
255 ansi_prefix.push_str(text);
256 if text == "\x1B[0m" {
257 self.ansi_prefix_sgr = "\x1B[0m".to_owned();
258 } else {
259 self.ansi_prefix_sgr.push_str(text);
260 }
261 } else {
262 ansi_prefix.push_str(text);
263 }
264 }
266 // Regular text.
267 (text, false) => {
268 let text = text.trim_right_matches(|c| c == '\r' || c == '\n');
269 let mut chars = text.chars();
270 let mut remaining = text.chars().count();
272 while remaining > 0 {
273 let available = cursor_max - cursor;
275 // It fits.
276 if remaining <= available {
277 let text = chars.by_ref().take(remaining).collect::<String>();
278 cursor += remaining;
280 write!(
281 handle,
282 "{}",
283 as_terminal_escaped(
284 style,
285 &*format!(
286 "{}{}{}",
287 self.ansi_prefix_sgr, ansi_prefix, text
288 ),
289 self.config.true_color,
290 self.config.colored_output,
291 )
292 )?;
293 break;
294 }
296 // Generate wrap padding if not already generated.
297 if panel_wrap.is_none() {
298 panel_wrap = if self.panel_width > 0 {
299 Some(format!(
300 "{} ",
301 self.decorations
302 .iter()
303 .map(|ref d| d
304 .generate(line_number, true, self)
305 .text).collect::<Vec<String>>()
306 .join(" ")
307 ))
308 } else {
309 Some("".to_string())
310 }
311 }
313 // It wraps.
314 let text = chars.by_ref().take(available).collect::<String>();
315 cursor = 0;
316 remaining -= available;
318 write!(
319 handle,
320 "{}\n{}",
321 as_terminal_escaped(
322 style,
323 &*format!(
324 "{}{}{}",
325 self.ansi_prefix_sgr, ansi_prefix, text
326 ),
327 self.config.true_color,
328 self.config.colored_output,
329 ),
330 panel_wrap.clone().unwrap()
331 )?;
332 }
334 // Clear the ANSI prefix buffer.
335 ansi_prefix.clear();
336 }
337 }
338 }
339 }
341 write!(handle, "\n")?;
342 }
344 Ok(())
345 }
348const DEFAULT_GUTTER_COLOR: u8 = 238;
350#[derive(Default)]
351pub struct Colors {
352 pub grid: Style,
353 pub filename: Style,
354 pub git_added: Style,
355 pub git_removed: Style,
356 pub git_modified: Style,
357 pub line_number: Style,
360impl Colors {
361 fn plain() -> Self {
362 Colors::default()
363 }
365 fn colored(theme: &Theme, true_color: bool) -> Self {
366 let gutter_color = theme
367 .settings
368 .gutter_foreground
369 .map(|c| to_ansi_color(c, true_color))
370 .unwrap_or(Fixed(DEFAULT_GUTTER_COLOR));
372 Colors {
373 grid: gutter_color.normal(),
374 filename: Style::new().bold(),
375 git_added: Green.normal(),
376 git_removed: Red.normal(),
377 git_modified: Yellow.normal(),
378 line_number: gutter_color.normal(),
379 }
380 }