Comment déterminer la couleur de fond d’un terminal ?
-
22-09-2019 - |
Question
J'aimerais savoir s'il existe un moyen de déterminer la couleur de fond d'un terminal ?
Dans mon cas, j'utilise gnome-terminal.
Cela peut avoir son importance, car c'est à l'application du terminal de dessiner l'arrière-plan de ses fenêtres, qui peut même être autre chose qu'une couleur unie.
La solution
Je suis venu avec ce qui suit:
#!/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 / Contenu essentiel: https://gist.github.com/blueyed/c8470c2aad3381c33ea3
Autres conseils
En dehors de apparemment rxvt seulement COLORFGBG $ , je suis pas au courant que toute autre chose existe. La plupart des gens semblent être se référant à comment vim il fait , et même qui est une supposition au mieux.
Quelques liens :
- Code d'échappement Xterm :
- http://www.talisman.org/~erlkonig/documents/xterm-color-queries/
- https://invisible-island.net/xterm/ctlseqs/ctlseqs.html (couleurs dynamiques / Demande Termcap/Terminfo String)
- http://thrysoee.dk/xtermcontrol/ (
xtermcontrol --get-bg
) - https://gist.github.com/blueyed/c8470c2aad3381c33ea3
- https://github.com/rocky/bash-term-background/blob/master/term-background.sh
COLORFGBG
variable d'environnement (utilisée par Rxvt mais pas beaucoup d'autres...) :
Il est réglé sur quelque chose comme<foreground-color>:[<other-setting>:]<background-color>
, (<other setting>:
est facultatif), et si<background-color>
dans {0,1,2,3,4,5,6,8}, alors nous avons un fond sombre.- Vigueur:
- Emacs...(mode arrière-plan) (je pense qu'il utilise le code d'échappement)
- Questions/rapports/discussions connexes :
- Existe-t-il un moyen de déterminer la couleur d’arrière-plan d’un terminal ?
- Comment Vim devine-t-il la couleur d’arrière-plan sur xterm ?
- https://unix.stackexchange.com/questions/245378/common-environment-variable-to-set-dark-or-light-terminal-background
- https://bugzilla.gnome.org/show_bug.cgi?id=733423
- https://github.com/neovim/neovim/issues/2764
Par exemple.un extrait connexe de Néovim numéro 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";
}
À propos COLORFGBG
env, de Gnome BugZilla 733423:
Sur un certain nombre de terminaux que je viens d'essayer sous Linux, seuls urxvt et konsole le configurent (ceux qui ne le font pas :xterm, st, terminologie, pterm).Konsole et Urxvt utilisent une syntaxe et une sémantique différentes, c'est-à-direpour moi, la console le définit sur "0;15" (même si j'utilise le jeu de couleurs "Noir sur jaune clair" - alors pourquoi pas "par défaut" au lieu de "15" ?), alors que mon urxvt le définit sur "0;par défaut ;15" (c'est en fait noir sur blanc - mais pourquoi trois champs ?).Ainsi, dans aucun de ces deux cas, la valeur ne correspond à vos spécifications.
C'est mon propre code que j'utilise (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)
Voulez-vous dire une méthode pour déterminer la couleur d'arrière-plan terminal, ou définir la couleur du terminal?
Dans ce dernier cas, vous pouvez interroger votre environnement du terminal PS1 la variable pour obtenir la couleur.
Il y a un article sur la définition (et ainsi déduire) les couleurs terminales ici: http://www.ibm.com/developerworks/linux/library / l-tip-prompt /