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