4use ansi_term::Colour::{Fixed, Green, Red, Yellow};
7use console::AnsiCodeIterator;
9use syntect::easy::HighlightLines;
10use syntect::highlighting::Theme;
11use syntect::parsing::SyntaxSet;
13use content_inspector::ContentType;
15use encoding::all::{UTF_16BE, UTF_16LE};
16use encoding::{DecoderTrap, Encoding};
19use assets::HighlightingAssets;
20use decorations::{Decoration, GridBorderDecoration, LineChangesDecoration, LineNumberDecoration};
21use diff::get_git_diff;
24use inputfile::{InputFile, InputFileReader};
25use preprocessor::expand;
27use terminal::{as_terminal_escaped, to_ansi_color};
30 fn print_header(&mut self, handle: &mut Write, file: InputFile) -> Result<()>;
31 fn print_footer(&mut self, handle: &mut Write) -> Result<()>;
41pub struct SimplePrinter;
44 pub fn new() -> Self {
49impl Printer for SimplePrinter {
50 fn print_header(&mut self, _handle: &mut Write, _file: InputFile) -> Result<()> {
54 fn print_footer(&mut self, _handle: &mut Write) -> Result<()> {
66 handle.write(line_buffer)?;
72pub struct InteractivePrinter<'a> {
74 config: &'a Config<'a>,
75 decorations: Vec<Box<dyn Decoration>>,
77 ansi_prefix_sgr: String,
78 content_type: ContentType,
79 pub line_changes: Option<LineChanges>,
80 highlighter: Option<HighlightLines<'a>>,
81 syntax_set: &'a SyntaxSet,
84impl<'a> InteractivePrinter<'a> {
87 assets: &'a HighlightingAssets,
89 reader: &mut InputFileReader,
91 let theme = assets.get_theme(&config.theme);
93 let colors = if config.colored_output {
94 Colors::colored(theme, config.true_color)
99 // Create decorations.
100 let mut decorations: Vec<Box<dyn Decoration>> = Vec::new();
102 if config.output_components.numbers() {
103 decorations.push(Box::new(LineNumberDecoration::new(&colors)));
106 if config.output_components.changes() {
107 decorations.push(Box::new(LineChangesDecoration::new(&colors)));
110 let mut panel_width: usize =
111 decorations.len() + decorations.iter().fold(0, |a, x| a + x.width());
113 // The grid border decoration isn't added until after the panel_width calculation, since the
114 // print_horizontal_line, print_header, and print_footer functions all assume the panel
115 // width is without the grid border.
116 if config.output_components.grid() && !decorations.is_empty() {
117 decorations.push(Box::new(GridBorderDecoration::new(&colors)));
120 // Disable the panel if the terminal is too small (i.e. can't fit 5 characters with the
123 < (decorations.len() + decorations.iter().fold(0, |a, x| a + x.width())) + 5
129 let mut line_changes = None;
131 let highlighter = if reader.content_type.is_binary() {
134 // Get the Git modifications
135 line_changes = if config.output_components.changes() {
137 InputFile::Ordinary(filename) => get_git_diff(filename),
144 // Determine the type of syntax for highlighting
145 let syntax = assets.get_syntax(config.language, file, reader, &config.syntax_mapping);
146 Some(HighlightLines::new(syntax, theme))
154 content_type: reader.content_type,
155 ansi_prefix_sgr: String::new(),
158 syntax_set: &assets.syntax_set,
162 fn print_horizontal_line(&mut self, handle: &mut Write, grid_char: char) -> Result<()> {
163 if self.panel_width == 0 {
167 self.colors.grid.paint("─".repeat(self.config.term_width))
170 let hline = "─".repeat(self.config.term_width - (self.panel_width + 1));
171 let hline = format!("{}{}{}", "─".repeat(self.panel_width), grid_char, hline);
172 writeln!(handle, "{}", self.colors.grid.paint(hline))?;
178 fn preprocess(&self, text: &str, cursor: &mut usize) -> String {
179 if self.config.tab_width > 0 {
180 expand(text, self.config.tab_width, cursor)
187impl<'a> Printer for InteractivePrinter<'a> {
188 fn print_header(&mut self, handle: &mut Write, file: InputFile) -> Result<()> {
189 if !self.config.output_components.header() {
193 if self.config.output_components.grid() {
194 self.print_horizontal_line(handle, '┬')?;
199 " ".repeat(self.panel_width),
202 .paint(if self.panel_width > 0 { "│ " } else { "" }),
205 write!(handle, "{}", " ".repeat(self.panel_width))?;
208 let (prefix, name) = match file {
209 InputFile::Ordinary(filename) => ("File: ", filename),
213 let mode = match self.content_type {
214 ContentType::BINARY => " <BINARY>",
215 ContentType::UTF_16LE => " <UTF-16LE>",
216 ContentType::UTF_16BE => " <UTF-16BE>",
224 self.colors.filename.paint(name),
228 if self.config.output_components.grid() {
229 if self.content_type.is_text() {
230 self.print_horizontal_line(handle, '┼')?;
232 self.print_horizontal_line(handle, '┴')?;
239 fn print_footer(&mut self, handle: &mut Write) -> Result<()> {
240 if self.config.output_components.grid() && self.content_type.is_text() {
241 self.print_horizontal_line(handle, '┴')
254 let line = match self.content_type {
255 ContentType::BINARY => {
258 ContentType::UTF_16LE => UTF_16LE
259 .decode(&line_buffer, DecoderTrap::Strict)
260 .unwrap_or("Invalid UTF-16LE".into()),
261 ContentType::UTF_16BE => UTF_16BE
262 .decode(&line_buffer, DecoderTrap::Strict)
263 .unwrap_or("Invalid UTF-16BE".into()),
264 _ => String::from_utf8_lossy(&line_buffer).to_string(),
267 let highlighter = match self.highlighter {
268 Some(ref mut highlighter) => highlighter,
273 highlighter.highlight(line.as_ref(), self.syntax_set)
280 let mut cursor: usize = 0;
281 let mut cursor_max: usize = self.config.term_width;
282 let mut cursor_total: usize = 0;
283 let mut panel_wrap: Option<String> = None;
286 if self.panel_width > 0 {
287 let decorations = self
290 .map(|ref d| d.generate(line_number, false, self))
291 .collect::<Vec<_>>();
293 for deco in decorations {
294 write!(handle, "{} ", deco.text)?;
295 cursor_max -= deco.width + 1;
300 if self.config.output_wrap == OutputWrap::None {
301 let true_color = self.config.true_color;
302 let colored_output = self.config.colored_output;
304 for &(style, region) in regions.iter() {
305 let text = &*self.preprocess(region, &mut cursor_total);
309 as_terminal_escaped(style, &*text, true_color, colored_output,)
313 if line.bytes().next_back() != Some(b'\n') {
314 write!(handle, "\n")?;
317 for &(style, region) in regions.iter() {
318 let mut ansi_iterator = AnsiCodeIterator::new(region);
319 let mut ansi_prefix: String = String::new();
320 for chunk in ansi_iterator {
322 // ANSI escape passthrough.
324 if text.chars().last().map_or(false, |c| c == 'm') {
325 ansi_prefix.push_str(text);
326 if text == "\x1B[0m" {
327 self.ansi_prefix_sgr = "\x1B[0m".to_owned();
329 self.ansi_prefix_sgr.push_str(text);
332 ansi_prefix.push_str(text);
338 let text = self.preprocess(
339 text.trim_right_matches(|c| c == '\r' || c == '\n'),
343 let mut chars = text.chars();
344 let mut remaining = text.chars().count();
346 while remaining > 0 {
347 let available = cursor_max - cursor;
350 if remaining <= available {
351 let text = chars.by_ref().take(remaining).collect::<String>();
361 self.ansi_prefix_sgr, ansi_prefix, text
363 self.config.true_color,
364 self.config.colored_output,
370 // Generate wrap padding if not already generated.
371 if panel_wrap.is_none() {
372 panel_wrap = if self.panel_width > 0 {
378 .generate(line_number, true, self)
380 .collect::<Vec<String>>()
389 let text = chars.by_ref().take(available).collect::<String>();
391 remaining -= available;
400 self.ansi_prefix_sgr, ansi_prefix, text
402 self.config.true_color,
403 self.config.colored_output,
405 panel_wrap.clone().unwrap()
409 // Clear the ANSI prefix buffer.
416 write!(handle, "\n")?;
423const DEFAULT_GUTTER_COLOR: u8 = 238;
429 pub git_added: Style,
430 pub git_removed: Style,
431 pub git_modified: Style,
432 pub line_number: Style,
440 fn colored(theme: &Theme, true_color: bool) -> Self {
441 let gutter_color = theme
444 .map(|c| to_ansi_color(c, true_color))
445 .unwrap_or(Fixed(DEFAULT_GUTTER_COLOR));
448 grid: gutter_color.normal(),
449 filename: Style::new().bold(),
450 git_added: Green.normal(),
451 git_removed: Red.normal(),
452 git_modified: Yellow.normal(),
453 line_number: gutter_color.normal(),
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list