on 9f005d1 help sign in
bat/src/printer.rs
266 lines 8.3 kB history raw
1use ansi_term::Style;
2use app::Config;
3use diff::{LineChange, LineChanges};
4use errors::*;
5use std::io::Write;
6use syntect::highlighting;
7use terminal::as_terminal_escaped;
8use style::OutputWrap;
9use Colors;
11const LINE_NUMBER_WIDTH: usize = 4;
13struct PrintSegment {
14 size: usize,
15 text: String,
18pub struct Printer<'a> {
19 handle: &'a mut Write,
20 colors: Colors,
21 config: &'a Config<'a>,
22 panel_width: usize,
23 pub line_changes: Option<LineChanges>,
26impl<'a> Printer<'a> {
27 pub fn new(handle: &'a mut Write, config: &'a Config) -> Self {
28 let colors = if config.colored_output {
29 Colors::colored()
30 } else {
31 Colors::plain()
32 };
34 // Create the instance.
35 let mut instance = Printer {
36 handle,
37 colors,
38 config,
39 panel_width: 0,
40 line_changes: None,
41 };
43 // Generate the panel (gutter) width.
44 let decorations = instance.gen_decorations(0);
45 instance.panel_width = decorations.len() + decorations.iter().fold(0, |a, x| a + x.size);
47 // Return the instance.
48 return instance;
49 }
51 pub fn print_header(&mut self, filename: Option<&str>) -> Result<()> {
52 if !self.config.output_components.header() {
53 return Ok(());
54 }
56 if self.config.output_components.grid() {
57 self.print_horizontal_line('┬')?;
59 write!(
60 self.handle,
61 "{}{} ",
62 " ".repeat(self.panel_width),
63 self.colors
64 .grid
65 .paint(if self.panel_width > 0 { "│" } else { "" }),
66 )?;
67 }
69 writeln!(
70 self.handle,
71 "{}{}",
72 filename.map_or("", |_| "File: "),
73 self.colors.filename.paint(filename.unwrap_or("STDIN"))
74 )?;
76 if self.config.output_components.grid() {
77 self.print_horizontal_line('┼')?;
78 }
80 Ok(())
81 }
83 pub fn print_footer(&mut self) -> Result<()> {
84 if self.config.output_components.grid() {
85 self.print_horizontal_line('┴')
86 } else {
87 Ok(())
88 }
89 }
91 pub fn print_line(
92 &mut self,
93 line_number: usize,
94 regions: &[(highlighting::Style, &str)],
95 ) -> Result<()> {
96 let mut cursor: usize = 0;
97 let mut cursor_max: usize = self.config.term_width;
99 // Line decoration.
100 let decorations = self.gen_decorations(line_number);
101 let gutter_width = decorations.len() + decorations.iter().fold(0, |a, x| a + x.size);
103 if gutter_width > 0 {
104 cursor_max -= gutter_width;
105 write!(
106 self.handle,
107 "{} ",
108 decorations
109 .iter()
110 .map(|seg| seg.text.to_owned())
111 .collect::<Vec<String>>()
112 .join(" ")
113 )?;
114 }
116 // Grid border.
117 let border = if gutter_width > 0 && self.config.output_components.grid() {
118 self.gen_border()
119 } else {
120 PrintSegment {
121 size: 0,
122 text: "".to_owned(),
123 }
124 };
126 cursor_max -= border.size;
127 write!(self.handle, "{}", border.text)?;
129 // Line contents.
130 if self.config.output_wrap == OutputWrap::None {
131 let true_color = self.config.true_color;
132 let colored_output = self.config.colored_output;
134 write!(self.handle, "{}",
135 regions.iter()
136 .map(|&(style, text)| as_terminal_escaped(style, text, true_color, colored_output))
137 .collect::<Vec<_>>()
138 .join("")
139 )?;
140 } else {
141 for &(style, text) in regions.iter() {
142 let mut chars = text.chars().filter(|c| *c != '\n');
143 let mut remaining = text.chars().filter(|c| *c != '\n').count();
145 while remaining > 0 {
146 let available = cursor_max - cursor;
148 // It fits.
149 if remaining <= available {
150 let text = chars.by_ref().take(remaining).collect::<String>();
151 cursor += remaining;
153 write!(
154 self.handle,
155 "{}",
156 as_terminal_escaped(
157 style,
158 &*text,
159 self.config.true_color,
160 self.config.colored_output,
161 )
162 )?;
163 break;
164 }
166 // It wraps.
167 if self.config.output_wrap == OutputWrap::Character {
168 let text = chars.by_ref().take(available).collect::<String>();
169 cursor = 0;
170 remaining -= available;
172 write!(
173 self.handle,
174 "{}\n{}{}",
175 as_terminal_escaped(
176 style,
177 &*text,
178 self.config.true_color,
179 self.config.colored_output,
180 ),
181 " ".repeat(gutter_width),
182 border.text.to_owned()
183 )?;
185 continue;
186 }
187 }
188 }
190 write!(self.handle, "\n")?;
191 }
193 // Finished.
194 Ok(())
195 }
197 /// Generates all the line decorations.
198 fn gen_decorations(&self, line_number: usize) -> Vec<PrintSegment> {
199 let mut decorations = Vec::new();
201 if self.config.output_components.numbers() {
202 decorations.push(self.gen_deco_line_number(line_number));
203 }
205 if self.config.output_components.changes() {
206 decorations.push(self.gen_deco_line_changes(line_number));
207 }
209 return decorations;
210 }
212 /// Generates the decoration for displaying the line number.
213 fn gen_deco_line_number(&self, line_number: usize) -> PrintSegment {
214 let plain: String = format!("{:width$}", line_number, width = LINE_NUMBER_WIDTH);
215 let color = self.colors.line_number.paint(plain.to_owned());
217 return PrintSegment {
218 text: color.to_string(),
219 size: plain.len(),
220 };
221 }
223 /// Generates the decoration for displaying the git changes.
224 fn gen_deco_line_changes(&self, line_number: usize) -> PrintSegment {
225 let color = if let Some(ref changes) = self.line_changes {
226 match changes.get(&(line_number as u32)) {
227 Some(&LineChange::Added) => self.colors.git_added.paint("+"),
228 Some(&LineChange::RemovedAbove) => self.colors.git_removed.paint("‾"),
229 Some(&LineChange::RemovedBelow) => self.colors.git_removed.paint("_"),
230 Some(&LineChange::Modified) => self.colors.git_modified.paint("~"),
231 _ => Style::default().paint(" "),
232 }
233 } else {
234 Style::default().paint(" ")
235 };
237 return PrintSegment {
238 text: color.to_string(),
239 size: 1,
240 };
241 }
243 /// Generates the vertical grid border.
244 fn gen_border(&self) -> PrintSegment {
245 return PrintSegment {
246 text: self.colors.grid.paint("│ ").to_string(),
247 size: 2,
248 };
249 }
251 fn print_horizontal_line(&mut self, grid_char: char) -> Result<()> {
252 if self.panel_width == 0 {
253 writeln!(
254 self.handle,
255 "{}",
256 self.colors.grid.paint("─".repeat(self.config.term_width))
257 )?;
258 } else {
259 let hline = "─".repeat(self.config.term_width - (self.panel_width + 1));
260 let hline = format!("{}{}{}", "─".repeat(self.panel_width), grid_char, hline);
261 writeln!(self.handle, "{}", self.colors.grid.paint(hline))?;
262 }
264 Ok(())
265 }