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.
This commit is contained in:
Matthias Clasen
2019-01-08 08:17:05 -05:00
parent a3d109de8f
commit 6c733ddc6a
2 changed files with 50 additions and 1 deletions

View File

@@ -21,7 +21,7 @@
#include "config.h"
#include <glib/gi18n.h>
#include <glib/gprintf.h>
#include <gio/gunixinputstream.h>
#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");
}
}

View File

@@ -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__ */