-
Notifications
You must be signed in to change notification settings - Fork 2
/
coloredconsole.cpp
96 lines (80 loc) · 2.96 KB
/
coloredconsole.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#include "stdafx.h"
#include <algorithm>
#include "coloredconsole.h"
#if !defined(__linux__) && !((defined(__APPLE__) && defined(__MACH__)))
#include <windows.h>
#endif
namespace coloredconsole
{
#if !defined(__linux__) && !((defined(__APPLE__) && defined(__MACH__)))
/// <summary>
/// RAII for set console output color in windows
/// </summary>
class WindowsConsoleColor final
{
WindowsConsoleColor(const WindowsConsoleColor&) = delete;
WindowsConsoleColor(WindowsConsoleColor&&) = delete;
WindowsConsoleColor& operator =(const WindowsConsoleColor&) = delete;
WindowsConsoleColor& operator =(WindowsConsoleColor&&) = delete;
public:
/// <summary>
/// set color
/// </summary>
/// <param name="color">color to set</param>
WindowsConsoleColor(WORD color): hConsole_(GetStdHandle(STD_OUTPUT_HANDLE))
{
CONSOLE_SCREEN_BUFFER_INFO csbi;
GetConsoleScreenBufferInfo(hConsole_, &csbi);
originalColor_ = csbi.wAttributes;
SetConsoleTextAttribute(hConsole_, color);
}
/// <summary>
/// set color back
/// </summary>
~WindowsConsoleColor()
{
SetConsoleTextAttribute(hConsole_, originalColor_);
}
protected:
HANDLE hConsole_;
WORD originalColor_;
};
#endif
void ColorizeWords(std::ostream& os, const std::string_view sv)
{
static const std::string_view errorSV = "ERROR";
static const std::string_view warningSV = "Warning";
size_t pos = 0;
while (pos < sv.size())
{
size_t errorPos = sv.find(errorSV, pos);
size_t warningPos = sv.find(warningSV, pos);
if (errorPos != std::string_view::npos && (warningPos == std::string_view::npos || errorPos < warningPos))
{
os << sv.substr(pos, errorPos - pos);
#if defined(__linux__) || ((defined(__APPLE__) && defined(__MACH__)))
os << "\033[1;31m" << errorSV << "\033[0m";
#else
WindowsConsoleColor color(FOREGROUND_RED | FOREGROUND_INTENSITY);
os << errorSV;
#endif
pos = errorPos + errorSV.size();
continue;
}
if (warningPos != std::string_view::npos)
{
os << sv.substr(pos, warningPos - pos);
#if defined(__linux__) || ((defined(__APPLE__) && defined(__MACH__)))
os << "\033[1;33m" << warningSV << "\033[0m";
#else
WindowsConsoleColor color(FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_INTENSITY);
os << warningSV;
#endif
pos = warningPos + warningSV.size();
continue;
}
os << sv.substr(pos, sv.size() - pos);
pos = sv.size();
} // while (pos < sv.size())
}// void ColorizeWords(std::ostream& os, const std::string_view sv)
} // namespace coloredconsole