Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop ANSI colour codes messing up printf alignment?

I discovered this while using ruby printf, but it also applies to C's printf.

If you include ANSI colour escape codes in an output string, it messes up the alignment.

Ruby:

ruby-1.9.2-head > printf "%20s\n%20s\n", "\033[32mGreen\033[0m", "Green"
      Green          # 6 spaces to the left of this one
               Green # correctly padded to 20 chars
 => nil

The same line in a C program produces the same output.

Is there anyway to get printf (or something else) to align output and not add spaces for non-printed characters?

Is this is a bug, or is there a good reason for it?

Update: Since printf can't be relied upon to align data when there's ANSI codes and wide chars, is there a best practice way of lining up coloured tabular data in the console in ruby?

like image 453
Stewart Johnson Avatar asked Sep 16 '10 03:09

Stewart Johnson


1 Answers

It's not a bug: there's no way ruby should know (at least within printf, it would be a different story for something like curses) that its stdout is going to a terminal that understands VT100 escape sequences.

If you're not adjusting background colours, something like this might be a better idea:

GREEN = "\033[32m"
NORMAL = "\033[0m"
printf "%s%20s%s\n", GREEN, "Green", NORMAL
like image 102
Jack Kelly Avatar answered Sep 22 '22 19:09

Jack Kelly