on v0.5.0 help sign in
bat/src/printer.rs
310 lines 11 kB history raw
1use ansi_term::Colour::{Fixed, Green, Red, Yellow};
2use ansi_term::Style;
3use app::Config;
4use console::AnsiCodeIterator;
5use decorations::{Decoration, GridBorderDecoration, LineChangesDecoration, LineNumberDecoration};
6use diff::LineChanges;
7use errors::*;
8use std::boxed::Box;
9use std::io::Write;
10use std::vec::Vec;
11use style::OutputWrap;
12use syntect::highlighting::{self, Theme};
13use terminal::{as_terminal_escaped, to_ansi_color};
15pub struct Printer<'a> {
16 handle: &'a mut Write,
17 colors: Colors,
18 pub config: &'a Config<'a>,
19 decorations: Vec<Box<Decoration>>,
20 panel_width: usize,
21 pub ansi_prefix_sgr: String,
22 pub line_number: usize,
23 pub line_changes: Option<LineChanges>,
26impl<'a> Printer<'a> {
27 pub fn new(handle: &'a mut Write, config: &'a Config, theme: &Theme) -> Self {
28 let colors = if config.colored_output {
29 Colors::colored(theme, config.true_color)
30 } else {
31 Colors::plain()
32 };
34 // Create decorations.
35 let mut decorations: Vec<Box<Decoration>> = Vec::new();
37 if config.output_components.numbers() {
38 decorations.push(Box::new(LineNumberDecoration::new(&colors)));
39 }
41 if config.output_components.changes() {
42 decorations.push(Box::new(LineChangesDecoration::new(&colors)));
43 }
45 let mut panel_width: usize =
46 decorations.len() + decorations.iter().fold(0, |a, x| a + x.width());
48 // The grid border decoration isn't added until after the panel_width calculation, since the
49 // print_horizontal_line, print_header, and print_footer functions all assume the panel
50 // width is without the grid border.
51 if config.output_components.grid() && !decorations.is_empty() {
52 decorations.push(Box::new(GridBorderDecoration::new(&colors)));
53 }
55 // Disable the panel if the terminal is too small (i.e. can't fit 5 characters with the
56 // panel showing).
57 if config.term_width
58 < (decorations.len() + decorations.iter().fold(0, |a, x| a + x.width())) + 5
59 {
60 decorations.clear();
61 panel_width = 0;
62 }
64 // Create printer.
65 Printer {
66 panel_width,
67 handle,
68 colors,
69 config,
70 decorations,
71 ansi_prefix_sgr: String::new(),
72 line_number: 0,
73 line_changes: None,
74 }
75 }
77 pub fn print_header(&mut self, filename: Option<&str>) -> Result<()> {
78 self.line_number = 0;
80 if !self.config.output_components.header() {
81 return Ok(());
82 }
84 if self.config.output_components.grid() {
85 self.print_horizontal_line('┬')?;
87 write!(
88 self.handle,
89 "{}{}",
90 " ".repeat(self.panel_width),
91 self.colors
92 .grid
93 .paint(if self.panel_width > 0 { "│ " } else { "" }),
94 )?;
95 } else {
96 write!(self.handle, "{}", " ".repeat(self.panel_width))?;
97 }
99 writeln!(
100 self.handle,
101 "{}{}",
102 filename.map_or("", |_| "File: "),
103 self.colors.filename.paint(filename.unwrap_or("STDIN"))
104 )?;
106 if self.config.output_components.grid() {
107 self.print_horizontal_line('┼')?;
108 }
110 Ok(())
111 }
113 pub fn print_footer(&mut self) -> Result<()> {
114 if self.config.output_components.grid() {
115 self.print_horizontal_line('┴')
116 } else {
117 Ok(())
118 }
119 }
121 pub fn print_line(&mut self, regions: &[(highlighting::Style, &str)]) -> Result<()> {
122 self.line_number += 1;
123 let mut cursor: usize = 0;
124 let mut cursor_max: usize = self.config.term_width;
125 let mut panel_wrap: Option<String> = None;
127 // Line decorations.
128 if self.panel_width > 0 {
129 let decorations = self
130 .decorations
131 .iter()
132 .map(|ref d| d.generate(self.line_number, false, self))
133 .collect::<Vec<_>>();
135 for deco in decorations {
136 write!(self.handle, "{} ", deco.text)?;
137 cursor_max -= deco.width + 1;
138 }
139 }
141 // Line contents.
142 if self.config.output_wrap == OutputWrap::None {
143 let true_color = self.config.true_color;
144 let colored_output = self.config.colored_output;
146 write!(
147 self.handle,
148 "{}",
149 regions
150 .iter()
151 .map(|&(style, text)| as_terminal_escaped(
152 style,
153 text,
154 true_color,
155 colored_output,
156 )).collect::<Vec<_>>()
157 .join("")
158 )?;
159 } else {
160 for &(style, region) in regions.iter() {
161 let mut ansi_iterator = AnsiCodeIterator::new(region);
162 let mut ansi_prefix: String = String::new();
163 for chunk in ansi_iterator {
164 match chunk {
165 // ANSI escape passthrough.
166 (text, true) => {
167 if text.chars().last().map_or(false, |c| c == 'm') {
168 ansi_prefix.push_str(text);
169 if text == "\x1B[0m" {
170 self.ansi_prefix_sgr = "\x1B[0m".to_owned();
171 } else {
172 self.ansi_prefix_sgr.push_str(text);
173 }
174 } else {
175 ansi_prefix.push_str(text);
176 }
177 }
179 // Regular text.
180 (text, false) => {
181 let text = text.trim_right_matches(|c| c == '\r' || c == '\n');
182 let mut chars = text.chars();
183 let mut remaining = text.chars().count();
185 while remaining > 0 {
186 let available = cursor_max - cursor;
188 // It fits.
189 if remaining <= available {
190 let text = chars.by_ref().take(remaining).collect::<String>();
191 cursor += remaining;
193 write!(
194 self.handle,
195 "{}",
196 as_terminal_escaped(
197 style,
198 &*format!(
199 "{}{}{}",
200 self.ansi_prefix_sgr, ansi_prefix, text
201 ),
202 self.config.true_color,
203 self.config.colored_output,
204 )
205 )?;
206 break;
207 }
209 // Generate wrap padding if not already generated.
210 if panel_wrap.is_none() {
211 panel_wrap = if self.panel_width > 0 {
212 Some(format!(
213 "{} ",
214 self.decorations
215 .iter()
216 .map(|ref d| d
217 .generate(self.line_number, true, self)
218 .text).collect::<Vec<String>>()
219 .join(" ")
220 ))
221 } else {
222 Some("".to_string())
223 }
224 }
226 // It wraps.
227 let text = chars.by_ref().take(available).collect::<String>();
228 cursor = 0;
229 remaining -= available;
231 write!(
232 self.handle,
233 "{}\n{}",
234 as_terminal_escaped(
235 style,
236 &*format!(
237 "{}{}{}",
238 self.ansi_prefix_sgr, ansi_prefix, text
239 ),
240 self.config.true_color,
241 self.config.colored_output,
242 ),
243 panel_wrap.clone().unwrap()
244 )?;
245 }
247 // Clear the ANSI prefix buffer.
248 ansi_prefix.clear();
249 }
250 }
251 }
252 }
254 write!(self.handle, "\n")?;
255 }
257 Ok(())
258 }
260 fn print_horizontal_line(&mut self, grid_char: char) -> Result<()> {
261 if self.panel_width == 0 {
262 writeln!(
263 self.handle,
264 "{}",
265 self.colors.grid.paint("─".repeat(self.config.term_width))
266 )?;
267 } else {
268 let hline = "─".repeat(self.config.term_width - (self.panel_width + 1));
269 let hline = format!("{}{}{}", "─".repeat(self.panel_width), grid_char, hline);
270 writeln!(self.handle, "{}", self.colors.grid.paint(hline))?;
271 }
273 Ok(())
274 }
277const DEFAULT_GUTTER_COLOR: u8 = 238;
279#[derive(Default)]
280pub struct Colors {
281 pub grid: Style,
282 pub filename: Style,
283 pub git_added: Style,
284 pub git_removed: Style,
285 pub git_modified: Style,
286 pub line_number: Style,
289impl Colors {
290 fn plain() -> Self {
291 Colors::default()
292 }
294 fn colored(theme: &Theme, true_color: bool) -> Self {
295 let gutter_color = theme
296 .settings
297 .gutter_foreground
298 .map(|c| to_ansi_color(c, true_color))
299 .unwrap_or(Fixed(DEFAULT_GUTTER_COLOR));
301 Colors {
302 grid: gutter_color.normal(),
303 filename: Style::new().bold(),
304 git_added: Green.normal(),
305 git_removed: Red.normal(),
306 git_modified: Yellow.normal(),
307 line_number: gutter_color.normal(),
308 }
309 }