4use ansi_term::Colour::{Fixed, Green, Red, Yellow};
7use console::AnsiCodeIterator;
9use syntect::easy::HighlightLines;
10use syntect::highlighting::Color;
11use syntect::highlighting::Theme;
12use syntect::parsing::SyntaxSet;
14use content_inspector::ContentType;
16use encoding::all::{UTF_16BE, UTF_16LE};
17use encoding::{DecoderTrap, Encoding};
19use crate::app::Config;
20use crate::assets::HighlightingAssets;
21use crate::decorations::{
22 Decoration, GridBorderDecoration, LineChangesDecoration, LineNumberDecoration,
24use crate::diff::get_git_diff;
25use crate::diff::LineChanges;
27use crate::inputfile::{InputFile, InputFileReader};
28use crate::preprocessor::{expand_tabs, replace_nonprintable};
29use crate::style::OutputWrap;
30use crate::terminal::{as_terminal_escaped, to_ansi_color};
33 fn print_header(&mut self, handle: &mut Write, file: InputFile) -> Result<()>;
34 fn print_footer(&mut self, handle: &mut Write) -> Result<()>;
44pub struct SimplePrinter;
47 pub fn new() -> Self {
52impl Printer for SimplePrinter {
53 fn print_header(&mut self, _handle: &mut Write, _file: InputFile) -> Result<()> {
57 fn print_footer(&mut self, _handle: &mut Write) -> Result<()> {
69 handle.write_all(line_buffer)?;
75pub struct InteractivePrinter<'a> {
77 config: &'a Config<'a>,
78 decorations: Vec<Box<dyn Decoration>>,
80 ansi_prefix_sgr: String,
81 content_type: ContentType,
82 pub line_changes: Option<LineChanges>,
83 highlighter: Option<HighlightLines<'a>>,
84 syntax_set: &'a SyntaxSet,
85 background_color_highlight: Option<Color>,
88impl<'a> InteractivePrinter<'a> {
91 assets: &'a HighlightingAssets,
93 reader: &mut InputFileReader,
95 let theme = assets.get_theme(&config.theme);
97 let background_color_highlight = theme.settings.line_highlight;
99 let colors = if config.colored_output {
100 Colors::colored(theme, config.true_color)
105 // Create decorations.
106 let mut decorations: Vec<Box<dyn Decoration>> = Vec::new();
108 if config.output_components.numbers() {
109 decorations.push(Box::new(LineNumberDecoration::new(&colors)));
112 if config.output_components.changes() {
113 decorations.push(Box::new(LineChangesDecoration::new(&colors)));
116 let mut panel_width: usize =
117 decorations.len() + decorations.iter().fold(0, |a, x| a + x.width());
119 // The grid border decoration isn't added until after the panel_width calculation, since the
120 // print_horizontal_line, print_header, and print_footer functions all assume the panel
121 // width is without the grid border.
122 if config.output_components.grid() && !decorations.is_empty() {
123 decorations.push(Box::new(GridBorderDecoration::new(&colors)));
126 // Disable the panel if the terminal is too small (i.e. can't fit 5 characters with the
129 < (decorations.len() + decorations.iter().fold(0, |a, x| a + x.width())) + 5
135 let mut line_changes = None;
137 let highlighter = if reader.content_type.is_binary() {
140 // Get the Git modifications
141 line_changes = if config.output_components.changes() {
143 InputFile::Ordinary(filename) => get_git_diff(filename),
150 // Determine the type of syntax for highlighting
151 let syntax = assets.get_syntax(config.language, file, reader, &config.syntax_mapping);
152 Some(HighlightLines::new(syntax, theme))
160 content_type: reader.content_type,
161 ansi_prefix_sgr: String::new(),
164 syntax_set: &assets.syntax_set,
165 background_color_highlight,
169 fn print_horizontal_line(&mut self, handle: &mut Write, grid_char: char) -> Result<()> {
170 if self.panel_width == 0 {
174 self.colors.grid.paint("─".repeat(self.config.term_width))
177 let hline = "─".repeat(self.config.term_width - (self.panel_width + 1));
178 let hline = format!("{}{}{}", "─".repeat(self.panel_width), grid_char, hline);
179 writeln!(handle, "{}", self.colors.grid.paint(hline))?;
185 fn preprocess(&self, text: &str, cursor: &mut usize) -> String {
186 if self.config.tab_width > 0 {
187 expand_tabs(text, self.config.tab_width, cursor)
194impl<'a> Printer for InteractivePrinter<'a> {
195 fn print_header(&mut self, handle: &mut Write, file: InputFile) -> Result<()> {
196 if !self.config.output_components.header() {
200 if self.config.output_components.grid() {
201 self.print_horizontal_line(handle, '┬')?;
206 " ".repeat(self.panel_width),
209 .paint(if self.panel_width > 0 { "│ " } else { "" }),
212 write!(handle, "{}", " ".repeat(self.panel_width))?;
215 let (prefix, name) = match file {
216 InputFile::Ordinary(filename) => ("File: ", filename),
220 let mode = match self.content_type {
221 ContentType::BINARY => " <BINARY>",
222 ContentType::UTF_16LE => " <UTF-16LE>",
223 ContentType::UTF_16BE => " <UTF-16BE>",
231 self.colors.filename.paint(name),
235 if self.config.output_components.grid() {
236 if self.content_type.is_text() {
237 self.print_horizontal_line(handle, '┼')?;
239 self.print_horizontal_line(handle, '┴')?;
246 fn print_footer(&mut self, handle: &mut Write) -> Result<()> {
247 if self.config.output_components.grid() && self.content_type.is_text() {
248 self.print_horizontal_line(handle, '┴')
261 let mut line = match self.content_type {
262 ContentType::BINARY => {
265 ContentType::UTF_16LE => UTF_16LE
266 .decode(&line_buffer, DecoderTrap::Replace)
267 .map_err(|_| "Invalid UTF-16LE")?,
268 ContentType::UTF_16BE => UTF_16BE
269 .decode(&line_buffer, DecoderTrap::Replace)
270 .map_err(|_| "Invalid UTF-16BE")?,
271 _ => String::from_utf8_lossy(&line_buffer).to_string(),
274 if self.config.show_nonprintable {
275 line = replace_nonprintable(&line, self.config.tab_width);
279 let highlighter = match self.highlighter {
280 Some(ref mut highlighter) => highlighter,
285 highlighter.highlight(line.as_ref(), self.syntax_set)
292 let mut cursor: usize = 0;
293 let mut cursor_max: usize = self.config.term_width;
294 let mut cursor_total: usize = 0;
295 let mut panel_wrap: Option<String> = None;
298 let highlight_this_line = self
302 .any(|&l| l == line_number);
304 let background_color = self
305 .background_color_highlight
306 .filter(|_| highlight_this_line);
309 if self.panel_width > 0 {
310 let decorations = self
313 .map(|ref d| d.generate(line_number, false, self))
314 .collect::<Vec<_>>();
316 for deco in decorations {
317 write!(handle, "{} ", deco.text)?;
318 cursor_max -= deco.width + 1;
323 if self.config.output_wrap == OutputWrap::None {
324 let true_color = self.config.true_color;
325 let colored_output = self.config.colored_output;
326 let italics = self.config.use_italic_text;
328 for &(style, region) in regions.iter() {
329 let text = &*self.preprocess(region, &mut cursor_total);
330 let text_trimmed = text.trim_end_matches(|c| c == '\r' || c == '\n');
344 if text.len() != text_trimmed.len() {
345 if let Some(background_color) = background_color {
346 let mut ansi_style = Style::default();
347 ansi_style.background = Some(to_ansi_color(background_color, true_color));
348 let width = if cursor_total <= cursor_max {
349 cursor_max - cursor_total + 1
353 write!(handle, "{}", ansi_style.paint(" ".repeat(width)))?;
355 write!(handle, "{}", &text[text_trimmed.len()..])?;
359 if line.bytes().next_back() != Some(b'\n') {
363 for &(style, region) in regions.iter() {
364 let ansi_iterator = AnsiCodeIterator::new(region);
365 let mut ansi_prefix: String = String::new();
366 for chunk in ansi_iterator {
368 // ANSI escape passthrough.
370 let is_ansi_csi = text.starts_with("\x1B[");
372 if is_ansi_csi && text.ends_with('m') {
373 // It's an ANSI SGR sequence.
374 // We should be mostly safe to just append these together.
375 ansi_prefix.push_str(text);
376 if text == "\x1B[0m" {
377 self.ansi_prefix_sgr = "\x1B[0m".to_owned();
379 self.ansi_prefix_sgr.push_str(text);
381 } else if is_ansi_csi {
382 // It's a regular CSI sequence.
383 // We should be mostly safe to just append these together.
384 ansi_prefix.push_str(text);
386 // It's probably a VT100 code.
387 // Passing it through is the safest bet.
388 write!(handle, "{}", text)?;
394 let text = self.preprocess(
395 text.trim_end_matches(|c| c == '\r' || c == '\n'),
399 let mut chars = text.chars();
400 let mut remaining = text.chars().count();
402 while remaining > 0 {
403 let available = cursor_max - cursor;
406 if remaining <= available {
407 let text = chars.by_ref().take(remaining).collect::<String>();
417 self.ansi_prefix_sgr, ansi_prefix, text
419 self.config.true_color,
420 self.config.colored_output,
421 self.config.use_italic_text,
428 // Generate wrap padding if not already generated.
429 if panel_wrap.is_none() {
430 panel_wrap = if self.panel_width > 0 {
436 .generate(line_number, true, self)
438 .collect::<Vec<String>>()
447 let text = chars.by_ref().take(available).collect::<String>();
449 remaining -= available;
458 self.ansi_prefix_sgr, ansi_prefix, text
460 self.config.true_color,
461 self.config.colored_output,
462 self.config.use_italic_text,
465 panel_wrap.clone().unwrap()
469 // Clear the ANSI prefix buffer.
476 if let Some(background_color) = background_color {
477 let mut ansi_style = Style::default();
478 ansi_style.background =
479 Some(to_ansi_color(background_color, self.config.true_color));
484 ansi_style.paint(" ".repeat(cursor_max - cursor))
494const DEFAULT_GUTTER_COLOR: u8 = 238;
500 pub git_added: Style,
501 pub git_removed: Style,
502 pub git_modified: Style,
503 pub line_number: Style,
511 fn colored(theme: &Theme, true_color: bool) -> Self {
512 let gutter_color = theme
515 .map(|c| to_ansi_color(c, true_color))
516 .unwrap_or(Fixed(DEFAULT_GUTTER_COLOR));
519 grid: gutter_color.normal(),
520 filename: Style::new().bold(),
521 git_added: Green.normal(),
522 git_removed: Red.normal(),
523 git_modified: Yellow.normal(),
524 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