rich_click.terminal_background
Detect whether the terminal has a dark or light background.
Detection runs in this order, stopping at the first answer:
- The
RICH_CLICK_BACKGROUNDenv var (darkorlight), so users can always override detection. - The
COLORFGBGenv var (fg;bg), which some terminals set (rxvt, Konsole, iTerm2). - Asking the terminal for its background color with an OSC 11 query.
The OSC 11 query is only sent when stdin and stdout are both an interactive terminal on POSIX,
and the process is in the foreground. Otherwise, the result is None (unknown).
How the terminal query works:
- We write two escape sequences to the terminal. The terminal answers them by “typing” its replies into our stdin, so we switch stdin to cbreak mode and read them back.
ESC ] 11 ; ? ESC \(OSC 11) asks for the background color. A terminal that supports it repliesESC ] 11 ; rgb:RRRR/GGGG/BBBB, which we convert to dark or light by its luminance. Terminals that don’t support it stay silent.ESC [ c(DA1, “Primary Device Attributes”) asks what kind of terminal this is. Nearly every terminal replies, with something likeESC [ ? 62 ; 22 c. We don’t care about its contents.- Terminals reply in the order they were asked, so once the DA1 reply (
_RE_DA1_REPLY) has arrived, any OSC 11 reply has already arrived too. That lets us stop reading straight away, rather than waiting out the timeout on terminals that never answer OSC 11. - If no DA1 reply arrives before the timeout, we give up and discard any unread input. A reply that arrives after that is left for the shell to read, and shows up as garbage at the prompt.
Attributes
| Name | Description |
|---|---|
Background | No description. |
QUERY_TIMEOUT | No description. |
QUERY_TIMEOUT_SSH | No description. |
Functions
| Name | Description |
|---|---|
detect_background | Detect whether the terminal has a dark or light background. |
parse_osc11_reply | Parse a terminal's OSC 11 reply, e.g. ESC ] 11 ; rgb:ffff/ffff/ffff BEL. |
Backgroundattributemodule attribute#
Background = Literal['dark', 'light']QUERY_TIMEOUTattributemodule attribute#
QUERY_TIMEOUT = 0.1QUERY_TIMEOUT_SSHattributemodule attribute#
QUERY_TIMEOUT_SSH = 0.5detect_backgroundfunction#
def detect_background() -> Background | NoneDetect whether the terminal has a dark or light background.
Returns
Background | None"dark","light", orNoneif the background could not be detected.
parse_osc11_replyfunction#
def parse_osc11_reply(reply: bytes) -> Background | NoneParse a terminal’s OSC 11 reply, e.g. ESC ] 11 ; rgb:ffff/ffff/ffff BEL.