Skip to content
This repository was archived by the owner on Nov 9, 2017. It is now read-only.

Commit 75288cc

Browse files
committed
Merge branch 'jx/utf8-printf-width' into maint
* jx/utf8-printf-width: Add utf8_fprintf helper that returns correct number of columns
2 parents d08d259 + c082196 commit 75288cc

File tree

3 files changed

+25
-2
lines changed

3 files changed

+25
-2
lines changed

parse-options.c

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
#include "cache.h"
44
#include "commit.h"
55
#include "color.h"
6+
#include "utf8.h"
67

78
static int parse_options_usage(struct parse_opt_ctx_t *ctx,
89
const char * const *usagestr,
@@ -491,7 +492,7 @@ static int usage_argh(const struct option *opts, FILE *outfile)
491492
s = literal ? "[%s]" : "[<%s>]";
492493
else
493494
s = literal ? " %s" : " <%s>";
494-
return fprintf(outfile, s, opts->argh ? _(opts->argh) : _("..."));
495+
return utf8_fprintf(outfile, s, opts->argh ? _(opts->argh) : _("..."));
495496
}
496497

497498
#define USAGE_OPTS_WIDTH 24
@@ -550,7 +551,7 @@ static int usage_with_options_internal(struct parse_opt_ctx_t *ctx,
550551
if (opts->long_name)
551552
pos += fprintf(outfile, "--%s", opts->long_name);
552553
if (opts->type == OPTION_NUMBER)
553-
pos += fprintf(outfile, "-NUM");
554+
pos += utf8_fprintf(outfile, _("-NUM"));
554555

555556
if ((opts->flags & PARSE_OPT_LITERAL_ARGHELP) ||
556557
!(opts->flags & PARSE_OPT_NOARG))

utf8.c

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -429,6 +429,27 @@ int same_encoding(const char *src, const char *dst)
429429
return !strcasecmp(src, dst);
430430
}
431431

432+
/*
433+
* Wrapper for fprintf and returns the total number of columns required
434+
* for the printed string, assuming that the string is utf8.
435+
*/
436+
int utf8_fprintf(FILE *stream, const char *format, ...)
437+
{
438+
struct strbuf buf = STRBUF_INIT;
439+
va_list arg;
440+
int columns;
441+
442+
va_start(arg, format);
443+
strbuf_vaddf(&buf, format, arg);
444+
va_end(arg);
445+
446+
columns = fputs(buf.buf, stream);
447+
if (0 <= columns) /* keep the error from the I/O */
448+
columns = utf8_strwidth(buf.buf);
449+
strbuf_release(&buf);
450+
return columns;
451+
}
452+
432453
/*
433454
* Given a buffer and its encoding, return it re-encoded
434455
* with iconv. If the conversion fails, returns NULL.

utf8.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ int utf8_strwidth(const char *string);
88
int is_utf8(const char *text);
99
int is_encoding_utf8(const char *name);
1010
int same_encoding(const char *, const char *);
11+
int utf8_fprintf(FILE *, const char *, ...);
1112

1213
void strbuf_add_wrapped_text(struct strbuf *buf,
1314
const char *text, int indent, int indent2, int width);

0 commit comments

Comments
 (0)