Created
May 2, 2024 15:33
-
-
Save ntrrgc/fc47b416bff68ebc05883ec733c8a7b8 to your computer and use it in GitHub Desktop.
OSC 10 & 11: Query terminal foreground and background colors
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import os, termios, collections, re | |
TermAttr = collections.namedtuple("TermAttr", | |
["iflag", "oflag", "cflag", "lflag", "ispeed", "ospeed", "cc"]) | |
old = TermAttr._make(termios.tcgetattr(0)) | |
new = old._replace( | |
lflag=old.lflag & ~(termios.ECHO | termios.ICANON) | |
) | |
try: | |
termios.tcsetattr(0, termios.TCSADRAIN, list(new)) | |
REQUEST_FG = b"\x1b]10;?\x1b\\" | |
REQUEST_BG = b"\x1b]11;?\x1b\\" | |
os.write(1, REQUEST_FG + REQUEST_BG) | |
re_rgb = re.compile(rb".*\x1b](10|11);rgb:(\w+)/(\w+)/(\w+)(?:\x1b\\|\x07)") | |
matches = [] | |
response = b"" | |
while True: | |
buf = os.read(0, 1) | |
if buf == b"": | |
break # EOF | |
response += buf | |
if match := re_rgb.match(response): | |
matches.append(match) | |
response = b"" | |
if len(matches) == 2: | |
break | |
except KeyboardInterrupt: | |
pass | |
finally: | |
termios.tcsetattr(0, termios.TCSADRAIN, list(old)) | |
for match in matches: | |
feature, r, g, b = [x.decode() for x in match.groups()] | |
feature = {"10": "Foreground", "11": "Background"}[feature] | |
print(f"{feature} R={r} G={g} B={b}") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment