Gwenn
Gwenn

Reputation: 55

How to compute the display width of a prompt on the CLI with ANSI escape codes?

A trivial implementation:

extern crate unicode_width;

fn main () {
    let prompt = "\x1b[1;32m>>\x1b[0m ";
    println!("{}", unicode_width::UnicodeWidthStr::width(prompt));
}

returns 12 but 3 is expected.

I would also be happy to use a crate that already does this, if there is one.

Upvotes: 1

Views: 334

Answers (1)

Thomas Dickey
Thomas Dickey

Reputation: 54505

You're not going to get the width of an escape-sequence using a Unicode width calculation, simply because none of the string is printable—on a terminal.

If you control the content of the string, you could calculate the width by

  • copying the string to a temporary variable
  • substituting the escape sequences to empty strings, e.g., changing the pattern starting with \x1b, allowing any combination of [, ], <, >', =, ?, ; or decimal digits through the "final" characters in the range @ to ~
  • measuring the length of what (if anything) is left.

In your example

let prompt = "\x1b[1;32m>>\x1b[0m ";

only ">> " would be left to measure.

For patterns... you would start here: Regex

Further reading:

Upvotes: 1

Related Questions