Most often, the tab suggests that the terminal program move the cursor to a column that is a multiple of 8, although many terminal programs allow you to configure this. With this behavior, how much tab width is actually added depends on where the cursor was previously relative to the tab stops. Thus, simply knowing the string contents is not enough to calculate the width for printing without any assumption or understanding regarding the preliminary placement of the cursor and tabs.
Non-printable codes also vary for each type of terminal, although if you only need ANSI color, then it's pretty easy. You can move along the line count characters; when you see ESCAPE, skip to the final m . Something like (unverified):
int displayed_width(const char* p) { int result = 0; for ( ; *p; ++p) { if (p[0] == '\e' && p[1] == '[') while (*p != 'm') if (*p) ++p; else throw std::runtime_error("string terminates inside ANSI colour sequence"); else ++result; } return result; }
user433534
source share