Determine terminal/TTY background color at runtime
Asked Answered
A

1

11

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.

Appetency answered 25/4, 2018 at 16:29 Comment(2)
There's no portable method. For xterm (and some of the terminals that imitate it), there's DECRQSS asking for the current SGR settings.Randazzo
See if this helps #2507837?Melcher
V
4

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.

Verger answered 6/5, 2018 at 23:17 Comment(1)
How do you do this with chalk specifically?Pandit

© 2022 - 2024 — McMap. All rights reserved.