From 6968ef3bb3ce86ef5f2f0a8effbf8ae2270d6cda Mon Sep 17 00:00:00 2001 From: Victor Zverovich Date: Wed, 19 Feb 2014 13:51:23 -0800 Subject: [PATCH] Implement PrintColored. Thanks https://github.com/jose55 for the idea. --- format-test.cc | 5 +++++ format.cc | 2 ++ format.h | 29 +++++++++++++++++++++++++++++ 3 files changed, 36 insertions(+) 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