
On 10/16/20, Steven D'Aprano <steve@pearwood.info> wrote:
On terminals that support it, this should work:
- `print('\33[H\33[2J')`
but I have no idea how to avoid clearing the scrollback buffer on Windows, or other posix systems with unusual terminals.
In Windows 10, ANSI sequences and some C1 control characters (e.g. clear via CSI -- '\x9b2J\x9bH') are supported by a console session if it's not in legacy mode. The ESC character can be typed as Ctrl+[, which is useful in the CMD shell, which doesn't support character escapes such as \33 or \x1b. It can also be set in an %ESC% environment variable. Using ANSI sequences and C1 controls requires virtual terminal (VT) mode to be enabled for the console screen buffer. VT mode is enabled by default in a pseudoconsole session (e.g. when attached to a tab in Windows Terminal), but it can be manually disabled. It's also enabled by default for non-legacy console sessions if "VirtualTerminalLevel" is set to 1 in "HKCU\Console". Regardless, it's simple to check whether VT mode is currently enabled for the screen buffer via WinAPI GetConsoleMode. If VT mode isn't enabled, the screen buffer can be scrolled using the console API function ScrollConsoleScreenBuffer using dimensions and attributes from GetConsoleScreenBufferInfo, and the cursor position can be set via SetConsoleCursorPosition.