I was also surprised when I discovered this. IMO this should be used everywhere but I've rarely seen it.
> How does it work with buffered stdout? For example, if you wanted to colour a single word?
This is not affected by buffering. What matters is what the output device/file/stream gets eventually.
How coloring a single word works depends on how you use it.
You can do
write_and_flush_to_dev_tty(BEGIN_RED_TEXT);
write_and_flush_to_dev_tty("word");
write_and_flush_to_dev_tty(END_RED_TEXT);
The write_and_flush_... pseudo functions are written in this way just to make it clear that I'm describing the behavior when the output gets the bytes immediately. I don't mean that you should use /dev/tty like this.Redirection won't have any effect on these lines of code. You always get a red "word" on the terminal. The redirection target doesn't get anything.
write_and_flush_to_dev_tty(BEGIN_RED_TEXT);
write_and_flush_to_stdout("word");
write_and_flush_to_dev_tty(END_RED_TEXT);
When directly used on a terminal, you get a red "word" on your terminal, but when
you do redirection, the target only gets plaintext "word". write_and_flush_to_dev_tty(BEGIN_RED_TEXT);
write_and_flush_to_stdout("word");
write_and_flush_to_stdout(END_RED_TEXT);
When redirected, your terminal stays red after the red "word" is printed, and your redirection target gets an extra escape code.When stdout is a tty, /dev/tty is the same as stdout, so a write that goes to one goes to the other. In this case, even if you don't flush after write immediately it's likely not a problem. Still it's something that the developer should pay attention to.
-------------
Edit:
Please ignore all the pseudocode examples. They don't convey what I wanted to express.
Just use /dev/tty in the same way as how you would use stdin/stdout/stderr that is connected to a terminal. Only difference is that it is a rw device that can be used for input and output at the same time.