Add println functions for formatted output with color support (#4782)

This commit is contained in:
ahoarau 2026-05-25 17:30:36 +02:00 committed by GitHub
parent 93e26fa578
commit 0acf106c52
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 48 additions and 0 deletions

View File

@ -528,6 +528,42 @@ void print(text_style ts, format_string<T...> fmt, T&&... args) {
return print(stdout, ts, fmt, std::forward<T>(args)...);
}
inline void vprintln(FILE* f, text_style ts, string_view fmt,
format_args args) {
auto buf = memory_buffer();
detail::vformat_to(buf, ts, fmt, args);
buf.push_back('\n');
print(f, FMT_STRING("{}"), string_view(buf.begin(), buf.size()));
}
/**
* Formats a string and prints it to the specified file stream followed by a
* newline, using ANSI escape sequences to specify text formatting.
*
* **Example**:
*
* fmt::println(fmt::emphasis::bold | fg(fmt::color::red),
* "Elapsed time: {0:.2f} seconds", 1.23);
*/
template <typename... T>
void println(FILE* f, text_style ts, format_string<T...> fmt, T&&... args) {
vprintln(f, ts, fmt.str, vargs<T...>{{args...}});
}
/**
* Formats a string and prints it to stdout followed by a newline, using ANSI
* escape sequences to specify text formatting.
*
* **Example**:
*
* fmt::println(fmt::emphasis::bold | fg(fmt::color::red),
* "Elapsed time: {0:.2f} seconds", 1.23);
*/
template <typename... T>
void println(text_style ts, format_string<T...> fmt, T&&... args) {
return println(stdout, ts, fmt, std::forward<T>(args)...);
}
inline auto vformat(text_style ts, string_view fmt, format_args args)
-> std::string {
auto buf = memory_buffer();

View File

@ -136,3 +136,15 @@ TEST(color_test, print) {
EXPECT_WRITE(stdout, fmt::print(fg(fmt::rgb(255, 20, 30)), "rgb(255,20,30)"),
"\x1b[38;2;255;020;030mrgb(255,20,30)\x1b[0m");
}
TEST(color_test, println) {
EXPECT_WRITE(stdout,
fmt::println(fg(fmt::rgb(255, 20, 30)), "rgb(255,20,30)"),
"\x1b[38;2;255;020;030mrgb(255,20,30)\x1b[0m\n");
EXPECT_WRITE(stdout, fmt::println(fmt::emphasis::bold, "bold"),
"\x1b[1mbold\x1b[0m\n");
EXPECT_WRITE(
stdout,
fmt::println(fg(fmt::color::blue) | fmt::emphasis::bold, "blue/bold"),
"\x1b[1m\x1b[38;2;000;000;255mblue/bold\x1b[0m\n");
}