Commit 6968ef3b authored by Victor Zverovich's avatar Victor Zverovich

Implement PrintColored.

Thanks https://github.com/jose55 for the idea.
parent 9bb93992
...@@ -1462,6 +1462,11 @@ TEST(FormatIntTest, FormatDec) { ...@@ -1462,6 +1462,11 @@ TEST(FormatIntTest, FormatDec) {
EXPECT_EQ("42", FormatDec(42ull)); EXPECT_EQ("42", FormatDec(42ull));
} }
TEST(ColorTest, PrintColored) {
fmt::PrintColored(fmt::RED, "Hello, {}!\n") << "world";
// TODO
}
template <typename T> template <typename T>
std::string str(const T &value) { std::string str(const T &value) {
return fmt::str(fmt::Format("{0}") << value); return fmt::str(fmt::Format("{0}") << value);
......
...@@ -663,6 +663,8 @@ void fmt::BasicFormatter<Char>::DoFormat() { ...@@ -663,6 +663,8 @@ void fmt::BasicFormatter<Char>::DoFormat() {
writer.buffer_.append(start, s); writer.buffer_.append(start, s);
} }
const char fmt::ColorWriter::RESET[] = "\x1b[0m";
// Explicit instantiations for char. // Explicit instantiations for char.
template void fmt::BasicWriter<char>::FormatDouble<double>( template void fmt::BasicWriter<char>::FormatDouble<double>(
......
...@@ -1465,6 +1465,35 @@ inline Formatter<Write> Print(StringRef format) { ...@@ -1465,6 +1465,35 @@ inline Formatter<Write> Print(StringRef format) {
Formatter<Write> f(format); Formatter<Write> f(format);
return f; 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 #if _MSC_VER
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment