]>
diplodocus.org Git - nmh/blob - test/getcwidth.c
2 * getcwidth - Get the OS's idea of the width of Unicode codepoints
4 * This code is Copyright (c) 2013, by the authors of nmh. See the
5 * COPYRIGHT file in the root directory of the nmh distribution for
6 * complete copyright information.
18 #ifdef MULTIBYTE_SUPPORT
23 #ifdef MULTIBYTE_SUPPORT
24 static void usage(char *);
25 static void dumpwidth(void);
26 static void getwidth(const char *);
27 #endif /* MULTIBYTE_SUPPORT */
30 main(int argc
, char *argv
[])
32 #ifndef MULTIBYTE_SUPPORT
35 fprintf(stderr
, "Nmh was not configured with multibyte support\n");
37 #else /* MULTIBYTE_SUPPORT */
41 if (! setlocale(LC_ALL
, "")) {
42 fprintf(stderr
, "setlocale failed, check your LC_ALL, "
43 "LC_CTYPE, and LANG environment variables\n");
49 if (strcmp(argv
[1], "--dump") == 0) {
54 fprintf(stderr
, "--dump cannot be combined with "
61 * Process each argument. If it begins with "U+", then try to
62 * convert it to a Unicode codepoint. Otherwise, take each
63 * string and get the total width
66 for (i
= 1; i
< argc
; i
++) {
67 if (strncmp(argv
[i
], "U+", 2) == 0) {
69 * We're making a big assumption here that
70 * wchar_t represents a Unicode codepoint.
71 * That technically isn't valid unless the
72 * C compiler defines __STDC_ISO_10646__, but
73 * we're going to assume now that it works.
76 c
= strtoul(argv
[i
] + 2, NULL
, 16);
78 fprintf(stderr
, "Codepoint %s invalid\n",
82 printf("%d\n", wcwidth(c
));
94 fprintf(stderr
, "Usage: %s [--dump]\n", argv0
);
95 fprintf(stderr
, " %s U+XXXX [...]\n", argv0
);
96 fprintf(stderr
, " %s utf-8-sequence [...]\n", argv0
);
97 fprintf(stderr
, "Returns the column width of a Unicode codepoint "
98 "or UTF-8 character sequence\n");
99 fprintf(stderr
, "\t--dump\tDump complete width table\n");
105 getwidth(const char *string
)
108 int charlen
, charleft
= strlen(string
);
112 * In theory we should be able to use wcswidth(), but since we're
113 * testing out how the format libraries behave we'll do it a character
117 if (mbtowc(NULL
, NULL
, 0)) {}
119 while (charleft
> 0) {
122 charlen
= mbtowc(&c
, string
, charleft
);
128 fprintf(stderr
, "Unable to convert string \"%s\"\n",
133 if ((clen
= wcwidth(c
)) < 0) {
134 fprintf(stderr
, "U+%04lX non-printable\n",
135 (unsigned long int) c
);
144 printf("%d\n", length
);
151 int width
, lastwidth
;
153 for (wc
= 0, low
= 1, lastwidth
= wcwidth(1); wc
< 0xffff; wc
++) {
154 width
= wcwidth(wc
+1);
155 if (width
!= lastwidth
) {
156 printf("%04lX - %04lX = %d\n", (unsigned long int) low
,
157 (unsigned long int) (wc
), lastwidth
);
164 if (width
== lastwidth
)
165 printf("%04lX - %04lX = %d\n", (unsigned long int) low
,
166 (unsigned long int) (wc
), width
);
167 #endif /* MULTIBYTE_SUPPORT */