cba270d06dfcc6e7e481a25ec43379f4bc705fff
[mmh] / sbr / check_charset.c
1 /*
2 ** check_charset.c -- routines for character sets
3 **
4 ** This code is Copyright (c) 2002, 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 <h/mh.h>
10 #ifdef HAVE_LANGINFO_H
11 # include <langinfo.h>
12 #endif
13
14
15 /*
16 ** Get the current character set
17 */
18 char *
19 get_charset ()
20 {
21         char *charset = getenv ("MM_CHARSET");
22 #if defined(HAVE_NL_LANGINFO) && defined(CODESET)
23         if (!charset)
24                 charset = norm_charmap(nl_langinfo (CODESET));
25 #endif
26         return charset;
27 }
28
29
30 /*
31 ** Check if we can display a given character set natively.
32 ** We are passed the length of the initial part of the
33 ** string to check, since we want to allow the name of the
34 ** character set to be a substring of a larger string.
35 */
36
37 int
38 check_charset (char *str, int len)
39 {
40         static char *mm_charset = NULL;
41         static char *alt_charset = NULL;
42         static int mm_len;
43         static int alt_len;
44
45         /* Cache the name of our default character set */
46         if (!mm_charset) {
47                 if (!(mm_charset = get_charset ()))
48                         mm_charset = "US-ASCII";
49                 mm_len = strlen (mm_charset);
50
51                 /* US-ASCII is a subset of the ISO-8859-X and UTF-8 character sets */
52                 if (!strncasecmp("ISO-8859-", mm_charset, 9) ||
53                         !mh_strcasecmp("UTF-8", mm_charset)) {
54                         alt_charset = "US-ASCII";
55                         alt_len = strlen (alt_charset);
56                 }
57         }
58
59         /* Check if character set is OK */
60         if ((len == mm_len) && !strncasecmp(str, mm_charset, mm_len))
61                 return 1;
62         if (alt_charset && (len == alt_len) && !strncasecmp(str, alt_charset, alt_len))
63                 return 1;
64
65         return 0;
66 }
67
68
69 /*
70 ** Return the name of the character set we are
71 ** using for 8bit text.
72 */
73 char *
74 write_charset_8bit (void)
75 {
76         static char *mm_charset = NULL;
77
78         /*
79         ** Cache the name of the character set to
80         ** use for 8bit text.
81         */
82         if (!mm_charset && !(mm_charset = get_charset ()))
83                 mm_charset = "x-unknown";
84
85         return mm_charset;
86 }