如何确定终端的背景颜色?

发布于 2024-08-26 08:10:52 字数 104 浏览 12 评论 0 原文

我想知道是否有任何方法可以确定终端的背景颜色?

就我而言,使用 gnome-terminal。
这可能很重要,因为完全由终端应用程序来绘制其窗口的背景,甚至可能不是纯色。

I'd like to know if there is any way to determine a terminal's background color ?

In my case, using gnome-terminal.
It might matter, since it's entirety up to the terminal application to draw the background of its windows, which may even be something else than a plain color.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

温柔戏命师 2024-09-02 08:10:52

为此有一个 xterm 控制序列:(

\e]11;?\a

\e\a 分别是 ESC 和 BEL 字符。)

Xterm 兼容终端应使用相同的序列进行回复,并将问号替换为 X11 颜色名称,例如 rgb:0000/0000/0000< /code> 为黑色。

There's an xterm control sequence for this:

\e]11;?\a

(\e and \a are the ESC and BEL characters, respectively.)

Xterm-compatible terminals should reply with the same sequence, with the question mark replaced by an X11 color name, e.g. rgb:0000/0000/0000 for black.

故事↓在人 2024-09-02 08:10:52

我想出了以下内容:

#!/bin/sh
#
# Query a property from the terminal, e.g. background color.
#
# XTerm Operating System Commands
#     "ESC ] Ps;Pt ST"

oldstty=$(stty -g)

# What to query?
# 11: text background
Ps=${1:-11}

stty raw -echo min 0 time 0
# stty raw -echo min 0 time 1
printf "\033]$Ps;?\033\\"
# xterm needs the sleep (or "time 1", but that is 1/10th second).
sleep 0.00000001
read -r answer
# echo $answer | cat -A
result=${answer#*;}
stty $oldstty
# Remove escape at the end.
echo $result | sed 's/[^rgb:0-9a-f/]\+$//'

Source/Repo/Gist: https://gist.github.com/蓝色/c8470c2aad3381c33ea3

I've came up with the following:

#!/bin/sh
#
# Query a property from the terminal, e.g. background color.
#
# XTerm Operating System Commands
#     "ESC ] Ps;Pt ST"

oldstty=$(stty -g)

# What to query?
# 11: text background
Ps=${1:-11}

stty raw -echo min 0 time 0
# stty raw -echo min 0 time 1
printf "\033]$Ps;?\033\\"
# xterm needs the sleep (or "time 1", but that is 1/10th second).
sleep 0.00000001
read -r answer
# echo $answer | cat -A
result=${answer#*;}
stty $oldstty
# Remove escape at the end.
echo $result | sed 's/[^rgb:0-9a-f/]\+$//'

Source/Repo/Gist: https://gist.github.com/blueyed/c8470c2aad3381c33ea3

上课铃就是安魂曲 2024-09-02 08:10:52

一些链接:

章/2764" rel="noreferrer">Neovim 问题 2764:

/*
 * Return "dark" or "light" depending on the kind of terminal.
 * This is just guessing!  Recognized are:
 * "linux"         Linux console
 * "screen.linux"   Linux console with screen
 * "cygwin"        Cygwin shell
 * "putty"         Putty program
 * We also check the COLORFGBG environment variable, which is set by
 * rxvt and derivatives. This variable contains either two or three
 * values separated by semicolons; we want the last value in either
 * case. If this value is 0-6 or 8, our background is dark.
 */
static char_u *term_bg_default(void)
{
  char_u      *p;

  if (STRCMP(T_NAME, "linux") == 0
      || STRCMP(T_NAME, "screen.linux") == 0
      || STRCMP(T_NAME, "cygwin") == 0
      || STRCMP(T_NAME, "putty") == 0
      || ((p = (char_u *)os_getenv("COLORFGBG")) != NULL
          && (p = vim_strrchr(p, ';')) != NULL
          && ((p[1] >= '0' && p[1] <= '6') || p[1] == '8')
          && p[2] == NUL))
    return (char_u *)"dark";
  return (char_u *)"light";
}

关于 COLORFGBG env,来自 Gnome BugZilla 733423

在我刚刚在 Linux 上尝试过的相当多的终端中,只有 urxvt 和 konsole 设置了它(没有设置的终端:xterm、st、terminology、pterm)。 Konsole 和 Urxvt 使用不同的语法和语义,即对我来说 konsole 将其设置为“0;15”(即使我使用“浅黄色上的黑色”配色方案 - 那么为什么不使用“默认”而不是“15”?),而我的 urxvt 将其设置为“0;default;15”(实际上是白底黑字 - 但为什么是三个字段?)。因此,这两个值都不符合您的规范。

这是我正在使用的一些自己的代码(via):

def is_dark_terminal_background():
    """
    :return: Whether we have a dark Terminal background color, or None if unknown.
        We currently just check the env var COLORFGBG,
        which some terminals define like "<foreground-color>:<background-color>",
        and if <background-color> in {0,1,2,3,4,5,6,8}, then we have some dark background.
        There are many other complex heuristics we could do here, which work in some cases but not in others.
        See e.g. `here <https://stackoverflow.com/questions/2507337/terminals-background-color>`__.
        But instead of adding more heuristics, we think that explicitly setting COLORFGBG would be the best thing,
        in case it's not like you want it.
    :rtype: bool|None
    """
    if os.environ.get("COLORFGBG", None):
        parts = os.environ["COLORFGBG"].split(";")
        try:
            last_number = int(parts[-1])
            if 0 <= last_number <= 6 or last_number == 8:
                return True
            else:
                return False
        except ValueError:  # not an integer?
            pass
    return None  # unknown (and bool(None) == False, i.e. expect light by default)

Some links:

E.g. some related snippet from Neovim issue 2764:

/*
 * Return "dark" or "light" depending on the kind of terminal.
 * This is just guessing!  Recognized are:
 * "linux"         Linux console
 * "screen.linux"   Linux console with screen
 * "cygwin"        Cygwin shell
 * "putty"         Putty program
 * We also check the COLORFGBG environment variable, which is set by
 * rxvt and derivatives. This variable contains either two or three
 * values separated by semicolons; we want the last value in either
 * case. If this value is 0-6 or 8, our background is dark.
 */
static char_u *term_bg_default(void)
{
  char_u      *p;

  if (STRCMP(T_NAME, "linux") == 0
      || STRCMP(T_NAME, "screen.linux") == 0
      || STRCMP(T_NAME, "cygwin") == 0
      || STRCMP(T_NAME, "putty") == 0
      || ((p = (char_u *)os_getenv("COLORFGBG")) != NULL
          && (p = vim_strrchr(p, ';')) != NULL
          && ((p[1] >= '0' && p[1] <= '6') || p[1] == '8')
          && p[2] == NUL))
    return (char_u *)"dark";
  return (char_u *)"light";
}

About COLORFGBG env, from Gnome BugZilla 733423:

Out of quite a few terminals I've just tried on linux, only urxvt and konsole set it (the ones that don't: xterm, st, terminology, pterm). Konsole and Urxvt use different syntax and semantics, i.e. for me konsole sets it to "0;15" (even though I use the "Black on Light Yellow" color scheme - so why not "default" instead of "15"?), whereas my urxvt sets it to "0;default;15" (it's actually black on white - but why three fields?). So in neither of these two does the value match your specification.

This is some own code I'm using (via):

def is_dark_terminal_background():
    """
    :return: Whether we have a dark Terminal background color, or None if unknown.
        We currently just check the env var COLORFGBG,
        which some terminals define like "<foreground-color>:<background-color>",
        and if <background-color> in {0,1,2,3,4,5,6,8}, then we have some dark background.
        There are many other complex heuristics we could do here, which work in some cases but not in others.
        See e.g. `here <https://stackoverflow.com/questions/2507337/terminals-background-color>`__.
        But instead of adding more heuristics, we think that explicitly setting COLORFGBG would be the best thing,
        in case it's not like you want it.
    :rtype: bool|None
    """
    if os.environ.get("COLORFGBG", None):
        parts = os.environ["COLORFGBG"].split(";")
        try:
            last_number = int(parts[-1])
            if 0 <= last_number <= 6 or last_number == 8:
                return True
            else:
                return False
        except ValueError:  # not an integer?
            pass
    return None  # unknown (and bool(None) == False, i.e. expect light by default)
一袭白衣梦中忆 2024-09-02 08:10:52

正如其他人提到的,您可以使用 OSC 11 ? 来查询终端(尽管支持有所不同)。

在 bash 和 gnome-terminal 中:

read -rs -d \\ -p 
00000000: 1b5d 3131 3b72 6762 3a30 3030 302f 3262  .]11;rgb:0000/2b
00000010: 3262 2f33 3633 361b 0a                   2b/3636..

请注意,Bash 有一些不错的功能(例如 read -s 禁用 echo、$'' 字符串作为转义码),但不幸的是吃掉最后一个反斜杠。

\e]11;?\e\\' BG echo "$BG" | xxd

请注意,Bash 有一些不错的功能(例如 read -s 禁用 echo、$'' 字符串作为转义码),但不幸的是吃掉最后一个反斜杠。

As other's have mentioned, you may use OSC 11 ? to query the terminal (although support varies).

In bash and gnome-terminal:

read -rs -d \\ -p 
00000000: 1b5d 3131 3b72 6762 3a30 3030 302f 3262  .]11;rgb:0000/2b
00000010: 3262 2f33 3633 361b 0a                   2b/3636..

Note that Bash has some nice features for this (eg read -s disabling echo, $'' strings for escape codes), but it unfortunately eats the final backslash.

\e]11;?\e\\' BG echo "$BG" | xxd

Note that Bash has some nice features for this (eg read -s disabling echo, $'' strings for escape codes), but it unfortunately eats the final backslash.

帅的被狗咬 2024-09-02 08:10:52

除了 显然仅 rxvt $COLORFGBG 之外,我不知道其他任何东西甚至都存在。大多数人似乎指的是如何vim 做到了,即使这充其量也是一个有根据的猜测。

Aside from apparently rxvt-only $COLORFGBG, I am not aware that anything else even exists. Mostly people seem to be referring to how vim does it, and even that is an educated guess at best.

软糖 2024-09-02 08:10:52

您是指确定终端背景颜色或设置终端颜色的方法吗?

如果是后者,您可以查询终端的 PS1 环境变量来获取颜色。

这里有一篇关于设置(以及派生)终端颜色的文章:
http://www.ibm.com/developerworks/linux/library /l-提示提示/

Do you mean a method to ascertain the terminal background colour, or set the terminal colour?

If the latter you could query your terminal's PS1 environment variable to obtain the colour.

There's an article on setting (and so deriving) the terminal colours here:
http://www.ibm.com/developerworks/linux/library/l-tip-prompt/

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文