Reputation: 343
I want to colorize a formatted output. But the format of the colorized text is ignored:
String leftAlignFormat = "| %-15s | %-15s |";
System.out.format(leftAlignFormat, "\033[38;5;16;48;5;40mHello\033[0m", "World");
| Hello | World |
The word Hello is correctly colored, but why is the word Hello not correctly formatted?
Upvotes: 0
Views: 831
Reputation: 2070
This is because formatting is based on String length. Following code will explain what happens:
String hello = "\033[38;5;16;48;5;40mHello\033[0m";
System.out.println(hello);
System.out.println(hello.length());
String leftAlignFormat = "| %-27s | %-20s |";
System.out.format(leftAlignFormat, hello, "World");
System.out.println("");
leftAlignFormat = "| %-28s | %-20s |";
System.out.format(leftAlignFormat, hello, "World");
String length will output 27. So a setting of 28 will start padding the String. It might be looking awkward, but formatting is String based - not meant to be an ANSI formatting tool.
Upvotes: 1
Reputation: 3938
The color format "\033[0m"
is used to reset the colors.
In your format you have used it just at the end of the first string; hence rest of the text is reset to default colors.
System.out.format(leftAlignFormat, "\033[38;5;16;48;5;40mHello\033[0m", "World");
Based on this format, the work Hello must be highlighted with green, but not the rest.
This is how I see it in my IDE.
Upvotes: 0
Reputation: 13374
Java's APIs don't natively understand ANSI color escape codes, so the format(...)
API is counting those as characters in the string.
But when those characters written to an ANSI terminal, the escape codes do not move the cursor, so the formatting appears incorrect.
Depending on the complexity of the usecase, you will need to build your own wrapper APIs (if there are strings with several colors), or you can work around it by knowing exactly how many extra characters you add to generate a color, and increase your padding width accordingly. For simplicity, I would recommend always prepending the color code sequence and appending the reset, so the "extra" padding is a fixed amount.
Also keep in mind that ANSI escape codes are not portable, so you may need to support a no color code & template path, depending on your target execution environment(s)
Upvotes: 2