100 行 C++20 打造终端里的“彩虹代码高亮器”,无需任何第三方库!
#include <iostream>
#include <sstream>
#include <regex>
#include <unordered_map>
using namespace std::string_literals;
// 16 色经典终端配色
const std::unordered_map<std::string, std::string> KEYWORD_COLOR = {
{"alignas", "93"}, {"alignof", "93"}, {"and", "93"}, {"and_eq", "93"},
{"asm", "93"}, {"auto", "93"}, {"bitand", "93"}, {"bitor", "93"},
{"bool", "91"}, {"break", "96"}, {"case", "96"}, {"catch", "96"},
{"char", "91"}, {"char8_t", "91"}, {"char16_t", "91"}, {"char32_t", "91"},
{"class", "96"}, {"compl", "93"}, {"concept", "96"}, {"const", "93"},
{"consteval", "93"}, {"constexpr", "93"}, {"constinit", "93"},
{"const_cast", "93"}, {"continue", "96"}, {"co_await", "96"},
{"co_return", "96"}, {"co_yield", "96"}, {"decltype", "93"},
{"default", "96"}, {"delete", "96"}, {"do", "96"}, {"double", "91"},
{"dynamic_cast", "93"}, {"else", "96"}, {"enum", "96"}, {"explicit", "93"},
{"export", "96"}, {"extern", "93"}, {"false", "95"}, {"float", "91"},
{"for", "96"}, {"friend", "93"}, {"goto", "96"}, {"if", "96"},
{"inline", "93"}, {"int", "91"}, {"long", "91"}, {"mutable", "93"},
{"namespace", "96"}, {"new", "96"}, {"noexcept", "93"}, {"not", "93"},
{"not_eq", "93"}, {"nullptr", "95"}, {"operator", "96"}, {"or", "93"},
{"or_eq", "93"}, {"private", "93"}, {"protected", "93"}, {"public", "93"},
{"register", "93"}, {"reinterpret_cast", "93"}, {"requires", "96"},
{"return", "96"}, {"short", "91"}, {"signed", "91"}, {"sizeof", "93"},
{"static", "93"}, {"static_assert", "93"}, {"static_cast", "93"},
{"struct", "96"}, {"switch", "96"}, {"template", "96"}, {"this", "95"},
{"thread_local", "93"}, {"throw", "96"}, {"true", "95"}, {"try", "96"},
{"typedef", "93"}, {"typeid", "93"}, {"typename", "96"}, {"union", "96"},
{"unsigned", "91"}, {"using", "96"}, {"virtual", "93"}, {"void", "91"},
{"volatile", "93"}, {"wchar_t", "91"}, {"while", "96"}, {"xor", "93"},
{"xor_eq", "93"},
};
std::string colorize(const std::string& code) {
static const std::regex comment(R"(//.*$)", std::regex_constants::multiline);
static const std::regex str(R"("([^"\\]|\\.)*")");
static const std::regex rawStr(R"(R"([^()\s]*?\([^)]*?\)[^()\s]*?")");
static const std::regex number(R"(\b\d+\.?\d*([eE][+-]?\d+)?[fFlLuU]?\b)");
std::string s = code;
// 1. 注释 -> 绿色
s = std::regex_replace(s, comment, "\033[32m$&\033[0m");
// 2. 字符串 -> 黄色
s = std::regex_replace(s, rawStr, "\033[33m$&\033[0m");
s = std::regex_replace(s, str, "\033[33m$&\033[0m");
// 3. 数字 -> 青色
s = std::regex_replace(s, number, "\033[36m$&\033[0m");
// 4. 关键字
for (const auto& [kw, col] : KEYWORD_COLOR)
s = std::regex_replace(s, std::regex(R"(\b)" + kw + R"(\b)"),
"\033[38;5;"s + col + "m$&\033[0m"s);
return s;
}
int main() {
std::ostringstream buf;
buf << std::cin.rdbuf();
std::cout << colorize(buf.str());
return 0;
}
更多推荐
所有评论(0)