Skip to content

Commit 4e3f2d8

Browse files
[#1487] ensure that when printing color text the background color of the terminal on windows is preserved (#1865)
Co-authored-by: dominic <[email protected]>
1 parent ffc727a commit 4e3f2d8

File tree

1 file changed

+11
-5
lines changed

1 file changed

+11
-5
lines changed

src/colorprint.cc

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -135,19 +135,25 @@ void ColorPrintf(std::ostream& out, LogColor color, const char* fmt,
135135
// Gets the current text color.
136136
CONSOLE_SCREEN_BUFFER_INFO buffer_info;
137137
GetConsoleScreenBufferInfo(stdout_handle, &buffer_info);
138-
const WORD old_color_attrs = buffer_info.wAttributes;
138+
const WORD original_color_attrs = buffer_info.wAttributes;
139139

140140
// We need to flush the stream buffers into the console before each
141141
// SetConsoleTextAttribute call lest it affect the text that is already
142142
// printed but has not yet reached the console.
143143
out.flush();
144-
SetConsoleTextAttribute(stdout_handle,
145-
GetPlatformColorCode(color) | FOREGROUND_INTENSITY);
144+
145+
const WORD original_background_attrs =
146+
original_color_attrs & (BACKGROUND_RED | BACKGROUND_GREEN |
147+
BACKGROUND_BLUE | BACKGROUND_INTENSITY);
148+
149+
SetConsoleTextAttribute(stdout_handle, GetPlatformColorCode(color) |
150+
FOREGROUND_INTENSITY |
151+
original_background_attrs);
146152
out << FormatString(fmt, args);
147153

148154
out.flush();
149-
// Restores the text color.
150-
SetConsoleTextAttribute(stdout_handle, old_color_attrs);
155+
// Restores the text and background color.
156+
SetConsoleTextAttribute(stdout_handle, original_color_attrs);
151157
#else
152158
const char* color_code = GetPlatformColorCode(color);
153159
if (color_code) out << FormatString("\033[0;3%sm", color_code);

0 commit comments

Comments
 (0)