Read the current text color in a xterm

前端 未结 4 573
情话喂你
情话喂你 2021-01-30 02:43

I\'m writing various utilities, and I\'m really liking colorized text. Nothing fancy, just using escape sequences. I\'ve created a simple class that has a pprint(msg, color) fun

4条回答
  •  别那么骄傲
    2021-01-30 03:13

    Actually, it's possible — for xterm, and compatible terminals.

    xtermcontrol for instance uses the OSC 10 control sequence to retrieve the default foreground/background colors. It's been documented in xterm since 2002.

    For other terminals:

    • In RHEL 5, the "Terminal" program is gnome-terminal 2.16.0; that version does not recognize OSC 10 (tested with the equivalent CentOS 5).
    • The question was asked in 2010, referring to the Red Hat enterprise version, which, if anything, is slower to update than Debian.
    • Moving forward in time, gnome-terminal 3.4.1.1 on Debian 7 (early 2012) also did not recognize the control sequence.
    • Finally, in Debian 8 with 3.14.1 (late 2014) the feature is recognized.
    • CentOS 7's gnome-terminal 3.14.3 recognizes the control sequence.

    Curious when it was added, bear in mind that VTE's developers don't write documentation. So... studying the git log shows

    commit 1b8c6b1aac587b79476a60a5830385abc939430d 
    Author: Egmont Koblinger  
    Date:   Wed Jan 22 00:13:51 2014 +0100
    
        emulation: Add support for OSC 1?1[017] (fg, bg, highlight colors)
    
        https://bugzilla.gnome.org/show_bug.cgi?id=567444
    

    On the other hand, the default colors are not the same as the current colors. Users have been able to do this with xterm since patch #93 in 1999 using the DECRQSS control sequence. That is, putting the terminal into raw mode and doing something like

    printf '\033P$m\033\\'
    

    would get it to reply with the string filled out with the SGR parameters.

    If colors were set using SGR, those codes would be part of the reply, e.g.

    \033P1$r0;33m\033\\
    

    to denote foreground color number 3 (encoded as 33).

    You could stop there (because you could extract those parameters and reuse them to set the terminal to the same state later), but then getting the actual RGB colors would be possible using OSC 4. You'd use the color number (from the SGR sequence), and send something like this:

    printf '\033]4;3;?\033\\'
    

    So it's certainly doable with xterm. There'll be a demo/test-script for DECRQSS in the next update for xterm.

    For other programs, you need more time:

    • xtermcontrol's developer overlooked DECRQSS (it has no feature for setting/getting SGR codes).

    • VTE's developers copy xterm features in response to bug reports; the VTE source does not mention DECRQSS. Its git log mentions OSC 4 in 2009, but the implementation is incomplete (it only allows one to set a color, not get the color).

提交回复
热议问题