From 17dc93934689235ac16b3354c3eb932420a88e85 Mon Sep 17 00:00:00 2001 From: Garfield Lee Date: Fri, 26 Jan 2024 00:16:26 +0800 Subject: [PATCH] lib/std/fs/File: enable VT seq support for Windows Console * Newer versions of Windows added VT seq support not only in Windows Terminal, but also in the old-fashioned Windows Console (standalone conhost.exe), though not enabled by default. * Try setting the newer console mode flags provides better experience for Windows Console users. Co-authored-by: Kexy Biscuit --- lib/std/fs/File.zig | 21 ++++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/lib/std/fs/File.zig b/lib/std/fs/File.zig index 42a2ae7132..c07f5864a0 100644 --- a/lib/std/fs/File.zig +++ b/lib/std/fs/File.zig @@ -248,9 +248,24 @@ pub fn isCygwinPty(file: File) bool { /// Test whether ANSI escape codes will be treated as such. pub fn supportsAnsiEscapeCodes(self: File) bool { if (builtin.os.tag == .windows) { - var console_mode: windows.DWORD = 0; - if (windows.kernel32.GetConsoleMode(self.handle, &console_mode) != 0) { - if (console_mode & windows.ENABLE_VIRTUAL_TERMINAL_PROCESSING != 0) return true; + var original_console_mode: windows.DWORD = 0; + + // For Windows Terminal, VT Sequences processing is enabled by default. + if (windows.kernel32.GetConsoleMode(self.handle, &original_console_mode) != 0) { + if (original_console_mode & windows.ENABLE_VIRTUAL_TERMINAL_PROCESSING != 0) return true; + + // For Windows Console, VT Sequences processing support was added in Windows 10 build 14361, but disabled by default. + // https://devblogs.microsoft.com/commandline/tmux-support-arrives-for-bash-on-ubuntu-on-windows/ + // Use Microsoft's recommended way to enable virtual terminal processing. + // https://learn.microsoft.com/en-us/windows/console/console-virtual-terminal-sequences#example-of-enabling-virtual-terminal-processing + var requested_console_modes: windows.DWORD = windows.ENABLE_VIRTUAL_TERMINAL_PROCESSING | windows.DISABLE_NEWLINE_AUTO_RETURN; + var console_mode = original_console_mode | requested_console_modes; + if (windows.kernel32.SetConsoleMode(self.handle, console_mode) != 0) return true; + + // An application receiving ERROR_INVALID_PARAMETER with one of the newer console mode flags in the bit field should gracefully degrade behavior and try again. + requested_console_modes = windows.ENABLE_VIRTUAL_TERMINAL_PROCESSING; + console_mode = original_console_mode | requested_console_modes; + if (windows.kernel32.SetConsoleMode(self.handle, console_mode) != 0) return true; } return self.isCygwinPty();