What does [?1049h and [?1h ANSI escape sequences do

escape-charactersless

When I used shell in a box and when I call less command (echo foo | less) in ajax response there was this code:

\u001B[?1049h\u001B[?1h\u001B=\rfoo\r\n\u001B[7m(END)\u001B[27m\u001B[K

what does \u001B[?1049h and \u001B[?1h escape sequences do, also what is \u001B=? Are they documented somewhere?

Best Answer

\u001B is an unnecessarily verbose ASCII escape character, which seems to have been introduced for ECMAScript6. POSIX would use octal \033, and some others allow hexadecimal \01b. The upper/lower case of the number is irrelevant.

The \u001B[?1049h (and \u001B[?1049l) are escape sequences which tell xterm to optionally switch to and from the alternate screen.

  • The question mark shows that it is "private use" (a category set aside for implementation-specific features in the standard). About a third of the private-use modes listed in XTerm Control Sequences correspond to one of DEC's (those have a mnemonic such as DECCKM in their descriptions). The others are either original to xterm, or adapted from other terminals, as noted.

  • The reason for this escape sequence is to provide a terminfo-based way to let users decide whether programs can use the alternate screen. According to the xterm manual:

titeInhibit (class TiteInhibit)
Specifies whether or not xterm should remove ti and te termcap entries (used to switch between alternate screens on startup of many screen-oriented programs) from the TERMCAP string. If set, xterm also ignores the escape sequence to switch to the alternate screen. Xterm supports terminfo in a different way, supporting composite control sequences (also known as private modes) 1047, 1048 and 1049 which have the same effect as the original 47 control sequence. The default for this resource is "false".

The 1049 code (introduced in 1998) is recognized by most terminal emulators which claim to be xterm-compatible, but most do not make the feature optional. So they don't really implement the feature.

On the other hand, \u001B[?1h did not originate with xterm, but (like \u001B=) is from DEC VT100s, used for switching the terminal to use application mode for cursor keys (DECCKM) and the numeric keypad (DECKPAM). These are used by programs such as less when initializing the terminal because terminal descriptions use application (or normal) mode escape sequences for special keys to match the initialization strings given in these terminal descriptions.

Further reading: