on fcecd97 help sign in
bat/src/terminal.rs
85 lines 2.3 kB history raw
1use std::fmt::Write;
3use ansi_term::Colour::{Fixed, RGB};
4use ansi_term::Style;
5use syntect::highlighting::{self, FontStyle};
7/// Approximate a 24 bit color value by a 8 bit ANSI code
8fn rgb2ansi(r: u8, g: u8, b: u8) -> u8 {
9 const BLACK: u8 = 16;
10 const WHITE: u8 = 231;
12 if r == g && g == b {
13 if r < 8 {
14 BLACK
15 } else if r > 248 {
16 WHITE
17 } else {
18 let fr = f32::from(r);
19 (((fr - 8.) / 247.) * 24.) as u8 + 232
20 }
21 } else {
22 let fr = f32::from(r);
23 let fg = f32::from(g);
24 let fb = f32::from(b);
25 16 + (36 * (fr / 255. * 5.) as u8) + (6 * (fg / 255. * 5.) as u8) + (fb / 255. * 5.) as u8
26 }
29pub fn as_terminal_escaped(
30 v: &[(highlighting::Style, &str)],
31 true_color: bool,
32 colored: bool,
33) -> String {
34 let mut s: String = String::new();
35 for &(ref style, text) in v.iter() {
36 let style = if !colored {
37 Style::default()
38 } else {
39 let color = if true_color {
40 RGB(style.foreground.r, style.foreground.g, style.foreground.b)
41 } else {
42 let ansi = rgb2ansi(style.foreground.r, style.foreground.g, style.foreground.b);
43 Fixed(ansi)
44 };
46 if style.font_style.contains(FontStyle::BOLD) {
47 color.bold()
48 } else if style.font_style.contains(FontStyle::UNDERLINE) {
49 color.underline()
50 } else if style.font_style.contains(FontStyle::ITALIC) {
51 color.italic()
52 } else {
53 color.normal()
54 }
55 };
57 write!(s, "{}", style.paint(text)).unwrap();
58 }
60 s
63#[test]
64fn test_rgb2ansi_black_white() {
65 assert_eq!(16, rgb2ansi(0x00, 0x00, 0x00));
66 assert_eq!(231, rgb2ansi(0xff, 0xff, 0xff));
69#[test]
70fn test_rgb2ansi_gray() {
71 assert_eq!(241, rgb2ansi(0x6c, 0x6c, 0x6c));
72 assert_eq!(233, rgb2ansi(0x1c, 0x1c, 0x1c));
75#[test]
76fn test_rgb2ansi_color() {
77 assert_eq!(96, rgb2ansi(0x87, 0x5f, 0x87));
78 assert_eq!(141, rgb2ansi(0xaf, 0x87, 0xff));
79 assert_eq!(193, rgb2ansi(0xd7, 0xff, 0xaf));
82#[test]
83fn test_rgb2ansi_approx() {
84 assert_eq!(231, rgb2ansi(0xfe, 0xfe, 0xfe));