Add utf8_fprintf helper that returns correct number of columns

Since command usages can be translated, they may include utf-8 encoded strings, and the output in console may not align well any more. This is because strlen() is different from strwidth() on utf-8 strings. A wrapper utf8_fprintf() can help to return the correct number of columns required. Signed-off-by: Jiang Xin <worldhello.net@gmail.com> Signed-off-by: Nguyễn Thái Ngọc Duy <pclouds@gmail.com> Reviewed-by: Torsten Bögershausen <tboegi@web.de> Signed-off-by: Junio C Hamano <gitster@pobox.com>

Jiang Xin committed Feb 9, 2013 at 14:31 UTC c082196575e13dd5960031f213b20e2df989ca18
3 files changed +25 -2
parse-options.c
+3 -2
@@ -3,6 +3,7 @@
3 #include "cache.h"
4 #include "commit.h"
5 #include "color.h"
6 +#include "utf8.h"
7
8 static int parse_options_usage(struct parse_opt_ctx_t *ctx,
9 const char * const *usagestr,
@@ -491,7 +492,7 @@ static int usage_argh(const struct option *opts, FILE *outfile)
492 s = literal ? "[%s]" : "[<%s>]";
493 else
494 s = literal ? " %s" : " <%s>";
494 - return fprintf(outfile, s, opts->argh ? _(opts->argh) : _("..."));
495 + return utf8_fprintf(outfile, s, opts->argh ? _(opts->argh) : _("..."));
496 }
497
498 #define USAGE_OPTS_WIDTH 24
@@ -550,7 +551,7 @@ static int usage_with_options_internal(struct parse_opt_ctx_t *ctx,
551 if (opts->long_name)
552 pos += fprintf(outfile, "--%s", opts->long_name);
553 if (opts->type == OPTION_NUMBER)
553 - pos += fprintf(outfile, "-NUM");
554 + pos += utf8_fprintf(outfile, _("-NUM"));
555
556 if ((opts->flags & PARSE_OPT_LITERAL_ARGHELP) ||
557 !(opts->flags & PARSE_OPT_NOARG))
utf8.c
+21
@@ -430,6 +430,27 @@ int same_encoding(const char *src, const char *dst)
430 return !strcasecmp(src, dst);
431 }
432
433 +/*
434 + * Wrapper for fprintf and returns the total number of columns required
435 + * for the printed string, assuming that the string is utf8.
436 + */
437 +int utf8_fprintf(FILE *stream, const char *format, ...)
438 +{
439 + struct strbuf buf = STRBUF_INIT;
440 + va_list arg;
441 + int columns;
442 +
443 + va_start(arg, format);
444 + strbuf_vaddf(&buf, format, arg);
445 + va_end(arg);
446 +
447 + columns = fputs(buf.buf, stream);
448 + if (0 <= columns) /* keep the error from the I/O */
449 + columns = utf8_strwidth(buf.buf);
450 + strbuf_release(&buf);
451 + return columns;
452 +}
453 +
454 /*
455 * Given a buffer and its encoding, return it re-encoded
456 * with iconv. If the conversion fails, returns NULL.
utf8.h
+1
@@ -8,6 +8,7 @@ int utf8_strwidth(const char *string);
8 int is_utf8(const char *text);
9 int is_encoding_utf8(const char *name);
10 int same_encoding(const char *, const char *);
11 +int utf8_fprintf(FILE *, const char *, ...);
12
13 int strbuf_add_wrapped_text(struct strbuf *buf,
14 const char *text, int indent, int indent2, int width);