Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine terminal/TTY background color at runtime

Using the chalk library to stylize/colorize the terminal.

import chalk from 'chalk';

if I use:

console.log(chalk.blue('foobar'));

that's totally readable in a terminal with a light background, but totally unreadable in a terminal with a dark background.

Is there some way to determine the background color of a terminal at runtime?


Example given:

The "npm notice" log level is a case of this problem:

enter image description here

It's difficult to read the blue on black.

like image 359
Alexander Mills Avatar asked Apr 25 '18 16:04

Alexander Mills


1 Answers

The following is a generic answer, about ANSI Escape sequences in the tty context.

To highlight a specific sequence by swapping the backgroud/foreground, so it stay readable on all color schemes, use code 7 Reverse video.

This way there is no need to prior knows the palette and adapt.

Example in bash, using reverse video:

echo -e "\033[7mHello world\e[0m"

This can be chained, reverse video, and a red background:

echo -e "\033[31;7mHello world\e[0m"

This will always be readable on any background, like the second line of this gif:

enter image description here

Reverse video is commonly used in software programs as a visual aid to highlight a selection that has been made as an aid in preventing description errors, where an intended action is performed on an object that is not the one intended. It is more common in modern desktop environments to change the background to other colors such as blue, or to use a semi-transparent background to "highlight" the selected text. On a terminal understanding ANSI escape sequences, the reverse video function is activated using the escape sequence CSI 7 m (which equals SGR 7). https://en.wikipedia.org/wiki/Reverse_video

From my own answer: How to change the output color of echo in Linux , a question with a lot of informations about ansi sequences.

like image 109
NVRM Avatar answered Sep 21 '22 13:09

NVRM