Determine terminal/TTY background color at runtime

浪子不回头ぞ 提交于 2020-06-22 18:01:48

问题


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:

It's difficult to read the blue on black.


回答1:


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:

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.



来源:https://stackoverflow.com/questions/50027162/determine-terminal-tty-background-color-at-runtime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!