From 6c733ddc6adda34ce2a167eebb830096c199890e Mon Sep 17 00:00:00 2001 From: Matthias Clasen Date: Tue, 8 Jan 2019 08:17:05 -0500 Subject: [PATCH] Add a utility for printing lines wrapped This is a variant of g_print that word-wraps lines to a given width, while respecting pre-existing line breaks. --- app/flatpak-builtins-utils.c | 49 +++++++++++++++++++++++++++++++++++- app/flatpak-builtins-utils.h | 2 ++ 2 files changed, 50 insertions(+), 1 deletion(-) diff --git a/app/flatpak-builtins-utils.c b/app/flatpak-builtins-utils.c index 421597e20..885fabdde 100644 --- a/app/flatpak-builtins-utils.c +++ b/app/flatpak-builtins-utils.c @@ -21,7 +21,7 @@ #include "config.h" #include - +#include #include #include "flatpak-chain-input-stream-private.h" @@ -1103,3 +1103,50 @@ print_aligned (int len, const char *title, const char *value) g_print ("%s%*s%s%s %s\n", on, len - (int)g_utf8_strlen (title, -1), "", title, off, value); } + +static void +print_line_wrapped (int cols, const char *line) +{ + g_auto(GStrv) words = g_strsplit (line, " ", 0); + int i; + int col = 0; + + for (i = 0; words[i]; i++) + { + int len = g_utf8_strlen (words[i], -1); + int space = col > 0; + + if (col + space + len >= cols) + { + g_print ("\n%s", words[i]); + col = len; + } + else + { + g_print ("%*s%s", space, "", words[i]); + col = col + space + len; + } + } +} + +void +print_wrapped (int cols, + const char *text, + ...) +{ + va_list args; + g_autofree char *msg = NULL; + g_auto(GStrv) lines = NULL; + int i; + + va_start (args, text); + g_vasprintf (&msg, text, args); + va_end (args); + + lines = g_strsplit (msg, "\n", 0); + for (i = 0; lines[i]; i++) + { + print_line_wrapped (cols, lines[i]); + g_print ("\n"); + } +} diff --git a/app/flatpak-builtins-utils.h b/app/flatpak-builtins-utils.h index 56dbe9f4b..f27a30f47 100644 --- a/app/flatpak-builtins-utils.h +++ b/app/flatpak-builtins-utils.h @@ -149,4 +149,6 @@ const char *as_app_get_localized_name (AsApp *app); const char *as_app_get_localized_comment (AsApp *app); const char *as_app_get_version (AsApp *app); +void print_wrapped (int columns, const char *text, ...) G_GNUC_PRINTF (2, 3); + #endif /* __FLATPAK_BUILTINS_UTILS_H__ */