如何获取 tput smcup/rmcup 设置的屏幕状态?

Ric*_*man 5 bash terminal xterm tput

虽然我知道tput rmcup从“备用屏幕”(在 中称为“杯子模式” man 5 terminfo)返回并恢复保存的屏幕,但它确实具有重新定位光标的副作用。

因此,如果tput smcup被调用,tput rmcup则恢复屏幕并重新定位光标,但如果您随后再键入一些命令或按 Enter 几次然后再次使用tput rmcup,光标将返回到原始保存的位置。

一个用例是在bash重播终端录音的脚本中[使用scriptreplay]:如果脚本提前结束而没有[相当于]调用tput rmcup,那么我希望能够在我的bash脚本中检测到这一点并tput rmcup自动调用。

简而言之,我希望能够确定当前的屏幕状态是什么;即,它是“备用屏幕”还是“正常屏幕”?

Tho*_*key 4

如果您使用 xterm,那么您可以询问它正在使用什么模式。尽管备用屏幕功能是 xterm 功能而不是“DEC”,但该设置与XTerm 控制序列DECSET中描述的模式分组:

CSI ? Pm h
          DEC Private Mode Set (DECSET).
...
            Ps = 1 0 4 7  -> Use Alternate Screen Buffer, xterm.  This
          may be disabled by the titeInhibit resource.
            Ps = 1 0 4 8  -> Save cursor as in DECSC, xterm.  This may
          be disabled by the titeInhibit resource.
            Ps = 1 0 4 9  -> Save cursor as in DECSC, xterm.  After sav-
          ing the cursor, switch to the Alternate Screen Buffer, clear-
          ing it first.  This may be disabled by the titeInhibit
Run Code Online (Sandbox Code Playgroud)

DECRQM控件可用于查询终端:

CSI ? Ps$ p
          Request DEC private mode (DECRQM).  For VT300 and up, reply
          DECRPM is
            CSI ? Ps; Pm$ y
          where Ps is the mode number as in DECSET/DECSET, Pm is the
          mode value as in the ANSI DECRQM.
Run Code Online (Sandbox Code Playgroud)

也就是说,你的脚本可以

printf '\033[?1049$p'
Run Code Online (Sandbox Code Playgroud)

并读回结果,期待类似的结果\033[?1049;1$y

这是一个快速演示:

#!/bin/sh                                                                      

unexpected() {
        result=$(echo "$check"|sed -e 's/^@/\\033/')
        printf '? unexpected reply: %s\n' "$result"
        exit 1
}

exec </dev/tty
old=`stty -g`
stty raw -echo min 0  time 5
printf '\033[?1049$p'
read status
stty $old

if [ -n "$status" ]
then
        check=$(echo "$status" |tr '\033' '@')
        if [ "$check" != "$status" ]
        then
                case "$check" in
                '@[?1049;1$y')
                        echo "alternate screen"
                        ;;
                '@[?1049;2$y')
                        echo "normal screen"
                        ;;
                *)
                        unexpected
                        ;;
                esac
        else
                unexpected
        fi
else
        echo "? no reply from terminal"
fi
Run Code Online (Sandbox Code Playgroud)

当然,如果您不使用 xterm,您的情况可能会有所不同......