Bump to 1.14.1
[platform/upstream/augeas.git] / lib / setlocale.c
1 /* Set the current locale.  -*- coding: utf-8 -*-
2    Copyright (C) 2009, 2011-2016 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     { "sv", "Swedish" },
385     { "sw", "Swahili" },
386     { "syr", "Syriac" },
387     { "ta", "Tamil" },
388     { "te", "Telugu" },
389     { "tg", "Tajik" },
390     { "th", "Thai" },
391     { "ti", "Tigrinya" },
392     { "tk", "Turkmen" },
393     { "tl", "Filipino" },
394     { "tn", "Tswana" },
395     { "tr", "Turkish" },
396     { "ts", "Tsonga" },
397     { "tt", "Tatar" },
398     { "ug", "Uighur" },
399     { "uk", "Ukrainian" },
400     { "ur", "Urdu" },
401     { "uz", "Uzbek" },
402     { "uz", "Uzbek (Latin)" },
403     { "uz@cyrillic", "Uzbek (Cyrillic)" },
404     { "ve", "Venda" },
405     { "vi", "Vietnamese" },
406     { "wen", "Sorbian" },
407     { "wo", "Wolof" },
408     { "xh", "Xhosa" },
409     { "yi", "Yiddish" },
410     { "yo", "Yoruba" },
411     { "zh", "Chinese" },
412     { "zu", "Zulu" }
413   };
414
415 /* Table from ISO 3166 country code to English name.
416    Keep in sync with the gl_locale_name_from_win32_LANGID function in
417    localename.c!  */
418 static const struct table_entry country_table[] =
419   {
420     { "AE", "U.A.E." },
421     { "AF", "Afghanistan" },
422     { "AL", "Albania" },
423     { "AM", "Armenia" },
424     { "AN", "Netherlands Antilles" },
425     { "AR", "Argentina" },
426     { "AT", "Austria" },
427     { "AU", "Australia" },
428     { "AZ", "Azerbaijan" },
429     { "BA", "Bosnia and Herzegovina" },
430     { "BD", "Bangladesh" },
431     { "BE", "Belgium" },
432     { "BG", "Bulgaria" },
433     { "BH", "Bahrain" },
434     { "BN", "Brunei Darussalam" },
435     { "BO", "Bolivia" },
436     { "BR", "Brazil" },
437     { "BT", "Bhutan" },
438     { "BY", "Belarus" },
439     { "BZ", "Belize" },
440     { "CA", "Canada" },
441     { "CG", "Congo" },
442     { "CH", "Switzerland" },
443     { "CI", "Cote d'Ivoire" },
444     { "CL", "Chile" },
445     { "CM", "Cameroon" },
446     { "CN", "People's Republic of China" },
447     { "CO", "Colombia" },
448     { "CR", "Costa Rica" },
449     { "CS", "Serbia and Montenegro" },
450     { "CZ", "Czech Republic" },
451     { "DE", "Germany" },
452     { "DK", "Denmark" },
453     { "DO", "Dominican Republic" },
454     { "DZ", "Algeria" },
455     { "EC", "Ecuador" },
456     { "EE", "Estonia" },
457     { "EG", "Egypt" },
458     { "ER", "Eritrea" },
459     { "ES", "Spain" },
460     { "ET", "Ethiopia" },
461     { "FI", "Finland" },
462     { "FO", "Faroe Islands" },
463     { "FR", "France" },
464     { "GB", "United Kingdom" },
465     { "GD", "Caribbean" },
466     { "GE", "Georgia" },
467     { "GL", "Greenland" },
468     { "GR", "Greece" },
469     { "GT", "Guatemala" },
470     { "HK", "Hong Kong" },
471     { "HK", "Hong Kong S.A.R." },
472     { "HN", "Honduras" },
473     { "HR", "Croatia" },
474     { "HT", "Haiti" },
475     { "HU", "Hungary" },
476     { "ID", "Indonesia" },
477     { "IE", "Ireland" },
478     { "IL", "Israel" },
479     { "IN", "India" },
480     { "IQ", "Iraq" },
481     { "IR", "Iran" },
482     { "IS", "Iceland" },
483     { "IT", "Italy" },
484     { "JM", "Jamaica" },
485     { "JO", "Jordan" },
486     { "JP", "Japan" },
487     { "KE", "Kenya" },
488     { "KG", "Kyrgyzstan" },
489     { "KH", "Cambodia" },
490     { "KR", "South Korea" },
491     { "KW", "Kuwait" },
492     { "KZ", "Kazakhstan" },
493     { "LA", "Laos" },
494     { "LB", "Lebanon" },
495     { "LI", "Liechtenstein" },
496     { "LK", "Sri Lanka" },
497     { "LT", "Lithuania" },
498     { "LU", "Luxembourg" },
499     { "LV", "Latvia" },
500     { "LY", "Libya" },
501     { "MA", "Morocco" },
502     { "MC", "Principality of Monaco" },
503     { "MD", "Moldava" },
504     { "MD", "Moldova" },
505     { "ME", "Montenegro" },
506     { "MK", "Former Yugoslav Republic of Macedonia" },
507     { "ML", "Mali" },
508     { "MM", "Myanmar" },
509     { "MN", "Mongolia" },
510     { "MO", "Macau S.A.R." },
511     { "MT", "Malta" },
512     { "MV", "Maldives" },
513     { "MX", "Mexico" },
514     { "MY", "Malaysia" },
515     { "NG", "Nigeria" },
516     { "NI", "Nicaragua" },
517     { "NL", "Netherlands" },
518     { "NO", "Norway" },
519     { "NP", "Nepal" },
520     { "NZ", "New Zealand" },
521     { "OM", "Oman" },
522     { "PA", "Panama" },
523     { "PE", "Peru" },
524     { "PH", "Philippines" },
525     { "PK", "Islamic Republic of Pakistan" },
526     { "PL", "Poland" },
527     { "PR", "Puerto Rico" },
528     { "PT", "Portugal" },
529     { "PY", "Paraguay" },
530     { "QA", "Qatar" },
531     { "RE", "Reunion" },
532     { "RO", "Romania" },
533     { "RS", "Serbia" },
534     { "RU", "Russia" },
535     { "RW", "Rwanda" },
536     { "SA", "Saudi Arabia" },
537     { "SE", "Sweden" },
538     { "SG", "Singapore" },
539     { "SI", "Slovenia" },
540     { "SK", "Slovak" },
541     { "SN", "Senegal" },
542     { "SO", "Somalia" },
543     { "SR", "Suriname" },
544     { "SV", "El Salvador" },
545     { "SY", "Syria" },
546     { "TH", "Thailand" },
547     { "TJ", "Tajikistan" },
548     { "TM", "Turkmenistan" },
549     { "TN", "Tunisia" },
550     { "TR", "Turkey" },
551     { "TT", "Trinidad and Tobago" },
552     { "TW", "Taiwan" },
553     { "TZ", "Tanzania" },
554     { "UA", "Ukraine" },
555     { "US", "United States" },
556     { "UY", "Uruguay" },
557     { "VA", "Vatican" },
558     { "VE", "Venezuela" },
559     { "VN", "Viet Nam" },
560     { "YE", "Yemen" },
561     { "ZA", "South Africa" },
562     { "ZW", "Zimbabwe" }
563   };
564
565 /* Given a string STRING, find the set of indices i such that TABLE[i].code is
566    the given STRING.  It is a range [lo,hi-1].  */
567 typedef struct { size_t lo; size_t hi; } range_t;
568 static void
569 search (const struct table_entry *table, size_t table_size, const char *string,
570         range_t *result)
571 {
572   /* The table is sorted.  Perform a binary search.  */
573   size_t hi = table_size;
574   size_t lo = 0;
575   while (lo < hi)
576     {
577       /* Invariant:
578          for i < lo, strcmp (table[i].code, string) < 0,
579          for i >= hi, strcmp (table[i].code, string) > 0.  */
580       size_t mid = (hi + lo) >> 1; /* >= lo, < hi */
581       int cmp = strcmp (table[mid].code, string);
582       if (cmp < 0)
583         lo = mid + 1;
584       else if (cmp > 0)
585         hi = mid;
586       else
587         {
588           /* Found an i with
589                strcmp (language_table[i].code, string) == 0.
590              Find the entire interval of such i.  */
591           {
592             size_t i;
593
594             for (i = mid; i > lo; )
595               {
596                 i--;
597                 if (strcmp (table[i].code, string) < 0)
598                   {
599                     lo = i + 1;
600                     break;
601                   }
602               }
603           }
604           {
605             size_t i;
606
607             for (i = mid; i < hi; i++)
608               {
609                 if (strcmp (table[i].code, string) > 0)
610                   {
611                     hi = i;
612                     break;
613                   }
614               }
615           }
616           /* The set of i with
617                strcmp (language_table[i].code, string) == 0
618              is the interval [lo, hi-1].  */
619           break;
620         }
621     }
622   result->lo = lo;
623   result->hi = hi;
624 }
625
626 /* Like setlocale, but accept also locale names in the form ll or ll_CC,
627    where ll is an ISO 639 language code and CC is an ISO 3166 country code.  */
628 static char *
629 setlocale_unixlike (int category, const char *locale)
630 {
631   char *result;
632   char llCC_buf[64];
633   char ll_buf[64];
634   char CC_buf[64];
635
636   /* First, try setlocale with the original argument unchanged.  */
637   result = setlocale (category, locale);
638   if (result != NULL)
639     return result;
640
641   /* Otherwise, assume the argument is in the form
642        language[_territory][.codeset][@modifier]
643      and try to map it using the tables.  */
644   if (strlen (locale) < sizeof (llCC_buf))
645     {
646       /* Second try: Remove the codeset part.  */
647       {
648         const char *p = locale;
649         char *q = llCC_buf;
650
651         /* Copy the part before the dot.  */
652         for (; *p != '\0' && *p != '.'; p++, q++)
653           *q = *p;
654         if (*p == '.')
655           /* Skip the part up to the '@', if any.  */
656           for (; *p != '\0' && *p != '@'; p++)
657             ;
658         /* Copy the part starting with '@', if any.  */
659         for (; *p != '\0'; p++, q++)
660           *q = *p;
661         *q = '\0';
662       }
663       /* llCC_buf now contains
664            language[_territory][@modifier]
665        */
666       if (strcmp (llCC_buf, locale) != 0)
667         {
668           result = setlocale (category, llCC_buf);
669           if (result != NULL)
670             return result;
671         }
672       /* Look it up in language_table.  */
673       {
674         range_t range;
675         size_t i;
676
677         search (language_table,
678                 sizeof (language_table) / sizeof (language_table[0]),
679                 llCC_buf,
680                 &range);
681
682         for (i = range.lo; i < range.hi; i++)
683           {
684             /* Try the replacement in language_table[i].  */
685             result = setlocale (category, language_table[i].english);
686             if (result != NULL)
687               return result;
688           }
689       }
690       /* Split language[_territory][@modifier]
691          into  ll_buf = language[@modifier]
692          and   CC_buf = territory
693        */
694       {
695         const char *underscore = strchr (llCC_buf, '_');
696         if (underscore != NULL)
697           {
698             const char *territory_start = underscore + 1;
699             const char *territory_end = strchr (territory_start, '@');
700             if (territory_end == NULL)
701               territory_end = territory_start + strlen (territory_start);
702
703             memcpy (ll_buf, llCC_buf, underscore - llCC_buf);
704             strcpy (ll_buf + (underscore - llCC_buf), territory_end);
705
706             memcpy (CC_buf, territory_start, territory_end - territory_start);
707             CC_buf[territory_end - territory_start] = '\0';
708
709             {
710               /* Look up ll_buf in language_table
711                  and CC_buf in country_table.  */
712               range_t language_range;
713
714               search (language_table,
715                       sizeof (language_table) / sizeof (language_table[0]),
716                       ll_buf,
717                       &language_range);
718               if (language_range.lo < language_range.hi)
719                 {
720                   range_t country_range;
721
722                   search (country_table,
723                           sizeof (country_table) / sizeof (country_table[0]),
724                           CC_buf,
725                           &country_range);
726                   if (country_range.lo < country_range.hi)
727                     {
728                       size_t i;
729                       size_t j;
730
731                       for (i = language_range.lo; i < language_range.hi; i++)
732                         for (j = country_range.lo; j < country_range.hi; j++)
733                           {
734                             /* Concatenate the replacements.  */
735                             const char *part1 = language_table[i].english;
736                             size_t part1_len = strlen (part1);
737                             const char *part2 = country_table[j].english;
738                             size_t part2_len = strlen (part2) + 1;
739                             char buf[64+64];
740
741                             if (!(part1_len + 1 + part2_len <= sizeof (buf)))
742                               abort ();
743                             memcpy (buf, part1, part1_len);
744                             buf[part1_len] = '_';
745                             memcpy (buf + part1_len + 1, part2, part2_len);
746
747                             /* Try the concatenated replacements.  */
748                             result = setlocale (category, buf);
749                             if (result != NULL)
750                               return result;
751                           }
752                     }
753
754                   /* Try omitting the country entirely.  This may set a locale
755                      corresponding to the wrong country, but is better than
756                      failing entirely.  */
757                   {
758                     size_t i;
759
760                     for (i = language_range.lo; i < language_range.hi; i++)
761                       {
762                         /* Try only the language replacement.  */
763                         result =
764                           setlocale (category, language_table[i].english);
765                         if (result != NULL)
766                           return result;
767                       }
768                   }
769                 }
770             }
771           }
772       }
773     }
774
775   /* Failed.  */
776   return NULL;
777 }
778
779 # else
780 #  define setlocale_unixlike setlocale
781 # endif
782
783 # if LC_MESSAGES == 1729
784
785 /* The system does not store an LC_MESSAGES locale category.  Do it here.  */
786 static char lc_messages_name[64] = "C";
787
788 /* Like setlocale, but support also LC_MESSAGES.  */
789 static char *
790 setlocale_single (int category, const char *locale)
791 {
792   if (category == LC_MESSAGES)
793     {
794       if (locale != NULL)
795         {
796           lc_messages_name[sizeof (lc_messages_name) - 1] = '\0';
797           strncpy (lc_messages_name, locale, sizeof (lc_messages_name) - 1);
798         }
799       return lc_messages_name;
800     }
801   else
802     return setlocale_unixlike (category, locale);
803 }
804
805 # else
806 #  define setlocale_single setlocale_unixlike
807 # endif
808
809 char *
810 rpl_setlocale (int category, const char *locale)
811 {
812   if (locale != NULL && locale[0] == '\0')
813     {
814       /* A request to the set the current locale to the default locale.  */
815       if (category == LC_ALL)
816         {
817           /* Set LC_CTYPE first.  Then the other categories.  */
818           static int const categories[] =
819             {
820               LC_NUMERIC,
821               LC_TIME,
822               LC_COLLATE,
823               LC_MONETARY,
824               LC_MESSAGES
825             };
826           char *saved_locale;
827           const char *base_name;
828           unsigned int i;
829
830           /* Back up the old locale, in case one of the steps fails.  */
831           saved_locale = setlocale (LC_ALL, NULL);
832           if (saved_locale == NULL)
833             return NULL;
834           saved_locale = strdup (saved_locale);
835           if (saved_locale == NULL)
836             return NULL;
837
838           /* Set LC_CTYPE category.  Set all other categories (except possibly
839              LC_MESSAGES) to the same value in the same call; this is likely to
840              save calls.  */
841           base_name =
842             gl_locale_name_environ (LC_CTYPE, category_to_name (LC_CTYPE));
843           if (base_name == NULL)
844             base_name = gl_locale_name_default ();
845
846           if (setlocale_unixlike (LC_ALL, base_name) == NULL)
847             goto fail;
848 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
849           /* On native Windows, setlocale(LC_ALL,...) may succeed but set the
850              LC_CTYPE category to an invalid value ("C") when it does not
851              support the specified encoding.  Report a failure instead.  */
852           if (strchr (base_name, '.') != NULL
853               && strcmp (setlocale (LC_CTYPE, NULL), "C") == 0)
854             goto fail;
855 # endif
856
857           for (i = 0; i < sizeof (categories) / sizeof (categories[0]); i++)
858             {
859               int cat = categories[i];
860               const char *name;
861
862               name = gl_locale_name_environ (cat, category_to_name (cat));
863               if (name == NULL)
864                 name = gl_locale_name_default ();
865
866               /* If name is the same as base_name, it has already been set
867                  through the setlocale call before the loop.  */
868               if (strcmp (name, base_name) != 0
869 # if LC_MESSAGES == 1729
870                   || cat == LC_MESSAGES
871 # endif
872                  )
873                 if (setlocale_single (cat, name) == NULL)
874                   goto fail;
875             }
876
877           /* All steps were successful.  */
878           free (saved_locale);
879           return setlocale (LC_ALL, NULL);
880
881         fail:
882           if (saved_locale[0] != '\0') /* don't risk an endless recursion */
883             setlocale (LC_ALL, saved_locale);
884           free (saved_locale);
885           return NULL;
886         }
887       else
888         {
889           const char *name =
890             gl_locale_name_environ (category, category_to_name (category));
891           if (name == NULL)
892             name = gl_locale_name_default ();
893
894           return setlocale_single (category, name);
895         }
896     }
897   else
898     {
899 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
900       if (category == LC_ALL && locale != NULL && strchr (locale, '.') != NULL)
901         {
902           char *saved_locale;
903
904           /* Back up the old locale.  */
905           saved_locale = setlocale (LC_ALL, NULL);
906           if (saved_locale == NULL)
907             return NULL;
908           saved_locale = strdup (saved_locale);
909           if (saved_locale == NULL)
910             return NULL;
911
912           if (setlocale_unixlike (LC_ALL, locale) == NULL)
913             {
914               free (saved_locale);
915               return NULL;
916             }
917
918           /* On native Windows, setlocale(LC_ALL,...) may succeed but set the
919              LC_CTYPE category to an invalid value ("C") when it does not
920              support the specified encoding.  Report a failure instead.  */
921           if (strcmp (setlocale (LC_CTYPE, NULL), "C") == 0)
922             {
923               if (saved_locale[0] != '\0') /* don't risk an endless recursion */
924                 setlocale (LC_ALL, saved_locale);
925               free (saved_locale);
926               return NULL;
927             }
928
929           /* It was really successful.  */
930           free (saved_locale);
931           return setlocale (LC_ALL, NULL);
932         }
933       else
934 # endif
935         return setlocale_single (category, locale);
936     }
937 }
938
939 #endif