on 2eee685 help sign in
bat/src/printer.rs
236 lines 7.6 kB history raw
1use app::Config;
2use decorations::{Decoration, GridBorderDecoration, LineChangesDecoration, LineNumberDecoration};
3use diff::LineChanges;
4use errors::*;
5use std::boxed::Box;
6use std::io::Write;
7use std::vec::Vec;
8use style::OutputWrap;
9use syntect::highlighting;
10use terminal::as_terminal_escaped;
11use Colors;
13pub struct Printer<'a> {
14 handle: &'a mut Write,
15 colors: Colors,
16 config: &'a Config<'a>,
17 decorations: Vec<Box<Decoration>>,
18 panel_width: usize,
19 pub line_changes: Option<LineChanges>,
22impl<'a> Printer<'a> {
23 pub fn new(handle: &'a mut Write, config: &'a Config) -> Self {
24 let colors = if config.colored_output {
25 Colors::colored()
26 } else {
27 Colors::plain()
28 };
30 // Create decorations.
31 let mut decorations: Vec<Box<Decoration>> = Vec::new();
33 if config.output_components.numbers() {
34 decorations.push(Box::new(LineNumberDecoration::new(&colors)));
35 }
37 if config.output_components.changes() {
38 decorations.push(Box::new(LineChangesDecoration::new(&colors)));
39 }
41 let mut panel_width: usize =
42 decorations.len() + decorations.iter().fold(0, |a, x| a + x.width());
44 // The grid border decoration isn't added until after the panel_width calculation, since the
45 // print_horizontal_line, print_header, and print_footer functions all assume the panel
46 // width is without the grid border.
47 if config.output_components.grid() && decorations.len() > 0 {
48 decorations.push(Box::new(GridBorderDecoration::new(&colors)));
49 }
51 // Disable the panel if the terminal is too small (i.e. can't fit 5 characters with the
52 // panel showing).
53 if config.term_width
54 < (decorations.len() + decorations.iter().fold(0, |a, x| a + x.width())) + 5
55 {
56 decorations.clear();
57 panel_width = 0;
58 }
60 // Create printer.
61 Printer {
62 panel_width,
63 handle,
64 colors,
65 config,
66 decorations,
67 line_changes: None,
68 }
69 }
71 pub fn print_header(&mut self, filename: Option<&str>) -> Result<()> {
72 if !self.config.output_components.header() {
73 return Ok(());
74 }
76 if self.config.output_components.grid() {
77 self.print_horizontal_line('┬')?;
79 write!(
80 self.handle,
81 "{}{} ",
82 " ".repeat(self.panel_width),
83 self.colors
84 .grid
85 .paint(if self.panel_width > 0 { "│" } else { "" }),
86 )?;
87 }
89 writeln!(
90 self.handle,
91 "{}{}",
92 filename.map_or("", |_| "File: "),
93 self.colors.filename.paint(filename.unwrap_or("STDIN"))
94 )?;
96 if self.config.output_components.grid() {
97 self.print_horizontal_line('┼')?;
98 }
100 Ok(())
101 }
103 pub fn print_footer(&mut self) -> Result<()> {
104 if self.config.output_components.grid() {
105 self.print_horizontal_line('┴')
106 } else {
107 Ok(())
108 }
109 }
111 pub fn print_line(
112 &mut self,
113 line_number: usize,
114 regions: &[(highlighting::Style, &str)],
115 ) -> Result<()> {
116 let mut cursor: usize = 0;
117 let mut cursor_max: usize = self.config.term_width;
118 let mut panel_wrap: Option<String> = None;
120 // Line decorations.
121 if self.panel_width > 0 {
122 let decorations = self
123 .decorations
124 .iter()
125 .map(|ref d| d.generate(line_number, false, self))
126 .collect::<Vec<_>>();
128 for deco in decorations {
129 write!(self.handle, "{} ", deco.text)?;
130 cursor_max -= deco.width + 1;
131 }
132 }
134 // Line contents.
135 if self.config.output_wrap == OutputWrap::None {
136 let true_color = self.config.true_color;
137 let colored_output = self.config.colored_output;
139 write!(
140 self.handle,
141 "{}",
142 regions
143 .iter()
144 .map(|&(style, text)| as_terminal_escaped(
145 style,
146 text,
147 true_color,
148 colored_output,
149 ))
150 .collect::<Vec<_>>()
151 .join("")
152 )?;
153 } else {
154 for &(style, text) in regions.iter() {
155 let text = text.trim_right_matches(|c| c == '\r' || c == '\n');
156 let mut chars = text.chars();
157 let mut remaining = text.chars().count();
159 while remaining > 0 {
160 let available = cursor_max - cursor;
162 // It fits.
163 if remaining <= available {
164 let text = chars.by_ref().take(remaining).collect::<String>();
165 cursor += remaining;
167 write!(
168 self.handle,
169 "{}",
170 as_terminal_escaped(
171 style,
172 &*text,
173 self.config.true_color,
174 self.config.colored_output,
175 )
176 )?;
177 break;
178 }
180 // Generate wrap padding if not already generated.
181 if panel_wrap.is_none() {
182 panel_wrap = if self.panel_width > 0 {
183 Some(format!(
184 "{} ",
185 self.decorations
186 .iter()
187 .map(|ref d| d.generate(line_number, true, self).text)
188 .collect::<Vec<String>>()
189 .join(" ")
190 ))
191 } else {
192 Some("".to_string())
193 }
194 }
196 // It wraps.
197 let text = chars.by_ref().take(available).collect::<String>();
198 cursor = 0;
199 remaining -= available;
201 write!(
202 self.handle,
203 "{}\n{}",
204 as_terminal_escaped(
205 style,
206 &*text,
207 self.config.true_color,
208 self.config.colored_output,
209 ),
210 panel_wrap.clone().unwrap()
211 )?;
212 }
213 }
215 write!(self.handle, "\n")?;
216 }
218 Ok(())
219 }
221 fn print_horizontal_line(&mut self, grid_char: char) -> Result<()> {
222 if self.panel_width == 0 {
223 writeln!(
224 self.handle,
225 "{}",
226 self.colors.grid.paint("─".repeat(self.config.term_width))
227 )?;
228 } else {
229 let hline = "─".repeat(self.config.term_width - (self.panel_width + 1));
230 let hline = format!("{}{}{}", "─".repeat(self.panel_width), grid_char, hline);
231 writeln!(self.handle, "{}", self.colors.grid.paint(hline))?;
232 }
234 Ok(())
235 }