Skip to content

Commit 6c588f1

Browse files
hackeddPaul Hooijenga
authored andcommitted
Windows: enable ANSI escape support in console.
1 parent b63748f commit 6c588f1

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed

pre_commit/color.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,15 @@
11
from __future__ import unicode_literals
22

3+
import os
34
import sys
45

6+
if os.name == 'nt': # pragma: no cover (windows)
7+
from pre_commit.color_windows import enable_virtual_terminal_processing
8+
try:
9+
enable_virtual_terminal_processing()
10+
except WindowsError:
11+
pass
12+
513
RED = '\033[41m'
614
GREEN = '\033[42m'
715
YELLOW = '\033[43;30m'

pre_commit/color_windows.py

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
from __future__ import unicode_literals
2+
3+
from ctypes import POINTER
4+
from ctypes import windll
5+
from ctypes import WinError
6+
from ctypes import WINFUNCTYPE
7+
from ctypes.wintypes import BOOL
8+
from ctypes.wintypes import DWORD
9+
from ctypes.wintypes import HANDLE
10+
11+
STD_OUTPUT_HANDLE = -11
12+
ENABLE_VIRTUAL_TERMINAL_PROCESSING = 4
13+
14+
15+
def bool_errcheck(result, func, args):
16+
if not result:
17+
raise WinError()
18+
return args
19+
20+
21+
GetStdHandle = WINFUNCTYPE(HANDLE, DWORD)(
22+
("GetStdHandle", windll.kernel32),
23+
((1, "nStdHandle"), )
24+
)
25+
26+
GetConsoleMode = WINFUNCTYPE(BOOL, HANDLE, POINTER(DWORD))(
27+
("GetConsoleMode", windll.kernel32),
28+
((1, "hConsoleHandle"), (2, "lpMode"))
29+
)
30+
GetConsoleMode.errcheck = bool_errcheck
31+
32+
SetConsoleMode = WINFUNCTYPE(BOOL, HANDLE, DWORD)(
33+
("SetConsoleMode", windll.kernel32),
34+
((1, "hConsoleHandle"), (1, "dwMode"))
35+
)
36+
SetConsoleMode.errcheck = bool_errcheck
37+
38+
39+
def enable_virtual_terminal_processing():
40+
"""As of Windows 10, the Windows console supports (some) ANSI escape
41+
sequences, but it needs to be enabled using `SetConsoleMode` first.
42+
43+
More info on the escape sequences supported:
44+
https://msdn.microsoft.com/en-us/library/windows/desktop/mt638032(v=vs.85).aspx
45+
46+
"""
47+
stdout = GetStdHandle(STD_OUTPUT_HANDLE)
48+
flags = GetConsoleMode(stdout)
49+
SetConsoleMode(stdout, flags | ENABLE_VIRTUAL_TERMINAL_PROCESSING)

0 commit comments

Comments
 (0)