From 0102101acc568682f7edb583d64f9a3d5a231ae1 Mon Sep 17 00:00:00 2001 From: Alex Guteniev Date: Fri, 7 Jan 2022 02:10:53 +0200 Subject: [PATCH] Make colored print handle UTF-8 (#2701) * Fix #2681 - Make detail::print handle UTF-8 * Okay, let's do this Windows-only * drop extra \0 * yay we can throw! --- include/fmt/color.h | 29 +++++++++++++++++------------ 1 file changed, 17 insertions(+), 12 deletions(-) diff --git a/include/fmt/color.h b/include/fmt/color.h index dfbe4829..0d0204f3 100644 --- a/include/fmt/color.h +++ b/include/fmt/color.h @@ -474,26 +474,27 @@ FMT_CONSTEXPR ansi_color_escape make_emphasis(emphasis em) FMT_NOEXCEPT { return ansi_color_escape(em); } -template -inline void fputs(const Char* chars, FILE* stream) FMT_NOEXCEPT { - std::fputs(chars, stream); +template inline void fputs(const Char* chars, FILE* stream) { + int result = std::fputs(chars, stream); + if (result < 0) + FMT_THROW(system_error(errno, FMT_STRING("cannot write to file"))); } -template <> -inline void fputs(const wchar_t* chars, FILE* stream) FMT_NOEXCEPT { - std::fputws(chars, stream); +template <> inline void fputs(const wchar_t* chars, FILE* stream) { + int result = std::fputws(chars, stream); + if (result < 0) + FMT_THROW(system_error(errno, FMT_STRING("cannot write to file"))); } -template inline void reset_color(FILE* stream) FMT_NOEXCEPT { +template inline void reset_color(FILE* stream) { fputs("\x1b[0m", stream); } -template <> inline void reset_color(FILE* stream) FMT_NOEXCEPT { +template <> inline void reset_color(FILE* stream) { fputs(L"\x1b[0m", stream); } -template -inline void reset_color(buffer& buffer) FMT_NOEXCEPT { +template inline void reset_color(buffer& buffer) { auto reset_color = string_view("\x1b[0m"); buffer.append(reset_color.begin(), reset_color.end()); } @@ -529,8 +530,12 @@ void vprint(std::FILE* f, const text_style& ts, const S& format, basic_format_args>> args) { basic_memory_buffer buf; detail::vformat_to(buf, ts, to_string_view(format), args); - buf.push_back(Char(0)); - detail::fputs(buf.data(), f); + if (detail::is_utf8()) { + detail::print(f, basic_string_view(buf.begin(), buf.size())); + } else { + buf.push_back(Char(0)); + detail::fputs(buf.data(), f); + } } /**