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_tabs, replace_nonprintable};
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_tabs(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 mut 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 if self.config.show_nonprintable {
268 line = replace_nonprintable(&mut line, self.config.tab_width);
272 let highlighter = match self.highlighter {
273 Some(ref mut highlighter) => highlighter,
278 highlighter.highlight(line.as_ref(), self.syntax_set)
285 let mut cursor: usize = 0;
286 let mut cursor_max: usize = self.config.term_width;
287 let mut cursor_total: usize = 0;
288 let mut panel_wrap: Option<String> = None;
291 if self.panel_width > 0 {
292 let decorations = self
295 .map(|ref d| d.generate(line_number, false, self))
296 .collect::<Vec<_>>();
298 for deco in decorations {
299 write!(handle, "{} ", deco.text)?;
300 cursor_max -= deco.width + 1;
305 if self.config.output_wrap == OutputWrap::None {
306 let true_color = self.config.true_color;
307 let colored_output = self.config.colored_output;
308 let italics = self.config.use_italic_text;
310 for &(style, region) in regions.iter() {
311 let text = &*self.preprocess(region, &mut cursor_total);
315 as_terminal_escaped(style, &*text, true_color, colored_output, italics,)
319 if line.bytes().next_back() != Some(b'\n') {
320 write!(handle, "\n")?;
323 for &(style, region) in regions.iter() {
324 let mut ansi_iterator = AnsiCodeIterator::new(region);
325 let mut ansi_prefix: String = String::new();
326 for chunk in ansi_iterator {
328 // ANSI escape passthrough.
330 if text.chars().last().map_or(false, |c| c == 'm') {
331 ansi_prefix.push_str(text);
332 if text == "\x1B[0m" {
333 self.ansi_prefix_sgr = "\x1B[0m".to_owned();
335 self.ansi_prefix_sgr.push_str(text);
338 ansi_prefix.push_str(text);
344 let text = self.preprocess(
345 text.trim_right_matches(|c| c == '\r' || c == '\n'),
349 let mut chars = text.chars();
350 let mut remaining = text.chars().count();
352 while remaining > 0 {
353 let available = cursor_max - cursor;
356 if remaining <= available {
357 let text = chars.by_ref().take(remaining).collect::<String>();
367 self.ansi_prefix_sgr, ansi_prefix, text
369 self.config.true_color,
370 self.config.colored_output,
371 self.config.use_italic_text
377 // Generate wrap padding if not already generated.
378 if panel_wrap.is_none() {
379 panel_wrap = if self.panel_width > 0 {
385 .generate(line_number, true, self)
387 .collect::<Vec<String>>()
396 let text = chars.by_ref().take(available).collect::<String>();
398 remaining -= available;
407 self.ansi_prefix_sgr, ansi_prefix, text
409 self.config.true_color,
410 self.config.colored_output,
411 self.config.use_italic_text
413 panel_wrap.clone().unwrap()
417 // Clear the ANSI prefix buffer.
424 write!(handle, "\n")?;
431const DEFAULT_GUTTER_COLOR: u8 = 238;
437 pub git_added: Style,
438 pub git_removed: Style,
439 pub git_modified: Style,
440 pub line_number: Style,
448 fn colored(theme: &Theme, true_color: bool) -> Self {
449 let gutter_color = theme
452 .map(|c| to_ansi_color(c, true_color))
453 .unwrap_or(Fixed(DEFAULT_GUTTER_COLOR));
456 grid: gutter_color.normal(),
457 filename: Style::new().bold(),
458 git_added: Green.normal(),
459 git_removed: Red.normal(),
460 git_modified: Yellow.normal(),
461 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