maint: update copyright
[gnulib.git] / lib / setlocale.c
1 /* Set the current locale.
2    Copyright (C) 2009, 2011-2014 Free Software Foundation, Inc.
3
4    This program is free software: you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation; either version 3 of the License, or
7    (at your option) any later version.
8
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13
14    You should have received a copy of the GNU General Public License
15    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
16
17 /* Written by Bruno Haible <bruno@clisp.org>, 2009.  */
18
19 #include <config.h>
20
21 /* Override setlocale() so that when the default locale is requested
22    (locale = ""), the environment variables LC_ALL, LC_*, and LANG are
23    considered.
24    Also include all the functionality from libintl's setlocale() override.  */
25
26 /* Please keep this file in sync with
27    gettext/gettext-runtime/intl/setlocale.c !  */
28
29 /* Specification.  */
30 #include <locale.h>
31
32 #include <stdlib.h>
33 #include <string.h>
34
35 #include "localename.h"
36
37 #if 1
38
39 # undef setlocale
40
41 /* Return string representation of locale category CATEGORY.  */
42 static const char *
43 category_to_name (int category)
44 {
45   const char *retval;
46
47   switch (category)
48   {
49   case LC_COLLATE:
50     retval = "LC_COLLATE";
51     break;
52   case LC_CTYPE:
53     retval = "LC_CTYPE";
54     break;
55   case LC_MONETARY:
56     retval = "LC_MONETARY";
57     break;
58   case LC_NUMERIC:
59     retval = "LC_NUMERIC";
60     break;
61   case LC_TIME:
62     retval = "LC_TIME";
63     break;
64   case LC_MESSAGES:
65     retval = "LC_MESSAGES";
66     break;
67   default:
68     /* If you have a better idea for a default value let me know.  */
69     retval = "LC_XXX";
70   }
71
72   return retval;
73 }
74
75 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
76
77 /* The native Windows setlocale() function expects locale names of the form
78    "German" or "German_Germany" or "DEU", but not "de" or "de_DE".  We need
79    to convert the names from the form with ISO 639 language code and ISO 3166
80    country code to the form with English names or with three-letter identifier.
81    The three-letter identifiers known by a Windows XP SP2 or SP3 are:
82      AFK  Afrikaans_South Africa.1252
83      ARA  Arabic_Saudi Arabia.1256
84      ARB  Arabic_Lebanon.1256
85      ARE  Arabic_Egypt.1256
86      ARG  Arabic_Algeria.1256
87      ARH  Arabic_Bahrain.1256
88      ARI  Arabic_Iraq.1256
89      ARJ  Arabic_Jordan.1256
90      ARK  Arabic_Kuwait.1256
91      ARL  Arabic_Libya.1256
92      ARM  Arabic_Morocco.1256
93      ARO  Arabic_Oman.1256
94      ARQ  Arabic_Qatar.1256
95      ARS  Arabic_Syria.1256
96      ART  Arabic_Tunisia.1256
97      ARU  Arabic_U.A.E..1256
98      ARY  Arabic_Yemen.1256
99      AZE  Azeri (Latin)_Azerbaijan.1254
100      BEL  Belarusian_Belarus.1251
101      BGR  Bulgarian_Bulgaria.1251
102      BSB  Bosnian_Bosnia and Herzegovina.1250
103      BSC  Bosnian (Cyrillic)_Bosnia and Herzegovina.1250  (wrong encoding!)
104      CAT  Catalan_Spain.1252
105      CHH  Chinese_Hong Kong S.A.R..950
106      CHI  Chinese_Singapore.936
107      CHS  Chinese_People's Republic of China.936
108      CHT  Chinese_Taiwan.950
109      CSY  Czech_Czech Republic.1250
110      CYM  Welsh_United Kingdom.1252
111      DAN  Danish_Denmark.1252
112      DEA  German_Austria.1252
113      DEC  German_Liechtenstein.1252
114      DEL  German_Luxembourg.1252
115      DES  German_Switzerland.1252
116      DEU  German_Germany.1252
117      ELL  Greek_Greece.1253
118      ENA  English_Australia.1252
119      ENB  English_Caribbean.1252
120      ENC  English_Canada.1252
121      ENG  English_United Kingdom.1252
122      ENI  English_Ireland.1252
123      ENJ  English_Jamaica.1252
124      ENL  English_Belize.1252
125      ENP  English_Republic of the Philippines.1252
126      ENS  English_South Africa.1252
127      ENT  English_Trinidad and Tobago.1252
128      ENU  English_United States.1252
129      ENW  English_Zimbabwe.1252
130      ENZ  English_New Zealand.1252
131      ESA  Spanish_Panama.1252
132      ESB  Spanish_Bolivia.1252
133      ESC  Spanish_Costa Rica.1252
134      ESD  Spanish_Dominican Republic.1252
135      ESE  Spanish_El Salvador.1252
136      ESF  Spanish_Ecuador.1252
137      ESG  Spanish_Guatemala.1252
138      ESH  Spanish_Honduras.1252
139      ESI  Spanish_Nicaragua.1252
140      ESL  Spanish_Chile.1252
141      ESM  Spanish_Mexico.1252
142      ESN  Spanish_Spain.1252
143      ESO  Spanish_Colombia.1252
144      ESP  Spanish_Spain.1252
145      ESR  Spanish_Peru.1252
146      ESS  Spanish_Argentina.1252
147      ESU  Spanish_Puerto Rico.1252
148      ESV  Spanish_Venezuela.1252
149      ESY  Spanish_Uruguay.1252
150      ESZ  Spanish_Paraguay.1252
151      ETI  Estonian_Estonia.1257
152      EUQ  Basque_Spain.1252
153      FAR  Farsi_Iran.1256
154      FIN  Finnish_Finland.1252
155      FOS  Faroese_Faroe Islands.1252
156      FPO  Filipino_Philippines.1252
157      FRA  French_France.1252
158      FRB  French_Belgium.1252
159      FRC  French_Canada.1252
160      FRL  French_Luxembourg.1252
161      FRM  French_Principality of Monaco.1252
162      FRS  French_Switzerland.1252
163      FYN  Frisian_Netherlands.1252
164      GLC  Galician_Spain.1252
165      HEB  Hebrew_Israel.1255
166      HRB  Croatian_Bosnia and Herzegovina.1250
167      HRV  Croatian_Croatia.1250
168      HUN  Hungarian_Hungary.1250
169      IND  Indonesian_Indonesia.1252
170      IRE  Irish_Ireland.1252
171      ISL  Icelandic_Iceland.1252
172      ITA  Italian_Italy.1252
173      ITS  Italian_Switzerland.1252
174      IUK  Inuktitut (Latin)_Canada.1252
175      JPN  Japanese_Japan.932
176      KKZ  Kazakh_Kazakhstan.1251
177      KOR  Korean_Korea.949
178      KYR  Kyrgyz_Kyrgyzstan.1251
179      LBX  Luxembourgish_Luxembourg.1252
180      LTH  Lithuanian_Lithuania.1257
181      LVI  Latvian_Latvia.1257
182      MKI  FYRO Macedonian_Former Yugoslav Republic of Macedonia.1251
183      MON  Mongolian_Mongolia.1251
184      MPD  Mapudungun_Chile.1252
185      MSB  Malay_Brunei Darussalam.1252
186      MSL  Malay_Malaysia.1252
187      MWK  Mohawk_Canada.1252
188      NLB  Dutch_Belgium.1252
189      NLD  Dutch_Netherlands.1252
190      NON  Norwegian-Nynorsk_Norway.1252
191      NOR  Norwegian (BokmÃ¥l)_Norway.1252
192      NSO  Northern Sotho_South Africa.1252
193      PLK  Polish_Poland.1250
194      PTB  Portuguese_Brazil.1252
195      PTG  Portuguese_Portugal.1252
196      QUB  Quechua_Bolivia.1252
197      QUE  Quechua_Ecuador.1252
198      QUP  Quechua_Peru.1252
199      RMC  Romansh_Switzerland.1252
200      ROM  Romanian_Romania.1250
201      RUS  Russian_Russia.1251
202      SKY  Slovak_Slovakia.1250
203      SLV  Slovenian_Slovenia.1250
204      SMA  Sami (Southern)_Norway.1252
205      SMB  Sami (Southern)_Sweden.1252
206      SME  Sami (Northern)_Norway.1252
207      SMF  Sami (Northern)_Sweden.1252
208      SMG  Sami (Northern)_Finland.1252
209      SMJ  Sami (Lule)_Norway.1252
210      SMK  Sami (Lule)_Sweden.1252
211      SMN  Sami (Inari)_Finland.1252
212      SMS  Sami (Skolt)_Finland.1252
213      SQI  Albanian_Albania.1250
214      SRB  Serbian (Cyrillic)_Serbia and Montenegro.1251
215      SRL  Serbian (Latin)_Serbia and Montenegro.1250
216      SRN  Serbian (Cyrillic)_Bosnia and Herzegovina.1251
217      SRS  Serbian (Latin)_Bosnia and Herzegovina.1250
218      SVE  Swedish_Sweden.1252
219      SVF  Swedish_Finland.1252
220      SWK  Swahili_Kenya.1252
221      THA  Thai_Thailand.874
222      TRK  Turkish_Turkey.1254
223      TSN  Tswana_South Africa.1252
224      TTT  Tatar_Russia.1251
225      UKR  Ukrainian_Ukraine.1251
226      URD  Urdu_Islamic Republic of Pakistan.1256
227      USA  English_United States.1252
228      UZB  Uzbek (Latin)_Uzbekistan.1254
229      VIT  Vietnamese_Viet Nam.1258
230      XHO  Xhosa_South Africa.1252
231      ZHH  Chinese_Hong Kong S.A.R..950
232      ZHI  Chinese_Singapore.936
233      ZHM  Chinese_Macau S.A.R..950
234      ZUL  Zulu_South Africa.1252
235  */
236
237 /* Table from ISO 639 language code, optionally with country or script suffix,
238    to English name.
239    Keep in sync with the gl_locale_name_from_win32_LANGID function in
240    localename.c!  */
241 struct table_entry
242 {
243   const char *code;
244   const char *english;
245 };
246 static const struct table_entry language_table[] =
247   {
248     { "af", "Afrikaans" },
249     { "am", "Amharic" },
250     { "ar", "Arabic" },
251     { "arn", "Mapudungun" },
252     { "as", "Assamese" },
253     { "az@cyrillic", "Azeri (Cyrillic)" },
254     { "az@latin", "Azeri (Latin)" },
255     { "ba", "Bashkir" },
256     { "be", "Belarusian" },
257     { "ber", "Tamazight" },
258     { "ber@arabic", "Tamazight (Arabic)" },
259     { "ber@latin", "Tamazight (Latin)" },
260     { "bg", "Bulgarian" },
261     { "bin", "Edo" },
262     { "bn", "Bengali" },
263     { "bn_BD", "Bengali (Bangladesh)" },
264     { "bn_IN", "Bengali (India)" },
265     { "bnt", "Sutu" },
266     { "bo", "Tibetan" },
267     { "br", "Breton" },
268     { "bs", "BSB" }, /* "Bosnian (Latin)" */
269     { "bs@cyrillic", "BSC" }, /* Bosnian (Cyrillic) */
270     { "ca", "Catalan" },
271     { "chr", "Cherokee" },
272     { "co", "Corsican" },
273     { "cpe", "Hawaiian" },
274     { "cs", "Czech" },
275     { "cy", "Welsh" },
276     { "da", "Danish" },
277     { "de", "German" },
278     { "dsb", "Lower Sorbian" },
279     { "dv", "Divehi" },
280     { "el", "Greek" },
281     { "en", "English" },
282     { "es", "Spanish" },
283     { "et", "Estonian" },
284     { "eu", "Basque" },
285     { "fa", "Farsi" },
286     { "ff", "Fulfulde" },
287     { "fi", "Finnish" },
288     { "fo", "Faroese" }, /* "Faeroese" does not work */
289     { "fr", "French" },
290     { "fy", "Frisian" },
291     { "ga", "IRE" }, /* Gaelic (Ireland) */
292     { "gd", "Gaelic (Scotland)" },
293     { "gd", "Scottish Gaelic" },
294     { "gl", "Galician" },
295     { "gn", "Guarani" },
296     { "gsw", "Alsatian" },
297     { "gu", "Gujarati" },
298     { "ha", "Hausa" },
299     { "he", "Hebrew" },
300     { "hi", "Hindi" },
301     { "hr", "Croatian" },
302     { "hsb", "Upper Sorbian" },
303     { "hu", "Hungarian" },
304     { "hy", "Armenian" },
305     { "id", "Indonesian" },
306     { "ig", "Igbo" },
307     { "ii", "Yi" },
308     { "is", "Icelandic" },
309     { "it", "Italian" },
310     { "iu", "IUK" }, /* Inuktitut */
311     { "ja", "Japanese" },
312     { "ka", "Georgian" },
313     { "kk", "Kazakh" },
314     { "kl", "Greenlandic" },
315     { "km", "Cambodian" },
316     { "km", "Khmer" },
317     { "kn", "Kannada" },
318     { "ko", "Korean" },
319     { "kok", "Konkani" },
320     { "kr", "Kanuri" },
321     { "ks", "Kashmiri" },
322     { "ks_IN", "Kashmiri_India" },
323     { "ks_PK", "Kashmiri (Arabic)_Pakistan" },
324     { "ky", "Kyrgyz" },
325     { "la", "Latin" },
326     { "lb", "Luxembourgish" },
327     { "lo", "Lao" },
328     { "lt", "Lithuanian" },
329     { "lv", "Latvian" },
330     { "mi", "Maori" },
331     { "mk", "FYRO Macedonian" },
332     { "mk", "Macedonian" },
333     { "ml", "Malayalam" },
334     { "mn", "Mongolian" },
335     { "mni", "Manipuri" },
336     { "moh", "Mohawk" },
337     { "mr", "Marathi" },
338     { "ms", "Malay" },
339     { "mt", "Maltese" },
340     { "my", "Burmese" },
341     { "nb", "NOR" }, /* Norwegian BokmÃ¥l */
342     { "ne", "Nepali" },
343     { "nic", "Ibibio" },
344     { "nl", "Dutch" },
345     { "nn", "NON" }, /* Norwegian Nynorsk */
346     { "no", "Norwegian" },
347     { "nso", "Northern Sotho" },
348     { "nso", "Sepedi" },
349     { "oc", "Occitan" },
350     { "om", "Oromo" },
351     { "or", "Oriya" },
352     { "pa", "Punjabi" },
353     { "pap", "Papiamentu" },
354     { "pl", "Polish" },
355     { "prs", "Dari" },
356     { "ps", "Pashto" },
357     { "pt", "Portuguese" },
358     { "qu", "Quechua" },
359     { "qut", "K'iche'" },
360     { "rm", "Romansh" },
361     { "ro", "Romanian" },
362     { "ru", "Russian" },
363     { "rw", "Kinyarwanda" },
364     { "sa", "Sanskrit" },
365     { "sah", "Yakut" },
366     { "sd", "Sindhi" },
367     { "se", "Sami (Northern)" },
368     { "se", "Northern Sami" },
369     { "si", "Sinhalese" },
370     { "sk", "Slovak" },
371     { "sl", "Slovenian" },
372     { "sma", "Sami (Southern)" },
373     { "sma", "Southern Sami" },
374     { "smj", "Sami (Lule)" },
375     { "smj", "Lule Sami" },
376     { "smn", "Sami (Inari)" },
377     { "smn", "Inari Sami" },
378     { "sms", "Sami (Skolt)" },
379     { "sms", "Skolt Sami" },
380     { "so", "Somali" },
381     { "sq", "Albanian" },
382     { "sr", "Serbian (Latin)" },
383     { "sr@cyrillic", "SRB" }, /* Serbian (Cyrillic) */
384     { "sw", "Swahili" },
385     { "syr", "Syriac" },
386     { "ta", "Tamil" },
387     { "te", "Telugu" },
388     { "tg", "Tajik" },
389     { "th", "Thai" },
390     { "ti", "Tigrinya" },
391     { "tk", "Turkmen" },
392     { "tl", "Filipino" },
393     { "tn", "Tswana" },
394     { "tr", "Turkish" },
395     { "ts", "Tsonga" },
396     { "tt", "Tatar" },
397     { "ug", "Uighur" },
398     { "uk", "Ukrainian" },
399     { "ur", "Urdu" },
400     { "uz", "Uzbek" },
401     { "uz", "Uzbek (Latin)" },
402     { "uz@cyrillic", "Uzbek (Cyrillic)" },
403     { "ve", "Venda" },
404     { "vi", "Vietnamese" },
405     { "wen", "Sorbian" },
406     { "wo", "Wolof" },
407     { "xh", "Xhosa" },
408     { "yi", "Yiddish" },
409     { "yo", "Yoruba" },
410     { "zh", "Chinese" },
411     { "zu", "Zulu" }
412   };
413
414 /* Table from ISO 3166 country code to English name.
415    Keep in sync with the gl_locale_name_from_win32_LANGID function in
416    localename.c!  */
417 static const struct table_entry country_table[] =
418   {
419     { "AE", "U.A.E." },
420     { "AF", "Afghanistan" },
421     { "AL", "Albania" },
422     { "AM", "Armenia" },
423     { "AN", "Netherlands Antilles" },
424     { "AR", "Argentina" },
425     { "AT", "Austria" },
426     { "AU", "Australia" },
427     { "AZ", "Azerbaijan" },
428     { "BA", "Bosnia and Herzegovina" },
429     { "BD", "Bangladesh" },
430     { "BE", "Belgium" },
431     { "BG", "Bulgaria" },
432     { "BH", "Bahrain" },
433     { "BN", "Brunei Darussalam" },
434     { "BO", "Bolivia" },
435     { "BR", "Brazil" },
436     { "BT", "Bhutan" },
437     { "BY", "Belarus" },
438     { "BZ", "Belize" },
439     { "CA", "Canada" },
440     { "CG", "Congo" },
441     { "CH", "Switzerland" },
442     { "CI", "Cote d'Ivoire" },
443     { "CL", "Chile" },
444     { "CM", "Cameroon" },
445     { "CN", "People's Republic of China" },
446     { "CO", "Colombia" },
447     { "CR", "Costa Rica" },
448     { "CS", "Serbia and Montenegro" },
449     { "CZ", "Czech Republic" },
450     { "DE", "Germany" },
451     { "DK", "Denmark" },
452     { "DO", "Dominican Republic" },
453     { "DZ", "Algeria" },
454     { "EC", "Ecuador" },
455     { "EE", "Estonia" },
456     { "EG", "Egypt" },
457     { "ER", "Eritrea" },
458     { "ES", "Spain" },
459     { "ET", "Ethiopia" },
460     { "FI", "Finland" },
461     { "FO", "Faroe Islands" },
462     { "FR", "France" },
463     { "GB", "United Kingdom" },
464     { "GD", "Caribbean" },
465     { "GE", "Georgia" },
466     { "GL", "Greenland" },
467     { "GR", "Greece" },
468     { "GT", "Guatemala" },
469     { "HK", "Hong Kong" },
470     { "HK", "Hong Kong S.A.R." },
471     { "HN", "Honduras" },
472     { "HR", "Croatia" },
473     { "HT", "Haiti" },
474     { "HU", "Hungary" },
475     { "ID", "Indonesia" },
476     { "IE", "Ireland" },
477     { "IL", "Israel" },
478     { "IN", "India" },
479     { "IQ", "Iraq" },
480     { "IR", "Iran" },
481     { "IS", "Iceland" },
482     { "IT", "Italy" },
483     { "JM", "Jamaica" },
484     { "JO", "Jordan" },
485     { "JP", "Japan" },
486     { "KE", "Kenya" },
487     { "KG", "Kyrgyzstan" },
488     { "KH", "Cambodia" },
489     { "KR", "South Korea" },
490     { "KW", "Kuwait" },
491     { "KZ", "Kazakhstan" },
492     { "LA", "Laos" },
493     { "LB", "Lebanon" },
494     { "LI", "Liechtenstein" },
495     { "LK", "Sri Lanka" },
496     { "LT", "Lithuania" },
497     { "LU", "Luxembourg" },
498     { "LV", "Latvia" },
499     { "LY", "Libya" },
500     { "MA", "Morocco" },
501     { "MC", "Principality of Monaco" },
502     { "MD", "Moldava" },
503     { "MD", "Moldova" },
504     { "ME", "Montenegro" },
505     { "MK", "Former Yugoslav Republic of Macedonia" },
506     { "ML", "Mali" },
507     { "MM", "Myanmar" },
508     { "MN", "Mongolia" },
509     { "MO", "Macau S.A.R." },
510     { "MT", "Malta" },
511     { "MV", "Maldives" },
512     { "MX", "Mexico" },
513     { "MY", "Malaysia" },
514     { "NG", "Nigeria" },
515     { "NI", "Nicaragua" },
516     { "NL", "Netherlands" },
517     { "NO", "Norway" },
518     { "NP", "Nepal" },
519     { "NZ", "New Zealand" },
520     { "OM", "Oman" },
521     { "PA", "Panama" },
522     { "PE", "Peru" },
523     { "PH", "Philippines" },
524     { "PK", "Islamic Republic of Pakistan" },
525     { "PL", "Poland" },
526     { "PR", "Puerto Rico" },
527     { "PT", "Portugal" },
528     { "PY", "Paraguay" },
529     { "QA", "Qatar" },
530     { "RE", "Reunion" },
531     { "RO", "Romania" },
532     { "RS", "Serbia" },
533     { "RU", "Russia" },
534     { "RW", "Rwanda" },
535     { "SA", "Saudi Arabia" },
536     { "SE", "Sweden" },
537     { "SG", "Singapore" },
538     { "SI", "Slovenia" },
539     { "SK", "Slovak" },
540     { "SN", "Senegal" },
541     { "SO", "Somalia" },
542     { "SR", "Suriname" },
543     { "SV", "El Salvador" },
544     { "SY", "Syria" },
545     { "TH", "Thailand" },
546     { "TJ", "Tajikistan" },
547     { "TM", "Turkmenistan" },
548     { "TN", "Tunisia" },
549     { "TR", "Turkey" },
550     { "TT", "Trinidad and Tobago" },
551     { "TW", "Taiwan" },
552     { "TZ", "Tanzania" },
553     { "UA", "Ukraine" },
554     { "US", "United States" },
555     { "UY", "Uruguay" },
556     { "VA", "Vatican" },
557     { "VE", "Venezuela" },
558     { "VN", "Viet Nam" },
559     { "YE", "Yemen" },
560     { "ZA", "South Africa" },
561     { "ZW", "Zimbabwe" }
562   };
563
564 /* Given a string STRING, find the set of indices i such that TABLE[i].code is
565    the given STRING.  It is a range [lo,hi-1].  */
566 typedef struct { size_t lo; size_t hi; } range_t;
567 static void
568 search (const struct table_entry *table, size_t table_size, const char *string,
569         range_t *result)
570 {
571   /* The table is sorted.  Perform a binary search.  */
572   size_t hi = table_size;
573   size_t lo = 0;
574   while (lo < hi)
575     {
576       /* Invariant:
577          for i < lo, strcmp (table[i].code, string) < 0,
578          for i >= hi, strcmp (table[i].code, string) > 0.  */
579       size_t mid = (hi + lo) >> 1; /* >= lo, < hi */
580       int cmp = strcmp (table[mid].code, string);
581       if (cmp < 0)
582         lo = mid + 1;
583       else if (cmp > 0)
584         hi = mid;
585       else
586         {
587           /* Found an i with
588                strcmp (language_table[i].code, string) == 0.
589              Find the entire interval of such i.  */
590           {
591             size_t i;
592
593             for (i = mid; i > lo; )
594               {
595                 i--;
596                 if (strcmp (table[i].code, string) < 0)
597                   {
598                     lo = i + 1;
599                     break;
600                   }
601               }
602           }
603           {
604             size_t i;
605
606             for (i = mid; i < hi; i++)
607               {
608                 if (strcmp (table[i].code, string) > 0)
609                   {
610                     hi = i;
611                     break;
612                   }
613               }
614           }
615           /* The set of i with
616                strcmp (language_table[i].code, string) == 0
617              is the interval [lo, hi-1].  */
618           break;
619         }
620     }
621   result->lo = lo;
622   result->hi = hi;
623 }
624
625 /* Like setlocale, but accept also locale names in the form ll or ll_CC,
626    where ll is an ISO 639 language code and CC is an ISO 3166 country code.  */
627 static char *
628 setlocale_unixlike (int category, const char *locale)
629 {
630   char *result;
631   char llCC_buf[64];
632   char ll_buf[64];
633   char CC_buf[64];
634
635   /* First, try setlocale with the original argument unchanged.  */
636   result = setlocale (category, locale);
637   if (result != NULL)
638     return result;
639
640   /* Otherwise, assume the argument is in the form
641        language[_territory][.codeset][@modifier]
642      and try to map it using the tables.  */
643   if (strlen (locale) < sizeof (llCC_buf))
644     {
645       /* Second try: Remove the codeset part.  */
646       {
647         const char *p = locale;
648         char *q = llCC_buf;
649
650         /* Copy the part before the dot.  */
651         for (; *p != '\0' && *p != '.'; p++, q++)
652           *q = *p;
653         if (*p == '.')
654           /* Skip the part up to the '@', if any.  */
655           for (; *p != '\0' && *p != '@'; p++)
656             ;
657         /* Copy the part starting with '@', if any.  */
658         for (; *p != '\0'; p++, q++)
659           *q = *p;
660         *q = '\0';
661       }
662       /* llCC_buf now contains
663            language[_territory][@modifier]
664        */
665       if (strcmp (llCC_buf, locale) != 0)
666         {
667           result = setlocale (category, llCC_buf);
668           if (result != NULL)
669             return result;
670         }
671       /* Look it up in language_table.  */
672       {
673         range_t range;
674         size_t i;
675
676         search (language_table,
677                 sizeof (language_table) / sizeof (language_table[0]),
678                 llCC_buf,
679                 &range);
680
681         for (i = range.lo; i < range.hi; i++)
682           {
683             /* Try the replacement in language_table[i].  */
684             result = setlocale (category, language_table[i].english);
685             if (result != NULL)
686               return result;
687           }
688       }
689       /* Split language[_territory][@modifier]
690          into  ll_buf = language[@modifier]
691          and   CC_buf = territory
692        */
693       {
694         const char *underscore = strchr (llCC_buf, '_');
695         if (underscore != NULL)
696           {
697             const char *territory_start = underscore + 1;
698             const char *territory_end = strchr (territory_start, '@');
699             if (territory_end == NULL)
700               territory_end = territory_start + strlen (territory_start);
701
702             memcpy (ll_buf, llCC_buf, underscore - llCC_buf);
703             strcpy (ll_buf + (underscore - llCC_buf), territory_end);
704
705             memcpy (CC_buf, territory_start, territory_end - territory_start);
706             CC_buf[territory_end - territory_start] = '\0';
707
708             {
709               /* Look up ll_buf in language_table
710                  and CC_buf in country_table.  */
711               range_t language_range;
712
713               search (language_table,
714                       sizeof (language_table) / sizeof (language_table[0]),
715                       ll_buf,
716                       &language_range);
717               if (language_range.lo < language_range.hi)
718                 {
719                   range_t country_range;
720
721                   search (country_table,
722                           sizeof (country_table) / sizeof (country_table[0]),
723                           CC_buf,
724                           &country_range);
725                   if (country_range.lo < country_range.hi)
726                     {
727                       size_t i;
728                       size_t j;
729
730                       for (i = language_range.lo; i < language_range.hi; i++)
731                         for (j = country_range.lo; j < country_range.hi; j++)
732                           {
733                             /* Concatenate the replacements.  */
734                             const char *part1 = language_table[i].english;
735                             size_t part1_len = strlen (part1);
736                             const char *part2 = country_table[j].english;
737                             size_t part2_len = strlen (part2) + 1;
738                             char buf[64+64];
739
740                             if (!(part1_len + 1 + part2_len <= sizeof (buf)))
741                               abort ();
742                             memcpy (buf, part1, part1_len);
743                             buf[part1_len] = '_';
744                             memcpy (buf + part1_len + 1, part2, part2_len);
745
746                             /* Try the concatenated replacements.  */
747                             result = setlocale (category, buf);
748                             if (result != NULL)
749                               return result;
750                           }
751                     }
752
753                   /* Try omitting the country entirely.  This may set a locale
754                      corresponding to the wrong country, but is better than
755                      failing entirely.  */
756                   {
757                     size_t i;
758
759                     for (i = language_range.lo; i < language_range.hi; i++)
760                       {
761                         /* Try only the language replacement.  */
762                         result =
763                           setlocale (category, language_table[i].english);
764                         if (result != NULL)
765                           return result;
766                       }
767                   }
768                 }
769             }
770           }
771       }
772     }
773
774   /* Failed.  */
775   return NULL;
776 }
777
778 # else
779 #  define setlocale_unixlike setlocale
780 # endif
781
782 # if LC_MESSAGES == 1729
783
784 /* The system does not store an LC_MESSAGES locale category.  Do it here.  */
785 static char lc_messages_name[64] = "C";
786
787 /* Like setlocale, but support also LC_MESSAGES.  */
788 static char *
789 setlocale_single (int category, const char *locale)
790 {
791   if (category == LC_MESSAGES)
792     {
793       if (locale != NULL)
794         {
795           lc_messages_name[sizeof (lc_messages_name) - 1] = '\0';
796           strncpy (lc_messages_name, locale, sizeof (lc_messages_name) - 1);
797         }
798       return lc_messages_name;
799     }
800   else
801     return setlocale_unixlike (category, locale);
802 }
803
804 # else
805 #  define setlocale_single setlocale_unixlike
806 # endif
807
808 char *
809 rpl_setlocale (int category, const char *locale)
810 {
811   if (locale != NULL && locale[0] == '\0')
812     {
813       /* A request to the set the current locale to the default locale.  */
814       if (category == LC_ALL)
815         {
816           /* Set LC_CTYPE first.  Then the other categories.  */
817           static int const categories[] =
818             {
819               LC_NUMERIC,
820               LC_TIME,
821               LC_COLLATE,
822               LC_MONETARY,
823               LC_MESSAGES
824             };
825           char *saved_locale;
826           const char *base_name;
827           unsigned int i;
828
829           /* Back up the old locale, in case one of the steps fails.  */
830           saved_locale = setlocale (LC_ALL, NULL);
831           if (saved_locale == NULL)
832             return NULL;
833           saved_locale = strdup (saved_locale);
834           if (saved_locale == NULL)
835             return NULL;
836
837           /* Set LC_CTYPE category.  Set all other categories (except possibly
838              LC_MESSAGES) to the same value in the same call; this is likely to
839              save calls.  */
840           base_name =
841             gl_locale_name_environ (LC_CTYPE, category_to_name (LC_CTYPE));
842           if (base_name == NULL)
843             base_name = gl_locale_name_default ();
844
845           if (setlocale_unixlike (LC_ALL, base_name) == NULL)
846             goto fail;
847 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
848           /* On native Windows, setlocale(LC_ALL,...) may succeed but set the
849              LC_CTYPE category to an invalid value ("C") when it does not
850              support the specified encoding.  Report a failure instead.  */
851           if (strchr (base_name, '.') != NULL
852               && strcmp (setlocale (LC_CTYPE, NULL), "C") == 0)
853             goto fail;
854 # endif
855
856           for (i = 0; i < sizeof (categories) / sizeof (categories[0]); i++)
857             {
858               int cat = categories[i];
859               const char *name;
860
861               name = gl_locale_name_environ (cat, category_to_name (cat));
862               if (name == NULL)
863                 name = gl_locale_name_default ();
864
865               /* If name is the same as base_name, it has already been set
866                  through the setlocale call before the loop.  */
867               if (strcmp (name, base_name) != 0
868 # if LC_MESSAGES == 1729
869                   || cat == LC_MESSAGES
870 # endif
871                  )
872                 if (setlocale_single (cat, name) == NULL)
873                   goto fail;
874             }
875
876           /* All steps were successful.  */
877           free (saved_locale);
878           return setlocale (LC_ALL, NULL);
879
880         fail:
881           if (saved_locale[0] != '\0') /* don't risk an endless recursion */
882             setlocale (LC_ALL, saved_locale);
883           free (saved_locale);
884           return NULL;
885         }
886       else
887         {
888           const char *name =
889             gl_locale_name_environ (category, category_to_name (category));
890           if (name == NULL)
891             name = gl_locale_name_default ();
892
893           return setlocale_single (category, name);
894         }
895     }
896   else
897     {
898 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
899       if (category == LC_ALL && locale != NULL && strchr (locale, '.') != NULL)
900         {
901           char *saved_locale;
902
903           /* Back up the old locale.  */
904           saved_locale = setlocale (LC_ALL, NULL);
905           if (saved_locale == NULL)
906             return NULL;
907           saved_locale = strdup (saved_locale);
908           if (saved_locale == NULL)
909             return NULL;
910
911           if (setlocale_unixlike (LC_ALL, locale) == NULL)
912             {
913               free (saved_locale);
914               return NULL;
915             }
916
917           /* On native Windows, setlocale(LC_ALL,...) may succeed but set the
918              LC_CTYPE category to an invalid value ("C") when it does not
919              support the specified encoding.  Report a failure instead.  */
920           if (strcmp (setlocale (LC_CTYPE, NULL), "C") == 0)
921             {
922               if (saved_locale[0] != '\0') /* don't risk an endless recursion */
923                 setlocale (LC_ALL, saved_locale);
924               free (saved_locale);
925               return NULL;
926             }
927
928           /* It was really successful.  */
929           free (saved_locale);
930           return setlocale (LC_ALL, NULL);
931         }
932       else
933 # endif
934         return setlocale_single (category, locale);
935     }
936 }
937
938 #endif