diff --git a/format-test.cc b/format-test.cc index 40a4fbbd..b9ea8ed0 100644 --- a/format-test.cc +++ b/format-test.cc @@ -1462,6 +1462,11 @@ TEST(FormatIntTest, FormatDec) { EXPECT_EQ("42", FormatDec(42ull)); } +TEST(ColorTest, PrintColored) { + fmt::PrintColored(fmt::RED, "Hello, {}!\n") << "world"; + // TODO +} + template std::string str(const T &value) { return fmt::str(fmt::Format("{0}") << value); diff --git a/format.cc b/format.cc index 30d10f77..f191e3a4 100644 --- a/format.cc +++ b/format.cc @@ -663,6 +663,8 @@ void fmt::BasicFormatter::DoFormat() { writer.buffer_.append(start, s); } +const char fmt::ColorWriter::RESET[] = "\x1b[0m"; + // Explicit instantiations for char. template void fmt::BasicWriter::FormatDouble( diff --git a/format.h b/format.h index 07eb5a17..eaf9f5c0 100644 --- a/format.h +++ b/format.h @@ -1465,6 +1465,35 @@ inline Formatter Print(StringRef format) { Formatter f(format); return f; } + +enum Color {BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE}; + +/** A formatting action that writes colored output to stdout. */ +class ColorWriter { + private: + Color color_; + static const char RESET[]; + + public: + explicit ColorWriter(Color c) : color_(c) {} + + /** Writes the colored output to stdout. */ + void operator()(const BasicWriter &w) const { + char escape[] = "\x1b[30m"; + escape[3] = '0' + color_; + std::fputs(escape, stdout); + std::fwrite(w.data(), 1, w.size(), stdout); + std::fputs(RESET, stdout); + } +}; + +// Formats a string and prints it to stdout with the given color. +// Example: +// PrintColored(fmt::RED, "Elapsed time: {0:.2f} seconds") << 1.23; +inline Formatter PrintColored(Color c, StringRef format) { + Formatter f(format, ColorWriter(c)); + return f; +} } #if _MSC_VER