Skip to content

Commit 4507edd

Browse files
committed
256 colour support in ls_colors
This is more annoying than it should be because it has to work with Styles rather than with strings, which means parsing them, and parsing is always tricky business.
1 parent bad794a commit 4507edd

File tree

1 file changed

+34
-2
lines changed

1 file changed

+34
-2
lines changed

src/style/lsc.rs

Lines changed: 34 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
use std::ops::FnMut;
22

3-
use ansi_term::Style;
3+
use ansi_term::{Colour, Style};
44
use ansi_term::Colour::*;
55

66

@@ -25,11 +25,30 @@ pub struct Pair<'var> {
2525
pub value: &'var str,
2626
}
2727

28+
use std::iter::Peekable;
29+
fn parse_into_high_colour<'a, I>(iter: &mut Peekable<I>) -> Option<Colour>
30+
where I: Iterator<Item=&'a str> {
31+
match iter.peek() {
32+
Some(&"5") => {
33+
let _5 = iter.next();
34+
if let Some(byte) = iter.next() {
35+
if let Ok(num) = byte.parse() {
36+
return Some(Fixed(num));
37+
}
38+
}
39+
}
40+
_ => {},
41+
}
42+
43+
None
44+
}
45+
2846
impl<'var> Pair<'var> {
2947
pub fn to_style(&self) -> Style {
3048
let mut style = Style::default();
49+
let mut iter = self.value.split(";").peekable();
3150

32-
for num in self.value.split(";") {
51+
while let Some(num) = iter.next() {
3352
match num {
3453

3554
// Bold and italic
@@ -45,6 +64,7 @@ impl<'var> Pair<'var> {
4564
"35" => style = style.fg(Purple),
4665
"36" => style = style.fg(Cyan),
4766
"37" => style = style.fg(White),
67+
"38" => if let Some(c) = parse_into_high_colour(&mut iter) { style = style.fg(c) },
4868

4969
// Background colours
5070
"40" => style = style.on(Black),
@@ -55,6 +75,8 @@ impl<'var> Pair<'var> {
5575
"45" => style = style.on(Purple),
5676
"46" => style = style.on(Cyan),
5777
"47" => style = style.on(White),
78+
"48" => if let Some(c) = parse_into_high_colour(&mut iter) { style = style.on(c) },
79+
5880
_ => {/* ignore the error and do nothing */},
5981
}
6082
}
@@ -93,6 +115,16 @@ mod ansi_test {
93115
test!(semis: ";;;;;;" => Style::default());
94116
test!(nines: "99999999" => Style::default());
95117
test!(word: "GREEN" => Style::default());
118+
119+
// Higher colours
120+
test!(hifg: "38;5;149" => Fixed(149).normal());
121+
test!(hibg: "48;5;1" => Style::default().on(Fixed(1)));
122+
test!(hibo: "48;5;1;1" => Style::default().on(Fixed(1)).bold());
123+
test!(hiund: "4;48;5;1" => Style::default().on(Fixed(1)).underline());
124+
125+
test!(fgbg: "38;5;121;48;5;212" => Fixed(121).on(Fixed(212)));
126+
test!(bgfg: "48;5;121;38;5;212" => Fixed(212).on(Fixed(121)));
127+
test!(toohi: "48;5;999" => Style::default());
96128
}
97129

98130

0 commit comments

Comments
 (0)