]> diplodocus.org Git - nmh/blob - test/getcwidth.c
f2a2ac69e5207dfd9375644f402d42f282613f44
[nmh] / test / getcwidth.c
1 /*
2 * getcwidth - Get the OS's idea of the width of a combining character
3 *
4 * This code is Copyright (c) 2012, by the authors of nmh. See the
5 * COPYRIGHT file in the root directory of the nmh distribution for
6 * complete copyright information.
7 */
8
9 #include <stdio.h>
10 #include <stdlib.h>
11 #include <string.h>
12 #include <errno.h>
13
14 #ifdef HAVE_CONFIG_H
15 #include <config.h>
16 #endif
17
18 #ifdef MULTIBYTE_SUPPORT
19 #include <locale.h>
20 #include <wchar.h>
21 #endif
22
23 static void usage(char *);
24 static void dumpwidth(void);
25
26 int
27 main(int argc, char *argv[])
28 {
29 wchar_t c;
30 int charlen;
31 char *p;
32
33 /*
34 * This is the UTF-8 for "n" + U+0308 (Combining Diaeresis)
35 */
36
37 unsigned char string[] = "n\xcc\x88";
38
39 setlocale(LC_ALL, "");
40
41 if (argc > 2)
42 usage(argv[0]);
43
44 if (argc == 2) {
45 if (strcmp(argv[1], "--dump") == 0) {
46 dumpwidth();
47 exit(0);
48 } else {
49 usage(argv[0]);
50 }
51 }
52
53 #ifndef MULTIBYTE_SUPPORT
54 fprintf(stderr, "Nmh was not configured with multibyte support\n");
55 exit(1);
56 #else /* MULTIBYTE_SUPPORT */
57 /*
58 * It's not clear to me that we can just call mbtowc() with a
59 * combining character; just to be safe, feed it in a base
60 * character first.
61 */
62
63 mbtowc(NULL, NULL, 0);
64
65 charlen = mbtowc(&c, (char *) string, strlen((char *) string));
66
67 if (charlen != 1) {
68 fprintf(stderr, "We expected a beginning character length "
69 "of 1, got %d instead\n", charlen);
70 exit(1);
71 }
72
73 p = (char *) (string + charlen);
74
75 charlen = mbtowc(&c, p, strlen(p));
76
77 if (charlen != 2) {
78 fprintf(stderr, "We expected a multibyte character length "
79 "of 2, got %d instead\n", charlen);
80 fprintf(stderr, "Are you using a UTF-8 locale?\n");
81 exit(1);
82 }
83
84 printf("%d\n", wcwidth(c));
85
86 exit(0);
87 #endif /* MULTIBYTE_SUPPORT */
88 }
89
90 static void
91 usage(char *argv0)
92 {
93 fprintf(stderr, "Usage: %s [--dump]\n", argv0);
94 fprintf(stderr, "Returns the column width of a UTF-8 combining "
95 "multibyte character\n");
96 fprintf(stderr, "\t--dump\tDump complete width table\n");
97
98 exit(1);
99 }
100
101 static void
102 dumpwidth(void)
103 {
104 #ifndef MULTIBYTE_SUPPORT
105 fprintf(stderr, "Nmh was not configured with multibyte support\n");
106 exit(1);
107 #else /* MULTIBYTE_SUPPORT */
108 wchar_t wc, low;
109 int width, lastwidth;
110
111 for (wc = low = 1, lastwidth = wcwidth(wc); wc <= 0xffff; wc++) {
112 width = wcwidth(wc);
113 if (width != lastwidth) {
114 printf("%04X - %04X = %d\n", low, wc - 1, lastwidth);
115 low = wc;
116 }
117 lastwidth = width;
118 }
119
120 width = wcwidth(wc - 1);
121 if (width == lastwidth)
122 printf("%04X - %04X = %d\n", low, wc - 1, width);
123 #endif /* MULTIBYTE_SUPPORT */
124 }