How to get the displayed line width?

If you have non-fixed width characters (for example, \t ) in a string or escape codes, for example for ANSI color (for example, \1xb[31m ), these characters are added to .length() std::string , but when printed do not add the displayed length.

Is there a way in C ++ to get the displayed line width in * nix?

For example:

 displayed_width("a\tb") would be 4 if the displayed tab width is 2 displayed_width("\1xb[33mGREEN") would be 5 
+7
source share
4 answers

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; } 
+2
source

Nothing is embedded. The "displayed width" of the tab character is an implementation detail as well as console escape sequences. C ++ doesn't care about platform-like things.

Is there anything you are trying to do? We can offer alternatives if we know what specific task you are working on.

+1
source

Not with standard methods, as far as I know. C ++ does not know about terminals. I would rather use NCURSES for this. Dunno if boost has something sleeve for this though.

0
source

Display length on which device? A console using a fixed-width font? A window that uses proportional font? This is a device dependent question. There is no single answer. You will need to use the tools associated with the target output device.

0
source

All Articles