]>
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 setlocale(LC_ALL
, "");
46 if (strcmp(argv
[1], "--dump") == 0) {
51 fprintf(stderr
, "--dump cannot be combined with "
58 * Process each argument. If it begins with "U+", then try to
59 * convert it to a Unicode codepoint. Otherwise, take each
60 * string and get the total width
63 for (i
= 1; i
< argc
; i
++) {
64 if (strncmp(argv
[i
], "U+", 2) == 0) {
66 * We're making a big assumption here that
67 * wchar_t represents a Unicode codepoint.
68 * That technically isn't valid unless the
69 * C compiler defines __STDC_ISO_10646__, but
70 * we're going to assume now that it works.
73 c
= strtoul(argv
[i
] + 2, NULL
, 16);
75 fprintf(stderr
, "Codepoint %s invalid\n",
79 printf("%d\n", wcwidth(c
));
91 fprintf(stderr
, "Usage: %s [--dump]\n", argv0
);
92 fprintf(stderr
, " %s U+XXXX [...]\n", argv0
);
93 fprintf(stderr
, " %s utf-8-sequence [...]\n", argv0
);
94 fprintf(stderr
, "Returns the column width of a Unicode codepoint "
95 "or UTF-8 character sequence\n");
96 fprintf(stderr
, "\t--dump\tDump complete width table\n");
102 getwidth(const char *string
)
105 int charlen
, charleft
= strlen(string
);
109 * In theory we should be able to use wcswidth(), but since we're
110 * testing out how the format libraries behave we'll do it a character
114 mbtowc(NULL
, NULL
, 0);
116 while (charleft
> 0) {
119 charlen
= mbtowc(&c
, string
, charleft
);
125 fprintf(stderr
, "Unable to convert string \"%s\"\n",
130 if ((clen
= wcwidth(c
)) < 0) {
131 fprintf(stderr
, "U+%04lX non-printable\n",
132 (unsigned long int) c
);
141 printf("%d\n", length
);
148 int width
, lastwidth
;
150 for (wc
= 0, low
= 1, lastwidth
= wcwidth(1); wc
< 0xffff; wc
++) {
151 width
= wcwidth(wc
+1);
152 if (width
!= lastwidth
) {
153 printf("%04lX - %04lX = %d\n", (unsigned long int) low
,
154 (unsigned long int) (wc
), lastwidth
);
161 if (width
== lastwidth
)
162 printf("%04lX - %04lX = %d\n", (unsigned long int) low
,
163 (unsigned long int) (wc
), width
);
164 #endif /* MULTIBYTE_SUPPORT */