Remove K&R cruft in getopt.
[gnulib.git] / lib / getopt.c
1 /* Getopt for GNU.
2    NOTE: getopt is now part of the C library, so if you don't know what
3    "Keep this file name-space clean" means, talk to drepper@gnu.org
4    before changing it!
5
6    Copyright (C) 1987, 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995,
7    1996, 1998, 1999, 2000, 2001, 2002, 2003 Free Software Foundation,
8    Inc.
9
10    This file is part of the GNU C Library.
11
12    This program is free software; you can redistribute it and/or modify
13    it under the terms of the GNU General Public License as published by
14    the Free Software Foundation; either version 2, or (at your option)
15    any later version.
16
17    This program is distributed in the hope that it will be useful,
18    but WITHOUT ANY WARRANTY; without even the implied warranty of
19    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20    GNU General Public License for more details.
21
22    You should have received a copy of the GNU General Public License along
23    with this program; if not, write to the Free Software Foundation,
24    Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
25 \f
26 /* This tells Alpha OSF/1 not to define a getopt prototype in <stdio.h>.
27    Ditto for AIX 3.2 and <stdlib.h>.  */
28 #ifndef _NO_PROTO
29 # define _NO_PROTO
30 #endif
31
32 #ifdef HAVE_CONFIG_H
33 # include <config.h>
34 #endif
35
36 #include <stdio.h>
37
38 /* Comment out all this code if we are using the GNU C Library, and are not
39    actually compiling the library itself.  This code is part of the GNU C
40    Library, but also included in many other GNU distributions.  Compiling
41    and linking in this code is a waste when using the GNU C library
42    (especially if it is a shared library).  Rather than having every GNU
43    program understand `configure --with-gnu-libc' and omit the object files,
44    it is simpler to just do this in the source for each such file.  */
45
46 #define GETOPT_INTERFACE_VERSION 2
47 #if !defined _LIBC && defined __GLIBC__ && __GLIBC__ >= 2
48 # include <gnu-versions.h>
49 # if _GNU_GETOPT_INTERFACE_VERSION == GETOPT_INTERFACE_VERSION
50 #  define ELIDE_CODE
51 # endif
52 #endif
53
54 #ifndef ELIDE_CODE
55
56
57 /* This needs to come after some library #include
58    to get __GNU_LIBRARY__ defined.  */
59 #ifdef  __GNU_LIBRARY__
60 /* Don't include stdlib.h for non-GNU C libraries because some of them
61    contain conflicting prototypes for getopt.  */
62 # include <stdlib.h>
63 # include <unistd.h>
64 #endif  /* GNU C library.  */
65
66 #include <string.h>
67
68 #ifdef VMS
69 # include <unixlib.h>
70 #endif
71
72 #ifdef _LIBC
73 # include <libintl.h>
74 #else
75 /* This is for other GNU distributions with internationalized messages.  */
76 # include "gettext.h"
77 #endif
78 #define _(msgid) gettext (msgid)
79
80 #if defined _LIBC && defined USE_IN_LIBIO
81 # include <wchar.h>
82 #endif
83
84 #ifndef attribute_hidden
85 # define attribute_hidden
86 #endif
87
88 /* This version of `getopt' appears to the caller like standard Unix `getopt'
89    but it behaves differently for the user, since it allows the user
90    to intersperse the options with the other arguments.
91
92    As `getopt' works, it permutes the elements of ARGV so that,
93    when it is done, all the options precede everything else.  Thus
94    all application programs are extended to handle flexible argument order.
95
96    Setting the environment variable POSIXLY_CORRECT disables permutation.
97    Then the behavior is completely standard.
98
99    GNU application programs can use a third alternative mode in which
100    they can distinguish the relative order of options and other arguments.  */
101
102 #include "getopt.h"
103
104 /* For communication from `getopt' to the caller.
105    When `getopt' finds an option that takes an argument,
106    the argument value is returned here.
107    Also, when `ordering' is RETURN_IN_ORDER,
108    each non-option ARGV-element is returned here.  */
109
110 char *optarg;
111
112 /* Index in ARGV of the next element to be scanned.
113    This is used for communication to and from the caller
114    and for communication between successive calls to `getopt'.
115
116    On entry to `getopt', zero means this is the first call; initialize.
117
118    When `getopt' returns -1, this is the index of the first of the
119    non-option elements that the caller should itself scan.
120
121    Otherwise, `optind' communicates from one call to the next
122    how much of ARGV has been scanned so far.  */
123
124 /* 1003.2 says this must be 1 before any call.  */
125 int optind = 1;
126
127 /* Formerly, initialization of getopt depended on optind==0, which
128    causes problems with re-calling getopt as programs generally don't
129    know that. */
130
131 int __getopt_initialized attribute_hidden;
132
133 /* The next char to be scanned in the option-element
134    in which the last option character we returned was found.
135    This allows us to pick up the scan where we left off.
136
137    If this is zero, or a null string, it means resume the scan
138    by advancing to the next ARGV-element.  */
139
140 static char *nextchar;
141
142 /* Callers store zero here to inhibit the error message
143    for unrecognized options.  */
144
145 int opterr = 1;
146
147 /* Set to an option character which was unrecognized.
148    This must be initialized on some systems to avoid linking in the
149    system's own getopt implementation.  */
150
151 int optopt = '?';
152
153 /* Describe how to deal with options that follow non-option ARGV-elements.
154
155    If the caller did not specify anything,
156    the default is REQUIRE_ORDER if the environment variable
157    POSIXLY_CORRECT is defined, PERMUTE otherwise.
158
159    REQUIRE_ORDER means don't recognize them as options;
160    stop option processing when the first non-option is seen.
161    This is what Unix does.
162    This mode of operation is selected by either setting the environment
163    variable POSIXLY_CORRECT, or using `+' as the first character
164    of the list of option characters.
165
166    PERMUTE is the default.  We permute the contents of ARGV as we scan,
167    so that eventually all the non-options are at the end.  This allows options
168    to be given in any order, even with programs that were not written to
169    expect this.
170
171    RETURN_IN_ORDER is an option available to programs that were written
172    to expect options and other ARGV-elements in any order and that care about
173    the ordering of the two.  We describe each non-option ARGV-element
174    as if it were the argument of an option with character code 1.
175    Using `-' as the first character of the list of option characters
176    selects this mode of operation.
177
178    The special argument `--' forces an end of option-scanning regardless
179    of the value of `ordering'.  In the case of RETURN_IN_ORDER, only
180    `--' can cause `getopt' to return -1 with `optind' != ARGC.  */
181
182 static enum
183 {
184   REQUIRE_ORDER, PERMUTE, RETURN_IN_ORDER
185 } ordering;
186
187 /* Value of POSIXLY_CORRECT environment variable.  */
188 static char *posixly_correct;
189 \f
190 #ifndef __GNU_LIBRARY__
191
192 /* Avoid depending on library functions or files
193    whose names are inconsistent.  */
194
195 #ifndef getenv
196 extern char *getenv ();
197 #endif
198
199 #endif /* not __GNU_LIBRARY__ */
200 \f
201 /* Handle permutation of arguments.  */
202
203 /* Describe the part of ARGV that contains non-options that have
204    been skipped.  `first_nonopt' is the index in ARGV of the first of them;
205    `last_nonopt' is the index after the last of them.  */
206
207 static int first_nonopt;
208 static int last_nonopt;
209
210 #ifdef _LIBC
211 /* Stored original parameters.
212    XXX This is no good solution.  We should rather copy the args so
213    that we can compare them later.  But we must not use malloc(3).  */
214 extern int __libc_argc;
215 extern char **__libc_argv;
216
217 /* Bash 2.0 gives us an environment variable containing flags
218    indicating ARGV elements that should not be considered arguments.  */
219
220 # ifdef USE_NONOPTION_FLAGS
221 /* Defined in getopt_init.c  */
222 extern char *__getopt_nonoption_flags;
223
224 static int nonoption_flags_max_len;
225 static int nonoption_flags_len;
226 # endif
227
228 # ifdef USE_NONOPTION_FLAGS
229 #  define SWAP_FLAGS(ch1, ch2) \
230   if (nonoption_flags_len > 0)                                                \
231     {                                                                         \
232       char __tmp = __getopt_nonoption_flags[ch1];                             \
233       __getopt_nonoption_flags[ch1] = __getopt_nonoption_flags[ch2];          \
234       __getopt_nonoption_flags[ch2] = __tmp;                                  \
235     }
236 # else
237 #  define SWAP_FLAGS(ch1, ch2)
238 # endif
239 #else   /* !_LIBC */
240 # define SWAP_FLAGS(ch1, ch2)
241 #endif  /* _LIBC */
242
243 /* Exchange two adjacent subsequences of ARGV.
244    One subsequence is elements [first_nonopt,last_nonopt)
245    which contains all the non-options that have been skipped so far.
246    The other is elements [last_nonopt,optind), which contains all
247    the options processed since those non-options were skipped.
248
249    `first_nonopt' and `last_nonopt' are relocated so that they describe
250    the new indices of the non-options in ARGV after they are moved.  */
251
252 static void
253 exchange (char **argv)
254 {
255   int bottom = first_nonopt;
256   int middle = last_nonopt;
257   int top = optind;
258   char *tem;
259
260   /* Exchange the shorter segment with the far end of the longer segment.
261      That puts the shorter segment into the right place.
262      It leaves the longer segment in the right place overall,
263      but it consists of two parts that need to be swapped next.  */
264
265 #if defined _LIBC && defined USE_NONOPTION_FLAGS
266   /* First make sure the handling of the `__getopt_nonoption_flags'
267      string can work normally.  Our top argument must be in the range
268      of the string.  */
269   if (nonoption_flags_len > 0 && top >= nonoption_flags_max_len)
270     {
271       /* We must extend the array.  The user plays games with us and
272          presents new arguments.  */
273       char *new_str = malloc (top + 1);
274       if (new_str == NULL)
275         nonoption_flags_len = nonoption_flags_max_len = 0;
276       else
277         {
278           memset (__mempcpy (new_str, __getopt_nonoption_flags,
279                              nonoption_flags_max_len),
280                   '\0', top + 1 - nonoption_flags_max_len);
281           nonoption_flags_max_len = top + 1;
282           __getopt_nonoption_flags = new_str;
283         }
284     }
285 #endif
286
287   while (top > middle && middle > bottom)
288     {
289       if (top - middle > middle - bottom)
290         {
291           /* Bottom segment is the short one.  */
292           int len = middle - bottom;
293           register int i;
294
295           /* Swap it with the top part of the top segment.  */
296           for (i = 0; i < len; i++)
297             {
298               tem = argv[bottom + i];
299               argv[bottom + i] = argv[top - (middle - bottom) + i];
300               argv[top - (middle - bottom) + i] = tem;
301               SWAP_FLAGS (bottom + i, top - (middle - bottom) + i);
302             }
303           /* Exclude the moved bottom segment from further swapping.  */
304           top -= len;
305         }
306       else
307         {
308           /* Top segment is the short one.  */
309           int len = top - middle;
310           register int i;
311
312           /* Swap it with the bottom part of the bottom segment.  */
313           for (i = 0; i < len; i++)
314             {
315               tem = argv[bottom + i];
316               argv[bottom + i] = argv[middle + i];
317               argv[middle + i] = tem;
318               SWAP_FLAGS (bottom + i, middle + i);
319             }
320           /* Exclude the moved top segment from further swapping.  */
321           bottom += len;
322         }
323     }
324
325   /* Update records for the slots the non-options now occupy.  */
326
327   first_nonopt += (optind - last_nonopt);
328   last_nonopt = optind;
329 }
330
331 /* Initialize the internal data when the first call is made.  */
332
333 static const char *
334 _getopt_initialize (int argc, char *const *argv, const char *optstring)
335 {
336   /* Start processing options with ARGV-element 1 (since ARGV-element 0
337      is the program name); the sequence of previously skipped
338      non-option ARGV-elements is empty.  */
339
340   first_nonopt = last_nonopt = optind;
341
342   nextchar = NULL;
343
344   posixly_correct = getenv ("POSIXLY_CORRECT");
345
346   /* Determine how to handle the ordering of options and nonoptions.  */
347
348   if (optstring[0] == '-')
349     {
350       ordering = RETURN_IN_ORDER;
351       ++optstring;
352     }
353   else if (optstring[0] == '+')
354     {
355       ordering = REQUIRE_ORDER;
356       ++optstring;
357     }
358   else if (posixly_correct != NULL)
359     ordering = REQUIRE_ORDER;
360   else
361     ordering = PERMUTE;
362
363 #if defined _LIBC && defined USE_NONOPTION_FLAGS
364   if (posixly_correct == NULL
365       && argc == __libc_argc && argv == __libc_argv)
366     {
367       if (nonoption_flags_max_len == 0)
368         {
369           if (__getopt_nonoption_flags == NULL
370               || __getopt_nonoption_flags[0] == '\0')
371             nonoption_flags_max_len = -1;
372           else
373             {
374               const char *orig_str = __getopt_nonoption_flags;
375               int len = nonoption_flags_max_len = strlen (orig_str);
376               if (nonoption_flags_max_len < argc)
377                 nonoption_flags_max_len = argc;
378               __getopt_nonoption_flags =
379                 (char *) malloc (nonoption_flags_max_len);
380               if (__getopt_nonoption_flags == NULL)
381                 nonoption_flags_max_len = -1;
382               else
383                 memset (__mempcpy (__getopt_nonoption_flags, orig_str, len),
384                         '\0', nonoption_flags_max_len - len);
385             }
386         }
387       nonoption_flags_len = nonoption_flags_max_len;
388     }
389   else
390     nonoption_flags_len = 0;
391 #endif
392
393   return optstring;
394 }
395 \f
396 /* Scan elements of ARGV (whose length is ARGC) for option characters
397    given in OPTSTRING.
398
399    If an element of ARGV starts with '-', and is not exactly "-" or "--",
400    then it is an option element.  The characters of this element
401    (aside from the initial '-') are option characters.  If `getopt'
402    is called repeatedly, it returns successively each of the option characters
403    from each of the option elements.
404
405    If `getopt' finds another option character, it returns that character,
406    updating `optind' and `nextchar' so that the next call to `getopt' can
407    resume the scan with the following option character or ARGV-element.
408
409    If there are no more option characters, `getopt' returns -1.
410    Then `optind' is the index in ARGV of the first ARGV-element
411    that is not an option.  (The ARGV-elements have been permuted
412    so that those that are not options now come last.)
413
414    OPTSTRING is a string containing the legitimate option characters.
415    If an option character is seen that is not listed in OPTSTRING,
416    return '?' after printing an error message.  If you set `opterr' to
417    zero, the error message is suppressed but we still return '?'.
418
419    If a char in OPTSTRING is followed by a colon, that means it wants an arg,
420    so the following text in the same ARGV-element, or the text of the following
421    ARGV-element, is returned in `optarg'.  Two colons mean an option that
422    wants an optional arg; if there is text in the current ARGV-element,
423    it is returned in `optarg', otherwise `optarg' is set to zero.
424
425    If OPTSTRING starts with `-' or `+', it requests different methods of
426    handling the non-option ARGV-elements.
427    See the comments about RETURN_IN_ORDER and REQUIRE_ORDER, above.
428
429    Long-named options begin with `--' instead of `-'.
430    Their names may be abbreviated as long as the abbreviation is unique
431    or is an exact match for some defined option.  If they have an
432    argument, it follows the option name in the same ARGV-element, separated
433    from the option name by a `=', or else the in next ARGV-element.
434    When `getopt' finds a long-named option, it returns 0 if that option's
435    `flag' field is nonzero, the value of the option's `val' field
436    if the `flag' field is zero.
437
438    The elements of ARGV aren't really const, because we permute them.
439    But we pretend they're const in the prototype to be compatible
440    with other systems.
441
442    LONGOPTS is a vector of `struct option' terminated by an
443    element containing a name which is zero.
444
445    LONGIND returns the index in LONGOPT of the long-named option found.
446    It is only valid when a long-named option has been found by the most
447    recent call.
448
449    If LONG_ONLY is nonzero, '-' as well as '--' can introduce
450    long-named options.  */
451
452 int
453 _getopt_internal (int argc, char *const *argv,
454                   const char *optstring, const struct option *longopts,
455                   int *longind, int long_only)
456 {
457   int print_errors = opterr;
458   if (optstring[0] == ':')
459     print_errors = 0;
460
461   if (argc < 1)
462     return -1;
463
464   optarg = NULL;
465
466   if (optind == 0 || !__getopt_initialized)
467     {
468       if (optind == 0)
469         optind = 1;     /* Don't scan ARGV[0], the program name.  */
470       optstring = _getopt_initialize (argc, argv, optstring);
471       __getopt_initialized = 1;
472     }
473
474   /* Test whether ARGV[optind] points to a non-option argument.
475      Either it does not have option syntax, or there is an environment flag
476      from the shell indicating it is not an option.  The later information
477      is only used when the used in the GNU libc.  */
478 #if defined _LIBC && defined USE_NONOPTION_FLAGS
479 # define NONOPTION_P (argv[optind][0] != '-' || argv[optind][1] == '\0'       \
480                       || (optind < nonoption_flags_len                        \
481                           && __getopt_nonoption_flags[optind] == '1'))
482 #else
483 # define NONOPTION_P (argv[optind][0] != '-' || argv[optind][1] == '\0')
484 #endif
485
486   if (nextchar == NULL || *nextchar == '\0')
487     {
488       /* Advance to the next ARGV-element.  */
489
490       /* Give FIRST_NONOPT & LAST_NONOPT rational values if OPTIND has been
491          moved back by the user (who may also have changed the arguments).  */
492       if (last_nonopt > optind)
493         last_nonopt = optind;
494       if (first_nonopt > optind)
495         first_nonopt = optind;
496
497       if (ordering == PERMUTE)
498         {
499           /* If we have just processed some options following some non-options,
500              exchange them so that the options come first.  */
501
502           if (first_nonopt != last_nonopt && last_nonopt != optind)
503             exchange ((char **) argv);
504           else if (last_nonopt != optind)
505             first_nonopt = optind;
506
507           /* Skip any additional non-options
508              and extend the range of non-options previously skipped.  */
509
510           while (optind < argc && NONOPTION_P)
511             optind++;
512           last_nonopt = optind;
513         }
514
515       /* The special ARGV-element `--' means premature end of options.
516          Skip it like a null option,
517          then exchange with previous non-options as if it were an option,
518          then skip everything else like a non-option.  */
519
520       if (optind != argc && !strcmp (argv[optind], "--"))
521         {
522           optind++;
523
524           if (first_nonopt != last_nonopt && last_nonopt != optind)
525             exchange ((char **) argv);
526           else if (first_nonopt == last_nonopt)
527             first_nonopt = optind;
528           last_nonopt = argc;
529
530           optind = argc;
531         }
532
533       /* If we have done all the ARGV-elements, stop the scan
534          and back over any non-options that we skipped and permuted.  */
535
536       if (optind == argc)
537         {
538           /* Set the next-arg-index to point at the non-options
539              that we previously skipped, so the caller will digest them.  */
540           if (first_nonopt != last_nonopt)
541             optind = first_nonopt;
542           return -1;
543         }
544
545       /* If we have come to a non-option and did not permute it,
546          either stop the scan or describe it to the caller and pass it by.  */
547
548       if (NONOPTION_P)
549         {
550           if (ordering == REQUIRE_ORDER)
551             return -1;
552           optarg = argv[optind++];
553           return 1;
554         }
555
556       /* We have found another option-ARGV-element.
557          Skip the initial punctuation.  */
558
559       nextchar = (argv[optind] + 1
560                   + (longopts != NULL && argv[optind][1] == '-'));
561     }
562
563   /* Decode the current option-ARGV-element.  */
564
565   /* Check whether the ARGV-element is a long option.
566
567      If long_only and the ARGV-element has the form "-f", where f is
568      a valid short option, don't consider it an abbreviated form of
569      a long option that starts with f.  Otherwise there would be no
570      way to give the -f short option.
571
572      On the other hand, if there's a long option "fubar" and
573      the ARGV-element is "-fu", do consider that an abbreviation of
574      the long option, just like "--fu", and not "-f" with arg "u".
575
576      This distinction seems to be the most useful approach.  */
577
578   if (longopts != NULL
579       && (argv[optind][1] == '-'
580           || (long_only
581               && (argv[optind][2] || !strchr (optstring, argv[optind][1])))))
582     {
583       char *nameend;
584       const struct option *p;
585       const struct option *pfound = NULL;
586       int exact = 0;
587       int ambig = 0;
588       int indfound = -1;
589       int option_index;
590
591       for (nameend = nextchar; *nameend && *nameend != '='; nameend++)
592         /* Do nothing.  */ ;
593
594       /* Test all long options for either exact match
595          or abbreviated matches.  */
596       for (p = longopts, option_index = 0; p->name; p++, option_index++)
597         if (!strncmp (p->name, nextchar, nameend - nextchar))
598           {
599             if ((unsigned int) (nameend - nextchar)
600                 == (unsigned int) strlen (p->name))
601               {
602                 /* Exact match found.  */
603                 pfound = p;
604                 indfound = option_index;
605                 exact = 1;
606                 break;
607               }
608             else if (pfound == NULL)
609               {
610                 /* First nonexact match found.  */
611                 pfound = p;
612                 indfound = option_index;
613               }
614             else if (long_only
615                      || pfound->has_arg != p->has_arg
616                      || pfound->flag != p->flag
617                      || pfound->val != p->val)
618               /* Second or later nonexact match found.  */
619               ambig = 1;
620           }
621
622       if (ambig && !exact)
623         {
624           if (print_errors)
625             {
626 #if defined _LIBC && defined USE_IN_LIBIO
627               char *buf;
628
629               if (__asprintf (&buf, _("%s: option `%s' is ambiguous\n"),
630                               argv[0], argv[optind]) >= 0)
631                 {
632
633                   if (_IO_fwide (stderr, 0) > 0)
634                     __fwprintf (stderr, L"%s", buf);
635                   else
636                     fputs (buf, stderr);
637
638                   free (buf);
639                 }
640 #else
641               fprintf (stderr, _("%s: option `%s' is ambiguous\n"),
642                        argv[0], argv[optind]);
643 #endif
644             }
645           nextchar += strlen (nextchar);
646           optind++;
647           optopt = 0;
648           return '?';
649         }
650
651       if (pfound != NULL)
652         {
653           option_index = indfound;
654           optind++;
655           if (*nameend)
656             {
657               /* Don't test has_arg with >, because some C compilers don't
658                  allow it to be used on enums.  */
659               if (pfound->has_arg)
660                 optarg = nameend + 1;
661               else
662                 {
663                   if (print_errors)
664                     {
665 #if defined _LIBC && defined USE_IN_LIBIO
666                       char *buf;
667                       int n;
668 #endif
669
670                       if (argv[optind - 1][1] == '-')
671                         {
672                           /* --option */
673 #if defined _LIBC && defined USE_IN_LIBIO
674                           n = __asprintf (&buf, _("\
675 %s: option `--%s' doesn't allow an argument\n"),
676                                           argv[0], pfound->name);
677 #else
678                           fprintf (stderr, _("\
679 %s: option `--%s' doesn't allow an argument\n"),
680                                    argv[0], pfound->name);
681 #endif
682                         }
683                       else
684                         {
685                           /* +option or -option */
686 #if defined _LIBC && defined USE_IN_LIBIO
687                           n = __asprintf (&buf, _("\
688 %s: option `%c%s' doesn't allow an argument\n"),
689                                           argv[0], argv[optind - 1][0],
690                                           pfound->name);
691 #else
692                           fprintf (stderr, _("\
693 %s: option `%c%s' doesn't allow an argument\n"),
694                                    argv[0], argv[optind - 1][0], pfound->name);
695 #endif
696                         }
697
698 #if defined _LIBC && defined USE_IN_LIBIO
699                       if (n >= 0)
700                         {
701                           if (_IO_fwide (stderr, 0) > 0)
702                             __fwprintf (stderr, L"%s", buf);
703                           else
704                             fputs (buf, stderr);
705
706                           free (buf);
707                         }
708 #endif
709                     }
710
711                   nextchar += strlen (nextchar);
712
713                   optopt = pfound->val;
714                   return '?';
715                 }
716             }
717           else if (pfound->has_arg == 1)
718             {
719               if (optind < argc)
720                 optarg = argv[optind++];
721               else
722                 {
723                   if (print_errors)
724                     {
725 #if defined _LIBC && defined USE_IN_LIBIO
726                       char *buf;
727
728                       if (__asprintf (&buf, _("\
729 %s: option `%s' requires an argument\n"),
730                                       argv[0], argv[optind - 1]) >= 0)
731                         {
732                           if (_IO_fwide (stderr, 0) > 0)
733                             __fwprintf (stderr, L"%s", buf);
734                           else
735                             fputs (buf, stderr);
736
737                           free (buf);
738                         }
739 #else
740                       fprintf (stderr,
741                                _("%s: option `%s' requires an argument\n"),
742                                argv[0], argv[optind - 1]);
743 #endif
744                     }
745                   nextchar += strlen (nextchar);
746                   optopt = pfound->val;
747                   return optstring[0] == ':' ? ':' : '?';
748                 }
749             }
750           nextchar += strlen (nextchar);
751           if (longind != NULL)
752             *longind = option_index;
753           if (pfound->flag)
754             {
755               *(pfound->flag) = pfound->val;
756               return 0;
757             }
758           return pfound->val;
759         }
760
761       /* Can't find it as a long option.  If this is not getopt_long_only,
762          or the option starts with '--' or is not a valid short
763          option, then it's an error.
764          Otherwise interpret it as a short option.  */
765       if (!long_only || argv[optind][1] == '-'
766           || strchr (optstring, *nextchar) == NULL)
767         {
768           if (print_errors)
769             {
770 #if defined _LIBC && defined USE_IN_LIBIO
771               char *buf;
772               int n;
773 #endif
774
775               if (argv[optind][1] == '-')
776                 {
777                   /* --option */
778 #if defined _LIBC && defined USE_IN_LIBIO
779                   n = __asprintf (&buf, _("%s: unrecognized option `--%s'\n"),
780                                   argv[0], nextchar);
781 #else
782                   fprintf (stderr, _("%s: unrecognized option `--%s'\n"),
783                            argv[0], nextchar);
784 #endif
785                 }
786               else
787                 {
788                   /* +option or -option */
789 #if defined _LIBC && defined USE_IN_LIBIO
790                   n = __asprintf (&buf, _("%s: unrecognized option `%c%s'\n"),
791                                   argv[0], argv[optind][0], nextchar);
792 #else
793                   fprintf (stderr, _("%s: unrecognized option `%c%s'\n"),
794                            argv[0], argv[optind][0], nextchar);
795 #endif
796                 }
797
798 #if defined _LIBC && defined USE_IN_LIBIO
799               if (n >= 0)
800                 {
801                   if (_IO_fwide (stderr, 0) > 0)
802                     __fwprintf (stderr, L"%s", buf);
803                   else
804                     fputs (buf, stderr);
805
806                   free (buf);
807                 }
808 #endif
809             }
810           nextchar = (char *) "";
811           optind++;
812           optopt = 0;
813           return '?';
814         }
815     }
816
817   /* Look at and handle the next short option-character.  */
818
819   {
820     char c = *nextchar++;
821     char *temp = strchr (optstring, c);
822
823     /* Increment `optind' when we start to process its last character.  */
824     if (*nextchar == '\0')
825       ++optind;
826
827     if (temp == NULL || c == ':')
828       {
829         if (print_errors)
830           {
831 #if defined _LIBC && defined USE_IN_LIBIO
832               char *buf;
833               int n;
834 #endif
835
836             if (posixly_correct)
837               {
838                 /* 1003.2 specifies the format of this message.  */
839 #if defined _LIBC && defined USE_IN_LIBIO
840                 n = __asprintf (&buf, _("%s: illegal option -- %c\n"),
841                                 argv[0], c);
842 #else
843                 fprintf (stderr, _("%s: illegal option -- %c\n"), argv[0], c);
844 #endif
845               }
846             else
847               {
848 #if defined _LIBC && defined USE_IN_LIBIO
849                 n = __asprintf (&buf, _("%s: invalid option -- %c\n"),
850                                 argv[0], c);
851 #else
852                 fprintf (stderr, _("%s: invalid option -- %c\n"), argv[0], c);
853 #endif
854               }
855
856 #if defined _LIBC && defined USE_IN_LIBIO
857             if (n >= 0)
858               {
859                 if (_IO_fwide (stderr, 0) > 0)
860                   __fwprintf (stderr, L"%s", buf);
861                 else
862                   fputs (buf, stderr);
863
864                 free (buf);
865               }
866 #endif
867           }
868         optopt = c;
869         return '?';
870       }
871     /* Convenience. Treat POSIX -W foo same as long option --foo */
872     if (temp[0] == 'W' && temp[1] == ';')
873       {
874         char *nameend;
875         const struct option *p;
876         const struct option *pfound = NULL;
877         int exact = 0;
878         int ambig = 0;
879         int indfound = 0;
880         int option_index;
881
882         /* This is an option that requires an argument.  */
883         if (*nextchar != '\0')
884           {
885             optarg = nextchar;
886             /* If we end this ARGV-element by taking the rest as an arg,
887                we must advance to the next element now.  */
888             optind++;
889           }
890         else if (optind == argc)
891           {
892             if (print_errors)
893               {
894                 /* 1003.2 specifies the format of this message.  */
895 #if defined _LIBC && defined USE_IN_LIBIO
896                 char *buf;
897
898                 if (__asprintf (&buf,
899                                 _("%s: option requires an argument -- %c\n"),
900                                 argv[0], c) >= 0)
901                   {
902                     if (_IO_fwide (stderr, 0) > 0)
903                       __fwprintf (stderr, L"%s", buf);
904                     else
905                       fputs (buf, stderr);
906
907                     free (buf);
908                   }
909 #else
910                 fprintf (stderr, _("%s: option requires an argument -- %c\n"),
911                          argv[0], c);
912 #endif
913               }
914             optopt = c;
915             if (optstring[0] == ':')
916               c = ':';
917             else
918               c = '?';
919             return c;
920           }
921         else
922           /* We already incremented `optind' once;
923              increment it again when taking next ARGV-elt as argument.  */
924           optarg = argv[optind++];
925
926         /* optarg is now the argument, see if it's in the
927            table of longopts.  */
928
929         for (nextchar = nameend = optarg; *nameend && *nameend != '='; nameend++)
930           /* Do nothing.  */ ;
931
932         /* Test all long options for either exact match
933            or abbreviated matches.  */
934         for (p = longopts, option_index = 0; p->name; p++, option_index++)
935           if (!strncmp (p->name, nextchar, nameend - nextchar))
936             {
937               if ((unsigned int) (nameend - nextchar) == strlen (p->name))
938                 {
939                   /* Exact match found.  */
940                   pfound = p;
941                   indfound = option_index;
942                   exact = 1;
943                   break;
944                 }
945               else if (pfound == NULL)
946                 {
947                   /* First nonexact match found.  */
948                   pfound = p;
949                   indfound = option_index;
950                 }
951               else
952                 /* Second or later nonexact match found.  */
953                 ambig = 1;
954             }
955         if (ambig && !exact)
956           {
957             if (print_errors)
958               {
959 #if defined _LIBC && defined USE_IN_LIBIO
960                 char *buf;
961
962                 if (__asprintf (&buf, _("%s: option `-W %s' is ambiguous\n"),
963                                 argv[0], argv[optind]) >= 0)
964                   {
965                     if (_IO_fwide (stderr, 0) > 0)
966                       __fwprintf (stderr, L"%s", buf);
967                     else
968                       fputs (buf, stderr);
969
970                     free (buf);
971                   }
972 #else
973                 fprintf (stderr, _("%s: option `-W %s' is ambiguous\n"),
974                          argv[0], argv[optind]);
975 #endif
976               }
977             nextchar += strlen (nextchar);
978             optind++;
979             return '?';
980           }
981         if (pfound != NULL)
982           {
983             option_index = indfound;
984             if (*nameend)
985               {
986                 /* Don't test has_arg with >, because some C compilers don't
987                    allow it to be used on enums.  */
988                 if (pfound->has_arg)
989                   optarg = nameend + 1;
990                 else
991                   {
992                     if (print_errors)
993                       {
994 #if defined _LIBC && defined USE_IN_LIBIO
995                         char *buf;
996
997                         if (__asprintf (&buf, _("\
998 %s: option `-W %s' doesn't allow an argument\n"),
999                                         argv[0], pfound->name) >= 0)
1000                           {
1001                             if (_IO_fwide (stderr, 0) > 0)
1002                               __fwprintf (stderr, L"%s", buf);
1003                             else
1004                               fputs (buf, stderr);
1005
1006                             free (buf);
1007                           }
1008 #else
1009                         fprintf (stderr, _("\
1010 %s: option `-W %s' doesn't allow an argument\n"),
1011                                  argv[0], pfound->name);
1012 #endif
1013                       }
1014
1015                     nextchar += strlen (nextchar);
1016                     return '?';
1017                   }
1018               }
1019             else if (pfound->has_arg == 1)
1020               {
1021                 if (optind < argc)
1022                   optarg = argv[optind++];
1023                 else
1024                   {
1025                     if (print_errors)
1026                       {
1027 #if defined _LIBC && defined USE_IN_LIBIO
1028                         char *buf;
1029
1030                         if (__asprintf (&buf, _("\
1031 %s: option `%s' requires an argument\n"),
1032                                         argv[0], argv[optind - 1]) >= 0)
1033                           {
1034                             if (_IO_fwide (stderr, 0) > 0)
1035                               __fwprintf (stderr, L"%s", buf);
1036                             else
1037                               fputs (buf, stderr);
1038
1039                             free (buf);
1040                           }
1041 #else
1042                         fprintf (stderr,
1043                                  _("%s: option `%s' requires an argument\n"),
1044                                  argv[0], argv[optind - 1]);
1045 #endif
1046                       }
1047                     nextchar += strlen (nextchar);
1048                     return optstring[0] == ':' ? ':' : '?';
1049                   }
1050               }
1051             nextchar += strlen (nextchar);
1052             if (longind != NULL)
1053               *longind = option_index;
1054             if (pfound->flag)
1055               {
1056                 *(pfound->flag) = pfound->val;
1057                 return 0;
1058               }
1059             return pfound->val;
1060           }
1061           nextchar = NULL;
1062           return 'W';   /* Let the application handle it.   */
1063       }
1064     if (temp[1] == ':')
1065       {
1066         if (temp[2] == ':')
1067           {
1068             /* This is an option that accepts an argument optionally.  */
1069             if (*nextchar != '\0')
1070               {
1071                 optarg = nextchar;
1072                 optind++;
1073               }
1074             else
1075               optarg = NULL;
1076             nextchar = NULL;
1077           }
1078         else
1079           {
1080             /* This is an option that requires an argument.  */
1081             if (*nextchar != '\0')
1082               {
1083                 optarg = nextchar;
1084                 /* If we end this ARGV-element by taking the rest as an arg,
1085                    we must advance to the next element now.  */
1086                 optind++;
1087               }
1088             else if (optind == argc)
1089               {
1090                 if (print_errors)
1091                   {
1092                     /* 1003.2 specifies the format of this message.  */
1093 #if defined _LIBC && defined USE_IN_LIBIO
1094                     char *buf;
1095
1096                     if (__asprintf (&buf, _("\
1097 %s: option requires an argument -- %c\n"),
1098                                     argv[0], c) >= 0)
1099                       {
1100                         if (_IO_fwide (stderr, 0) > 0)
1101                           __fwprintf (stderr, L"%s", buf);
1102                         else
1103                           fputs (buf, stderr);
1104
1105                         free (buf);
1106                       }
1107 #else
1108                     fprintf (stderr,
1109                              _("%s: option requires an argument -- %c\n"),
1110                              argv[0], c);
1111 #endif
1112                   }
1113                 optopt = c;
1114                 if (optstring[0] == ':')
1115                   c = ':';
1116                 else
1117                   c = '?';
1118               }
1119             else
1120               /* We already incremented `optind' once;
1121                  increment it again when taking next ARGV-elt as argument.  */
1122               optarg = argv[optind++];
1123             nextchar = NULL;
1124           }
1125       }
1126     return c;
1127   }
1128 }
1129
1130 int
1131 getopt (int argc, char *const *argv, const char *optstring)
1132 {
1133   return _getopt_internal (argc, argv, optstring,
1134                            (const struct option *) 0,
1135                            (int *) 0,
1136                            0);
1137 }
1138
1139 #endif  /* Not ELIDE_CODE.  */
1140 \f
1141 #ifdef TEST
1142
1143 /* Compile with -DTEST to make an executable for use in testing
1144    the above definition of `getopt'.  */
1145
1146 int
1147 main (int argc, char **argv)
1148 {
1149   int c;
1150   int digit_optind = 0;
1151
1152   while (1)
1153     {
1154       int this_option_optind = optind ? optind : 1;
1155
1156       c = getopt (argc, argv, "abc:d:0123456789");
1157       if (c == -1)
1158         break;
1159
1160       switch (c)
1161         {
1162         case '0':
1163         case '1':
1164         case '2':
1165         case '3':
1166         case '4':
1167         case '5':
1168         case '6':
1169         case '7':
1170         case '8':
1171         case '9':
1172           if (digit_optind != 0 && digit_optind != this_option_optind)
1173             printf ("digits occur in two different argv-elements.\n");
1174           digit_optind = this_option_optind;
1175           printf ("option %c\n", c);
1176           break;
1177
1178         case 'a':
1179           printf ("option a\n");
1180           break;
1181
1182         case 'b':
1183           printf ("option b\n");
1184           break;
1185
1186         case 'c':
1187           printf ("option c with value `%s'\n", optarg);
1188           break;
1189
1190         case '?':
1191           break;
1192
1193         default:
1194           printf ("?? getopt returned character code 0%o ??\n", c);
1195         }
1196     }
1197
1198   if (optind < argc)
1199     {
1200       printf ("non-option ARGV-elements: ");
1201       while (optind < argc)
1202         printf ("%s ", argv[optind++]);
1203       printf ("\n");
1204     }
1205
1206   exit (0);
1207 }
1208
1209 #endif /* TEST */