Implement PrintColored.

Thanks https://github.com/jose55 for the idea.
This commit is contained in:
Victor Zverovich 2014-02-19 13:51:23 -08:00
parent 9bb93992b6
commit 6968ef3bb3
3 changed files with 36 additions and 0 deletions

View File

@ -1462,6 +1462,11 @@ TEST(FormatIntTest, FormatDec) {
EXPECT_EQ("42", FormatDec(42ull));
}
TEST(ColorTest, PrintColored) {
fmt::PrintColored(fmt::RED, "Hello, {}!\n") << "world";
// TODO
}
template <typename T>
std::string str(const T &value) {
return fmt::str(fmt::Format("{0}") << value);

View File

@ -663,6 +663,8 @@ void fmt::BasicFormatter<Char>::DoFormat() {
writer.buffer_.append(start, s);
}
const char fmt::ColorWriter::RESET[] = "\x1b[0m";
// Explicit instantiations for char.
template void fmt::BasicWriter<char>::FormatDouble<double>(

View File

@ -1465,6 +1465,35 @@ inline Formatter<Write> Print(StringRef format) {
Formatter<Write> 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<char> &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<ColorWriter> PrintColored(Color c, StringRef format) {
Formatter<ColorWriter> f(format, ColorWriter(c));
return f;
}
}
#if _MSC_VER