on 47a3721 help sign in
bat/src/terminal.rs
50 lines 1.6 kB history raw
1use ansi_term::Colour::{Fixed, RGB};
2use ansi_term::{self, Style};
4use syntect::highlighting::{self, FontStyle};
6pub fn to_ansi_color(color: highlighting::Color, true_color: bool) -> ansi_term::Colour {
7 if color.a == 0 {
8 // Themes can specify one of the user-configurable terminal colors by
9 // encoding them as #RRGGBBAA with AA set to 00 (transparent) and RR set
10 // to the color palette number. The built-in themes ansi-light,
11 // ansi-dark, and base16 use this.
12 Fixed(color.r)
13 } else if true_color {
14 RGB(color.r, color.g, color.b)
15 } else {
16 Fixed(ansi_colours::ansi256_from_rgb((color.r, color.g, color.b)))
17 }
20pub fn as_terminal_escaped(
21 style: highlighting::Style,
22 text: &str,
23 true_color: bool,
24 colored: bool,
25 italics: bool,
26 background_color: Option<highlighting::Color>,
27) -> String {
28 if text.is_empty() {
29 return text.to_string();
30 }
32 let mut style = if !colored {
33 Style::default()
34 } else {
35 let mut color = Style::from(to_ansi_color(style.foreground, true_color));
36 if style.font_style.contains(FontStyle::BOLD) {
37 color = color.bold();
38 }
39 if style.font_style.contains(FontStyle::UNDERLINE) {
40 color = color.underline();
41 }
42 if italics && style.font_style.contains(FontStyle::ITALIC) {
43 color = color.italic();
44 }
45 color
46 };
48 style.background = background_color.map(|c| to_ansi_color(c, true_color));
49 style.paint(text).to_string()