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};
20use assets::HighlightingAssets;
21use decorations::{Decoration, GridBorderDecoration, LineChangesDecoration, LineNumberDecoration};
22use diff::get_git_diff;
25use inputfile::{InputFile, InputFileReader};
26use preprocessor::{expand_tabs, replace_nonprintable};
28use terminal::{as_terminal_escaped, to_ansi_color};
31 fn print_header(&mut self, handle: &mut Write, file: InputFile) -> Result<()>;
32 fn print_footer(&mut self, handle: &mut Write) -> Result<()>;
42pub struct SimplePrinter;
45 pub fn new() -> Self {
50impl Printer for SimplePrinter {
51 fn print_header(&mut self, _handle: &mut Write, _file: InputFile) -> Result<()> {
55 fn print_footer(&mut self, _handle: &mut Write) -> Result<()> {
67 handle.write(line_buffer)?;
73pub struct InteractivePrinter<'a> {
75 config: &'a Config<'a>,
76 decorations: Vec<Box<dyn Decoration>>,
78 ansi_prefix_sgr: String,
79 content_type: ContentType,
80 pub line_changes: Option<LineChanges>,
81 highlighter: Option<HighlightLines<'a>>,
82 syntax_set: &'a SyntaxSet,
83 background_color_highlight: Option<Color>,
86impl<'a> InteractivePrinter<'a> {
89 assets: &'a HighlightingAssets,
91 reader: &mut InputFileReader,
93 let theme = assets.get_theme(&config.theme);
95 let background_color_highlight = theme.settings.line_highlight;
97 let colors = if config.colored_output {
98 Colors::colored(theme, config.true_color)
103 // Create decorations.
104 let mut decorations: Vec<Box<dyn Decoration>> = Vec::new();
106 if config.output_components.numbers() {
107 decorations.push(Box::new(LineNumberDecoration::new(&colors)));
110 if config.output_components.changes() {
111 decorations.push(Box::new(LineChangesDecoration::new(&colors)));
114 let mut panel_width: usize =
115 decorations.len() + decorations.iter().fold(0, |a, x| a + x.width());
117 // The grid border decoration isn't added until after the panel_width calculation, since the
118 // print_horizontal_line, print_header, and print_footer functions all assume the panel
119 // width is without the grid border.
120 if config.output_components.grid() && !decorations.is_empty() {
121 decorations.push(Box::new(GridBorderDecoration::new(&colors)));
124 // Disable the panel if the terminal is too small (i.e. can't fit 5 characters with the
127 < (decorations.len() + decorations.iter().fold(0, |a, x| a + x.width())) + 5
133 let mut line_changes = None;
135 let highlighter = if reader.content_type.is_binary() {
138 // Get the Git modifications
139 line_changes = if config.output_components.changes() {
141 InputFile::Ordinary(filename) => get_git_diff(filename),
148 // Determine the type of syntax for highlighting
149 let syntax = assets.get_syntax(config.language, file, reader, &config.syntax_mapping);
150 Some(HighlightLines::new(syntax, theme))
158 content_type: reader.content_type,
159 ansi_prefix_sgr: String::new(),
162 syntax_set: &assets.syntax_set,
163 background_color_highlight,
167 fn print_horizontal_line(&mut self, handle: &mut Write, grid_char: char) -> Result<()> {
168 if self.panel_width == 0 {
172 self.colors.grid.paint("─".repeat(self.config.term_width))
175 let hline = "─".repeat(self.config.term_width - (self.panel_width + 1));
176 let hline = format!("{}{}{}", "─".repeat(self.panel_width), grid_char, hline);
177 writeln!(handle, "{}", self.colors.grid.paint(hline))?;
183 fn preprocess(&self, text: &str, cursor: &mut usize) -> String {
184 if self.config.tab_width > 0 {
185 expand_tabs(text, self.config.tab_width, cursor)
192impl<'a> Printer for InteractivePrinter<'a> {
193 fn print_header(&mut self, handle: &mut Write, file: InputFile) -> Result<()> {
194 if !self.config.output_components.header() {
198 if self.config.output_components.grid() {
199 self.print_horizontal_line(handle, '┬')?;
204 " ".repeat(self.panel_width),
207 .paint(if self.panel_width > 0 { "│ " } else { "" }),
210 write!(handle, "{}", " ".repeat(self.panel_width))?;
213 let (prefix, name) = match file {
214 InputFile::Ordinary(filename) => ("File: ", filename),
218 let mode = match self.content_type {
219 ContentType::BINARY => " <BINARY>",
220 ContentType::UTF_16LE => " <UTF-16LE>",
221 ContentType::UTF_16BE => " <UTF-16BE>",
229 self.colors.filename.paint(name),
233 if self.config.output_components.grid() {
234 if self.content_type.is_text() {
235 self.print_horizontal_line(handle, '┼')?;
237 self.print_horizontal_line(handle, '┴')?;
244 fn print_footer(&mut self, handle: &mut Write) -> Result<()> {
245 if self.config.output_components.grid() && self.content_type.is_text() {
246 self.print_horizontal_line(handle, '┴')
259 let mut line = match self.content_type {
260 ContentType::BINARY => {
263 ContentType::UTF_16LE => UTF_16LE
264 .decode(&line_buffer, DecoderTrap::Strict)
265 .unwrap_or("Invalid UTF-16LE".into()),
266 ContentType::UTF_16BE => UTF_16BE
267 .decode(&line_buffer, DecoderTrap::Strict)
268 .unwrap_or("Invalid UTF-16BE".into()),
269 _ => String::from_utf8_lossy(&line_buffer).to_string(),
272 if self.config.show_nonprintable {
273 line = replace_nonprintable(&mut line, self.config.tab_width);
277 let highlighter = match self.highlighter {
278 Some(ref mut highlighter) => highlighter,
283 highlighter.highlight(line.as_ref(), self.syntax_set)
290 let mut cursor: usize = 0;
291 let mut cursor_max: usize = self.config.term_width;
292 let mut cursor_total: usize = 0;
293 let mut panel_wrap: Option<String> = None;
296 let background_color = if self
300 .find(|&&l| l == line_number)
303 self.background_color_highlight
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');
343 write!(handle, "{}", &text[text_trimmed.len()..])?;
346 if line.bytes().next_back() != Some(b'\n') {
347 write!(handle, "\n")?;
350 for &(style, region) in regions.iter() {
351 let mut ansi_iterator = AnsiCodeIterator::new(region);
352 let mut ansi_prefix: String = String::new();
353 for chunk in ansi_iterator {
355 // ANSI escape passthrough.
357 if text.chars().last().map_or(false, |c| c == 'm') {
358 ansi_prefix.push_str(text);
359 if text == "\x1B[0m" {
360 self.ansi_prefix_sgr = "\x1B[0m".to_owned();
362 self.ansi_prefix_sgr.push_str(text);
365 ansi_prefix.push_str(text);
371 let text = self.preprocess(
372 text.trim_end_matches(|c| c == '\r' || c == '\n'),
376 let mut chars = text.chars();
377 let mut remaining = text.chars().count();
379 while remaining > 0 {
380 let available = cursor_max - cursor;
383 if remaining <= available {
384 let text = chars.by_ref().take(remaining).collect::<String>();
394 self.ansi_prefix_sgr, ansi_prefix, text
396 self.config.true_color,
397 self.config.colored_output,
398 self.config.use_italic_text,
405 // Generate wrap padding if not already generated.
406 if panel_wrap.is_none() {
407 panel_wrap = if self.panel_width > 0 {
413 .generate(line_number, true, self)
415 .collect::<Vec<String>>()
424 let text = chars.by_ref().take(available).collect::<String>();
426 remaining -= available;
435 self.ansi_prefix_sgr, ansi_prefix, text
437 self.config.true_color,
438 self.config.colored_output,
439 self.config.use_italic_text,
442 panel_wrap.clone().unwrap()
446 // Clear the ANSI prefix buffer.
453 write!(handle, "\n")?;
460const DEFAULT_GUTTER_COLOR: u8 = 238;
466 pub git_added: Style,
467 pub git_removed: Style,
468 pub git_modified: Style,
469 pub line_number: Style,
477 fn colored(theme: &Theme, true_color: bool) -> Self {
478 let gutter_color = theme
481 .map(|c| to_ansi_color(c, true_color))
482 .unwrap_or(Fixed(DEFAULT_GUTTER_COLOR));
485 grid: gutter_color.normal(),
486 filename: Style::new().bold(),
487 git_added: Green.normal(),
488 git_removed: Red.normal(),
489 git_modified: Yellow.normal(),
490 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