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?
I disagree with your characterization of ‘9 spaces after the green Green’. I use Perl rather than Ruby, but if I use a modification of your statement, printing a pipe symbol after the string, I get:
This shows to me that the
printf()statement counted 14 characters in the string, so it prepended 6 spaces to produce 20 characters right-aligned. However, the terminal swallowed 9 of those characters, interpreting them as colour changes. So, the output appeared 9 characters shorter than you wanted it to. However, theprintf()did not print 9 blanks after the first ‘Green’.Regarding the best practices for aligned output (with colourization), I think you’ll need to have each sized-and-aligned field surrounded by simple ‘%s’ fields which deal with the colourization:
Where, obviously, the
co_XXXXvariables (constants?) contain the escape sequences to switch to the named colour (andco_plainmight be better asco_black). If it turns out that you don’t need colourization on some field, you can use the empty string in place of theco_XXXXvariables (or call itco_empty).