Last active
September 10, 2025 23:58
-
-
Save GersonFeDutra/e2828efcb5d2e7c871c4ac1e239b60fe to your computer and use it in GitHub Desktop.
ANSI escape on windows!
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <print> | |
| #if defined(_WIN32) || defined(_WIN64) | |
| bool enable_ansi_escape_codes() { | |
| HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE); | |
| if (hOut == INVALID_HANDLE_VALUE) return false; | |
| DWORD dwMode = 0; | |
| if (!GetConsoleMode(hOut, &dwMode)) return false; | |
| dwMode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING; | |
| return SetConsoleMode(hOut, dwMode); | |
| } | |
| extern static bool ansi_enabled = enable_ansi_escape_codes(); | |
| // simple mapping ANSI codes for Windows Console | |
| void set_console_color(const std::string& code) { | |
| HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE); | |
| if (hOut == INVALID_HANDLE_VALUE) return; | |
| if (code == "0") { // reset | |
| SetConsoleTextAttribute(hOut, FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE); | |
| } | |
| else if (code == "30") { // black | |
| SetConsoleTextAttribute(hOut, 0); | |
| } | |
| else if (code == "31") { // red | |
| SetConsoleTextAttribute(hOut, FOREGROUND_RED); | |
| } | |
| else if (code == "32") { // green | |
| SetConsoleTextAttribute(hOut, FOREGROUND_GREEN); | |
| } | |
| else if (code == "33") { // yellow | |
| SetConsoleTextAttribute(hOut, FOREGROUND_RED | FOREGROUND_GREEN); | |
| } | |
| else if (code == "34") { // blue | |
| SetConsoleTextAttribute(hOut, FOREGROUND_BLUE); | |
| } | |
| else if (code == "35") { // magenta | |
| SetConsoleTextAttribute(hOut, FOREGROUND_RED | FOREGROUND_BLUE); | |
| } | |
| else if (code == "36") { // cyan | |
| SetConsoleTextAttribute(hOut, FOREGROUND_GREEN | FOREGROUND_BLUE); | |
| } | |
| else if (code == "37") { // white | |
| SetConsoleTextAttribute(hOut, FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE); | |
| } | |
| } | |
| template <typename... T> | |
| void _filtered_print(const char* string, T... args) { | |
| // I do not recommend to do this in real world code. Just for the lulz | |
| std::string s = std::vformat(str, std::make_format_args(args...)); | |
| size_t i = 0; | |
| while (i < s.size()) { | |
| if (s[i] == '\033' && i + 1 < s.size() && s[i+1] == '[') { | |
| size_t m = s.find('m', i+2); | |
| if (m != std::string::npos) { | |
| std::string code = s.substr(i+2, m-(i+2)); | |
| set_console_color(code); | |
| i = m + 1; | |
| continue; | |
| } | |
| } | |
| std::putchar(s[i]); | |
| ++i; | |
| } | |
| } | |
| #endif |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment