]>
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
33 fprintf(stderr
, "Nmh was not configured with multibyte support\n");
35 #else /* MULTIBYTE_SUPPORT */
39 setlocale(LC_ALL
, "");
44 if (strcmp(argv
[1], "--dump") == 0) {
49 fprintf(stderr
, "--dump cannot be combined with "
56 * Process each argument. If it begins with "U+", then try to
57 * convert it to a Unicode codepoint. Otherwise, take each
58 * string and get the total width
61 for (i
= 1; i
< argc
; i
++) {
62 if (strncmp(argv
[i
], "U+", 2) == 0) {
64 * We're making a big assumption here that
65 * wchar_t represents a Unicode codepoint.
66 * That technically isn't valid unless the
67 * C compiler defines __STDC_ISO_10646__, but
68 * we're going to assume now that it works.
71 c
= strtoul(argv
[i
] + 2, NULL
, 16);
73 fprintf(stderr
, "Codepoint %s invalid\n",
77 printf("%d\n", wcwidth(c
));
89 fprintf(stderr
, "Usage: %s [--dump]\n", argv0
);
90 fprintf(stderr
, " %s U+XXXX [...]\n", argv0
);
91 fprintf(stderr
, " %s utf-8-sequence [...]\n", argv0
);
92 fprintf(stderr
, "Returns the column width of a Unicode codepoint "
93 "or UTF-8 character sequence\n");
94 fprintf(stderr
, "\t--dump\tDump complete width table\n");
100 getwidth(const char *string
)
103 int charlen
, charleft
= strlen(string
);
107 * In theory we should be able to use wcswidth(), but since we're
108 * testing out how the format libraries behave we'll do it a character
112 mbtowc(NULL
, NULL
, 0);
114 while (charleft
> 0) {
117 charlen
= mbtowc(&c
, string
, charleft
);
123 fprintf(stderr
, "Unable to convert string \"%s\"\n",
128 if ((clen
= wcwidth(c
)) < 0) {
129 fprintf(stderr
, "U+%04lX non-printable\n",
130 (unsigned long int) c
);
139 printf("%d\n", length
);
146 int width
, lastwidth
;
148 for (wc
= 0, low
= 1, lastwidth
= wcwidth(1); wc
< 0xffff; wc
++) {
149 width
= wcwidth(wc
+1);
150 if (width
!= lastwidth
) {
151 printf("%04lX - %04lX = %d\n", (unsigned long int) low
,
152 (unsigned long int) (wc
), lastwidth
);
159 if (width
== lastwidth
)
160 printf("%04lX - %04lX = %d\n", (unsigned long int) low
,
161 (unsigned long int) (wc
), width
);
163 #endif /* MULTIBYTE_SUPPORT */