From ca3a9cb73acda224f53a64bfec294a34a7b66994 Mon Sep 17 00:00:00 2001 From: Antoine Hoarau <703240+ahoarau@users.noreply.github.com> Date: Mon, 18 May 2026 08:50:28 +0200 Subject: [PATCH] Add println functions for formatted output with color support --- include/fmt/color.h | 36 ++++++++++++++++++++++++++++++++++++ test/color-test.cc | 12 ++++++++++++ 2 files changed, 48 insertions(+) diff --git a/include/fmt/color.h b/include/fmt/color.h index 153784f5..7d809e60 100644 --- a/include/fmt/color.h +++ b/include/fmt/color.h @@ -528,6 +528,42 @@ void print(text_style ts, format_string fmt, T&&... args) { return print(stdout, ts, fmt, std::forward(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 +void println(FILE* f, text_style ts, format_string fmt, T&&... args) { + vprintln(f, ts, fmt.str, vargs{{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 +void println(text_style ts, format_string fmt, T&&... args) { + return println(stdout, ts, fmt, std::forward(args)...); +} + inline auto vformat(text_style ts, string_view fmt, format_args args) -> std::string { auto buf = memory_buffer(); diff --git a/test/color-test.cc b/test/color-test.cc index 45d8cd92..67ce1833 100644 --- a/test/color-test.cc +++ b/test/color-test.cc @@ -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"); +}