Pregunta

Me gustaría saber si hay alguna forma de determinar el color de fondo de un terminal.

En mi caso, usando gnome-terminal.
Podría importar, ya que depende completamente de la aplicación de terminal dibujar el fondo de sus ventanas, que incluso puede ser algo más que un color simple.

¿Fue útil?

Solución

He ocurrió la siguiente:

#!/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/]\+$//'

Fuente / Repo / Síntesis: https://gist.github.com/blueyed/c8470c2aad3381c33ea3

Otros consejos

Hay una xterm control de secuencia para esto:

\e]11;?\a

(\e y \a son los caracteres ESC y BEL, respectivamente.)

terminales compatibles-Xterm deben responder con la misma secuencia, con el signo de interrogación sustituido por un X11 colorSpec, por ejemplo rgb:0000/0000/0000 de negro.

parecer rxvt de sólo $ COLORFGBG , soy no se dan cuenta de que todo lo demás existe. Sobre todo la gente parecen ser refiriéndose a cómo vim Qué , e incluso eso es una conjetura, en el mejor.

Algunos enlaces:

P.ej.algún fragmento relacionado de Número 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";
}

Acerca de COLORFGBG env, de Gnomo BugZilla 733423:

De bastantes terminales que acabo de probar en Linux, solo urxvt y konsole lo configuran (los que no lo hacen:xterm, st, terminología, pterm).Konsole y Urxvt utilizan diferentes sintaxis y semántica, es decir.para mí, konsole lo establece en "0;15" (aunque uso el esquema de color "Negro sobre amarillo claro", entonces, ¿por qué no "predeterminado" en lugar de "15"?), mientras que mi urxvt lo establece en "0;predeterminado ;15" (en realidad es negro sobre blanco, pero ¿por qué tres campos?).Entonces, en ninguno de estos dos el valor coincide con su especificación.

Este es un código propio que estoy usando (a través de):

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)

¿Se refiere a un método para determinar el color de fondo del terminal, o establecer el color del terminal?

En este último caso se podría consultar variable de entorno PS1 de su terminal para obtener el color.

Hay un artículo sobre la configuración (y así derivar) los colores terminales aquí: http://www.ibm.com/developerworks/linux/library / l-tip-prompt /

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top