Skip to content

Commit

Permalink
Use ansi_colours package for better true-colour approximation
Browse files Browse the repository at this point in the history
  • Loading branch information
mina86 committed Sep 21, 2018
1 parent 96b24d8 commit d7e03f1
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 44 deletions.
10 changes: 10 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ exclude = [
[dependencies]
atty = "0.2.2"
ansi_term = "0.11"
ansi_colours = "^1.0"
console = "0.6"
directories = "1.0"
lazy_static = "1.0"
Expand Down
47 changes: 3 additions & 44 deletions src/terminal.rs
Original file line number Diff line number Diff line change
@@ -1,32 +1,15 @@
extern crate ansi_colours;

use ansi_term::Colour::{Fixed, RGB};
use ansi_term::{self, Style};

use syntect::highlighting::{self, FontStyle};

/// Approximate a 24 bit color value by a 8 bit ANSI code
fn rgb2ansi(r: u8, g: u8, b: u8) -> u8 {
const BLACK: u8 = 16;
const WHITE: u8 = 231;

if r == g && g == b {
if r < 8 {
BLACK
} else if r > 248 {
WHITE
} else {
((r - 8) as u16 * 24 / 247) as u8 + 232
}
} else {
36 * (r / 51) + 6 * (g / 51) + (b / 51) + 16
}
}

pub fn to_ansi_color(color: highlighting::Color, true_color: bool) -> ansi_term::Colour {
if true_color {
RGB(color.r, color.g, color.b)
} else {
let ansi_code = rgb2ansi(color.r, color.g, color.b);
Fixed(ansi_code)
Fixed(ansi_colours::ansi256_from_rgb((color.r, color.g, color.b)))
}
}

Expand Down Expand Up @@ -54,27 +37,3 @@ pub fn as_terminal_escaped(

style.paint(text).to_string()
}

#[test]
fn test_rgb2ansi_black_white() {
assert_eq!(16, rgb2ansi(0x00, 0x00, 0x00));
assert_eq!(231, rgb2ansi(0xff, 0xff, 0xff));
}

#[test]
fn test_rgb2ansi_gray() {
assert_eq!(241, rgb2ansi(0x6c, 0x6c, 0x6c));
assert_eq!(233, rgb2ansi(0x1c, 0x1c, 0x1c));
}

#[test]
fn test_rgb2ansi_color() {
assert_eq!(96, rgb2ansi(0x87, 0x5f, 0x87));
assert_eq!(141, rgb2ansi(0xaf, 0x87, 0xff));
assert_eq!(193, rgb2ansi(0xd7, 0xff, 0xaf));
}

#[test]
fn test_rgb2ansi_approx() {
assert_eq!(231, rgb2ansi(0xfe, 0xfe, 0xfe));
}

0 comments on commit d7e03f1

Please sign in to comment.