ogham / rust-ansi-term

Rust library for ANSI terminal colours and styles (bold, underline)

Home Page:https://crates.io/crates/ansi_term

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

ANSIStrings could handle spaces specially

tbelaire opened this issue · comments

I see a potential improvement to ANSIStrings, where you can drop foreground colour changes for strings that are only whitespace.

I.E.

use ansi_term::Colour::Red;
use ansi_term::{ANSIString, ANSIStrings};
let some_value = format!("{:b}", 42);
let strings: &[ANSIString<'static>] = &[
    Red.paint("["),
    Blue.paint("   "),
    Red.paint("]"),
];
println!("Value: {}", ANSIStrings(strings));

could not bother switching to blue in the middle.

This is an interesting performance improvement! It's actually something that could be put to use in exa — there are quite a few places where it paints something in one colour, follows that with a default-coloured space, and then prints something in the same colour again. It could elide two of the colour codes if it knew that the spaces wouldn't actually affect anything.

the problem with doing it automatically is that it requires a runtime check, and that's not going to be appropriate in all cases. (Especially as we'd have to check for Unicode space characters, too.) Instead, I think this is possible with a two-step approach:

  1. Define a new style variant called Inherit or something that just keeps the colours that are already there. Currently it's not possible to do this because everything in ANSIStrings needs to have a style defined.
  2. Write a pass that detects strings that only contain spaces, and re-writes them to use this new style variant instead.

It would have to be clever and detect styles that do affect just spaces, such as underline or background colours, but it's certainly possible. How does this sound?

whoops hit the wrong button

I'd be hesitant to add this much cleverness around spaces, when the application code could also avoid styling the spaces. This would also take carefully analyzing things like "print styled space, position cursor, print over the space".

Does this case come up often enough to make it worth trying to omit the escape sequence?