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