GNU shell utilities
[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 roland@gnu.ai.mit.edu
4    before changing it!
5
6    Copyright (C) 1987, 88, 89, 90, 91, 92, 93, 94
7         Free Software Foundation, Inc.
8
9    This program is free software; you can redistribute it and/or modify it
10    under the terms of the GNU General Public License as published by the
11    Free Software Foundation; either version 2, or (at your option) any
12    later version.
13
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License for more details.
18
19    You should have received a copy of the GNU General Public License
20    along with this program; if not, write to the Free Software
21    Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.  */
22 \f
23 /* This tells Alpha OSF/1 not to define a getopt prototype in <stdio.h>.
24    Ditto for AIX 3.2 and <stdlib.h>.  */
25 #ifndef _NO_PROTO
26 #define _NO_PROTO
27 #endif
28
29 #ifdef HAVE_CONFIG_H
30 #if defined (emacs) || defined (CONFIG_BROKETS)
31 /* We use <config.h> instead of "config.h" so that a compilation
32    using -I. -I$srcdir will use ./config.h rather than $srcdir/config.h
33    (which it would do because it found this file in $srcdir).  */
34 #include <config.h>
35 #else
36 #include "config.h"
37 #endif
38 #endif
39
40 #ifndef __STDC__
41 /* This is a separate conditional since some stdc systems
42    reject `defined (const)'.  */
43 #ifndef const
44 #define const
45 #endif
46 #endif
47
48 #include <stdio.h>
49
50 /* Comment out all this code if we are using the GNU C Library, and are not
51    actually compiling the library itself.  This code is part of the GNU C
52    Library, but also included in many other GNU distributions.  Compiling
53    and linking in this code is a waste when using the GNU C library
54    (especially if it is a shared library).  Rather than having every GNU
55    program understand `configure --with-gnu-libc' and omit the object files,
56    it is simpler to just do this in the source for each such file.  */
57
58 #if defined (_LIBC) || !defined (__GNU_LIBRARY__)
59
60
61 /* This needs to come after some library #include
62    to get __GNU_LIBRARY__ defined.  */
63 #ifdef  __GNU_LIBRARY__
64 /* Don't include stdlib.h for non-GNU C libraries because some of them
65    contain conflicting prototypes for getopt.  */
66 #include <stdlib.h>
67 #endif  /* GNU C library.  */
68
69 /* This version of `getopt' appears to the caller like standard Unix `getopt'
70    but it behaves differently for the user, since it allows the user
71    to intersperse the options with the other arguments.
72
73    As `getopt' works, it permutes the elements of ARGV so that,
74    when it is done, all the options precede everything else.  Thus
75    all application programs are extended to handle flexible argument order.
76
77    Setting the environment variable POSIXLY_CORRECT disables permutation.
78    Then the behavior is completely standard.
79
80    GNU application programs can use a third alternative mode in which
81    they can distinguish the relative order of options and other arguments.  */
82
83 #include "getopt.h"
84
85 /* For communication from `getopt' to the caller.
86    When `getopt' finds an option that takes an argument,
87    the argument value is returned here.
88    Also, when `ordering' is RETURN_IN_ORDER,
89    each non-option ARGV-element is returned here.  */
90
91 char *optarg = NULL;
92
93 /* Index in ARGV of the next element to be scanned.
94    This is used for communication to and from the caller
95    and for communication between successive calls to `getopt'.
96
97    On entry to `getopt', zero means this is the first call; initialize.
98
99    When `getopt' returns EOF, this is the index of the first of the
100    non-option elements that the caller should itself scan.
101
102    Otherwise, `optind' communicates from one call to the next
103    how much of ARGV has been scanned so far.  */
104
105 /* XXX 1003.2 says this must be 1 before any call.  */
106 int optind = 0;
107
108 /* The next char to be scanned in the option-element
109    in which the last option character we returned was found.
110    This allows us to pick up the scan where we left off.
111
112    If this is zero, or a null string, it means resume the scan
113    by advancing to the next ARGV-element.  */
114
115 static char *nextchar;
116
117 /* Callers store zero here to inhibit the error message
118    for unrecognized options.  */
119
120 int opterr = 1;
121
122 /* Set to an option character which was unrecognized.
123    This must be initialized on some systems to avoid linking in the
124    system's own getopt implementation.  */
125
126 int optopt = '?';
127
128 /* Describe how to deal with options that follow non-option ARGV-elements.
129
130    If the caller did not specify anything,
131    the default is REQUIRE_ORDER if the environment variable
132    POSIXLY_CORRECT is defined, PERMUTE otherwise.
133
134    REQUIRE_ORDER means don't recognize them as options;
135    stop option processing when the first non-option is seen.
136    This is what Unix does.
137    This mode of operation is selected by either setting the environment
138    variable POSIXLY_CORRECT, or using `+' as the first character
139    of the list of option characters.
140
141    PERMUTE is the default.  We permute the contents of ARGV as we scan,
142    so that eventually all the non-options are at the end.  This allows options
143    to be given in any order, even with programs that were not written to
144    expect this.
145
146    RETURN_IN_ORDER is an option available to programs that were written
147    to expect options and other ARGV-elements in any order and that care about
148    the ordering of the two.  We describe each non-option ARGV-element
149    as if it were the argument of an option with character code 1.
150    Using `-' as the first character of the list of option characters
151    selects this mode of operation.
152
153    The special argument `--' forces an end of option-scanning regardless
154    of the value of `ordering'.  In the case of RETURN_IN_ORDER, only
155    `--' can cause `getopt' to return EOF with `optind' != ARGC.  */
156
157 static enum
158 {
159   REQUIRE_ORDER, PERMUTE, RETURN_IN_ORDER
160 } ordering;
161 \f
162 #ifdef  __GNU_LIBRARY__
163 /* We want to avoid inclusion of string.h with non-GNU libraries
164    because there are many ways it can cause trouble.
165    On some systems, it contains special magic macros that don't work
166    in GCC.  */
167 #include <string.h>
168 #define my_index        strchr
169 #else
170
171 /* Avoid depending on library functions or files
172    whose names are inconsistent.  */
173
174 char *getenv ();
175
176 static char *
177 my_index (str, chr)
178      const char *str;
179      int chr;
180 {
181   while (*str)
182     {
183       if (*str == chr)
184         return (char *) str;
185       str++;
186     }
187   return 0;
188 }
189
190 /* If using GCC, we can safely declare strlen this way.
191    If not using GCC, it is ok not to declare it.  */
192 #ifdef __GNUC__
193 /* Note that Motorola Delta 68k R3V7 comes with GCC but not stddef.h.
194    That was relevant to code that was here before.  */
195 #ifndef __STDC__
196 /* gcc with -traditional declares the built-in strlen to return int,
197    and has done so at least since version 2.4.5. -- rms.  */
198 extern int strlen (const char *);
199 #endif /* not __STDC__ */
200 #endif /* __GNUC__ */
201
202 #endif /* not __GNU_LIBRARY__ */
203 \f
204 /* Handle permutation of arguments.  */
205
206 /* Describe the part of ARGV that contains non-options that have
207    been skipped.  `first_nonopt' is the index in ARGV of the first of them;
208    `last_nonopt' is the index after the last of them.  */
209
210 static int first_nonopt;
211 static int last_nonopt;
212
213 /* Exchange two adjacent subsequences of ARGV.
214    One subsequence is elements [first_nonopt,last_nonopt)
215    which contains all the non-options that have been skipped so far.
216    The other is elements [last_nonopt,optind), which contains all
217    the options processed since those non-options were skipped.
218
219    `first_nonopt' and `last_nonopt' are relocated so that they describe
220    the new indices of the non-options in ARGV after they are moved.  */
221
222 static void
223 exchange (argv)
224      char **argv;
225 {
226   int bottom = first_nonopt;
227   int middle = last_nonopt;
228   int top = optind;
229   char *tem;
230
231   /* Exchange the shorter segment with the far end of the longer segment.
232      That puts the shorter segment into the right place.
233      It leaves the longer segment in the right place overall,
234      but it consists of two parts that need to be swapped next.  */
235
236   while (top > middle && middle > bottom)
237     {
238       if (top - middle > middle - bottom)
239         {
240           /* Bottom segment is the short one.  */
241           int len = middle - bottom;
242           register int i;
243
244           /* Swap it with the top part of the top segment.  */
245           for (i = 0; i < len; i++)
246             {
247               tem = argv[bottom + i];
248               argv[bottom + i] = argv[top - (middle - bottom) + i];
249               argv[top - (middle - bottom) + i] = tem;
250             }
251           /* Exclude the moved bottom segment from further swapping.  */
252           top -= len;
253         }
254       else
255         {
256           /* Top segment is the short one.  */
257           int len = top - middle;
258           register int i;
259
260           /* Swap it with the bottom part of the bottom segment.  */
261           for (i = 0; i < len; i++)
262             {
263               tem = argv[bottom + i];
264               argv[bottom + i] = argv[middle + i];
265               argv[middle + i] = tem;
266             }
267           /* Exclude the moved top segment from further swapping.  */
268           bottom += len;
269         }
270     }
271
272   /* Update records for the slots the non-options now occupy.  */
273
274   first_nonopt += (optind - last_nonopt);
275   last_nonopt = optind;
276 }
277
278 /* Initialize the internal data when the first call is made.  */
279
280 static const char *
281 _getopt_initialize (optstring)
282      const char *optstring;
283 {
284   /* Start processing options with ARGV-element 1 (since ARGV-element 0
285      is the program name); the sequence of previously skipped
286      non-option ARGV-elements is empty.  */
287
288   first_nonopt = last_nonopt = optind = 1;
289
290   nextchar = NULL;
291
292   /* Determine how to handle the ordering of options and nonoptions.  */
293
294   if (optstring[0] == '-')
295     {
296       ordering = RETURN_IN_ORDER;
297       ++optstring;
298     }
299   else if (optstring[0] == '+')
300     {
301       ordering = REQUIRE_ORDER;
302       ++optstring;
303     }
304   else if (getenv ("POSIXLY_CORRECT") != NULL)
305     ordering = REQUIRE_ORDER;
306   else
307     ordering = PERMUTE;
308
309   return optstring;
310 }
311 \f
312 /* Scan elements of ARGV (whose length is ARGC) for option characters
313    given in OPTSTRING.
314
315    If an element of ARGV starts with '-', and is not exactly "-" or "--",
316    then it is an option element.  The characters of this element
317    (aside from the initial '-') are option characters.  If `getopt'
318    is called repeatedly, it returns successively each of the option characters
319    from each of the option elements.
320
321    If `getopt' finds another option character, it returns that character,
322    updating `optind' and `nextchar' so that the next call to `getopt' can
323    resume the scan with the following option character or ARGV-element.
324
325    If there are no more option characters, `getopt' returns `EOF'.
326    Then `optind' is the index in ARGV of the first ARGV-element
327    that is not an option.  (The ARGV-elements have been permuted
328    so that those that are not options now come last.)
329
330    OPTSTRING is a string containing the legitimate option characters.
331    If an option character is seen that is not listed in OPTSTRING,
332    return '?' after printing an error message.  If you set `opterr' to
333    zero, the error message is suppressed but we still return '?'.
334
335    If a char in OPTSTRING is followed by a colon, that means it wants an arg,
336    so the following text in the same ARGV-element, or the text of the following
337    ARGV-element, is returned in `optarg'.  Two colons mean an option that
338    wants an optional arg; if there is text in the current ARGV-element,
339    it is returned in `optarg', otherwise `optarg' is set to zero.
340
341    If OPTSTRING starts with `-' or `+', it requests different methods of
342    handling the non-option ARGV-elements.
343    See the comments about RETURN_IN_ORDER and REQUIRE_ORDER, above.
344
345    Long-named options begin with `--' instead of `-'.
346    Their names may be abbreviated as long as the abbreviation is unique
347    or is an exact match for some defined option.  If they have an
348    argument, it follows the option name in the same ARGV-element, separated
349    from the option name by a `=', or else the in next ARGV-element.
350    When `getopt' finds a long-named option, it returns 0 if that option's
351    `flag' field is nonzero, the value of the option's `val' field
352    if the `flag' field is zero.
353
354    The elements of ARGV aren't really const, because we permute them.
355    But we pretend they're const in the prototype to be compatible
356    with other systems.
357
358    LONGOPTS is a vector of `struct option' terminated by an
359    element containing a name which is zero.
360
361    LONGIND returns the index in LONGOPT of the long-named option found.
362    It is only valid when a long-named option has been found by the most
363    recent call.
364
365    If LONG_ONLY is nonzero, '-' as well as '--' can introduce
366    long-named options.  */
367
368 int
369 _getopt_internal (argc, argv, optstring, longopts, longind, long_only)
370      int argc;
371      char *const *argv;
372      const char *optstring;
373      const struct option *longopts;
374      int *longind;
375      int long_only;
376 {
377   optarg = NULL;
378
379   if (optind == 0)
380     optstring = _getopt_initialize (optstring);
381
382   if (nextchar == NULL || *nextchar == '\0')
383     {
384       /* Advance to the next ARGV-element.  */
385
386       if (ordering == PERMUTE)
387         {
388           /* If we have just processed some options following some non-options,
389              exchange them so that the options come first.  */
390
391           if (first_nonopt != last_nonopt && last_nonopt != optind)
392             exchange ((char **) argv);
393           else if (last_nonopt != optind)
394             first_nonopt = optind;
395
396           /* Skip any additional non-options
397              and extend the range of non-options previously skipped.  */
398
399           while (optind < argc
400                  && (argv[optind][0] != '-' || argv[optind][1] == '\0'))
401             optind++;
402           last_nonopt = optind;
403         }
404
405       /* The special ARGV-element `--' means premature end of options.
406          Skip it like a null option,
407          then exchange with previous non-options as if it were an option,
408          then skip everything else like a non-option.  */
409
410       if (optind != argc && !strcmp (argv[optind], "--"))
411         {
412           optind++;
413
414           if (first_nonopt != last_nonopt && last_nonopt != optind)
415             exchange ((char **) argv);
416           else if (first_nonopt == last_nonopt)
417             first_nonopt = optind;
418           last_nonopt = argc;
419
420           optind = argc;
421         }
422
423       /* If we have done all the ARGV-elements, stop the scan
424          and back over any non-options that we skipped and permuted.  */
425
426       if (optind == argc)
427         {
428           /* Set the next-arg-index to point at the non-options
429              that we previously skipped, so the caller will digest them.  */
430           if (first_nonopt != last_nonopt)
431             optind = first_nonopt;
432           return EOF;
433         }
434
435       /* If we have come to a non-option and did not permute it,
436          either stop the scan or describe it to the caller and pass it by.  */
437
438       if ((argv[optind][0] != '-' || argv[optind][1] == '\0'))
439         {
440           if (ordering == REQUIRE_ORDER)
441             return EOF;
442           optarg = argv[optind++];
443           return 1;
444         }
445
446       /* We have found another option-ARGV-element.
447          Skip the initial punctuation.  */
448
449       nextchar = (argv[optind] + 1
450                   + (longopts != NULL && argv[optind][1] == '-'));
451     }
452
453   /* Decode the current option-ARGV-element.  */
454
455   /* Check whether the ARGV-element is a long option.
456
457      If long_only and the ARGV-element has the form "-f", where f is
458      a valid short option, don't consider it an abbreviated form of
459      a long option that starts with f.  Otherwise there would be no
460      way to give the -f short option.
461
462      On the other hand, if there's a long option "fubar" and
463      the ARGV-element is "-fu", do consider that an abbreviation of
464      the long option, just like "--fu", and not "-f" with arg "u".
465
466      This distinction seems to be the most useful approach.  */
467
468   if (longopts != NULL
469       && (argv[optind][1] == '-'
470           || (long_only && (argv[optind][2] || !my_index (optstring, argv[optind][1])))))
471     {
472       char *nameend;
473       const struct option *p;
474       const struct option *pfound = NULL;
475       int exact = 0;
476       int ambig = 0;
477       int indfound;
478       int option_index;
479
480       for (nameend = nextchar; *nameend && *nameend != '='; nameend++)
481         /* Do nothing.  */ ;
482
483       /* Test all long options for either exact match
484          or abbreviated matches.  */
485       for (p = longopts, option_index = 0; p->name; p++, option_index++)
486         if (!strncmp (p->name, nextchar, nameend - nextchar))
487           {
488             if (nameend - nextchar == strlen (p->name))
489               {
490                 /* Exact match found.  */
491                 pfound = p;
492                 indfound = option_index;
493                 exact = 1;
494                 break;
495               }
496             else if (pfound == NULL)
497               {
498                 /* First nonexact match found.  */
499                 pfound = p;
500                 indfound = option_index;
501               }
502             else
503               /* Second or later nonexact match found.  */
504               ambig = 1;
505           }
506
507       if (ambig && !exact)
508         {
509           if (opterr)
510             fprintf (stderr, "%s: option `%s' is ambiguous\n",
511                      argv[0], argv[optind]);
512           nextchar += strlen (nextchar);
513           optind++;
514           return '?';
515         }
516
517       if (pfound != NULL)
518         {
519           option_index = indfound;
520           optind++;
521           if (*nameend)
522             {
523               /* Don't test has_arg with >, because some C compilers don't
524                  allow it to be used on enums.  */
525               if (pfound->has_arg)
526                 optarg = nameend + 1;
527               else
528                 {
529                   if (opterr)
530                     {
531                       if (argv[optind - 1][1] == '-')
532                         /* --option */
533                         fprintf (stderr,
534                                  "%s: option `--%s' doesn't allow an argument\n",
535                                  argv[0], pfound->name);
536                       else
537                         /* +option or -option */
538                         fprintf (stderr,
539                              "%s: option `%c%s' doesn't allow an argument\n",
540                              argv[0], argv[optind - 1][0], pfound->name);
541                     }
542                   nextchar += strlen (nextchar);
543                   return '?';
544                 }
545             }
546           else if (pfound->has_arg == 1)
547             {
548               if (optind < argc)
549                 optarg = argv[optind++];
550               else
551                 {
552                   if (opterr)
553                     fprintf (stderr, "%s: option `%s' requires an argument\n",
554                              argv[0], argv[optind - 1]);
555                   nextchar += strlen (nextchar);
556                   return optstring[0] == ':' ? ':' : '?';
557                 }
558             }
559           nextchar += strlen (nextchar);
560           if (longind != NULL)
561             *longind = option_index;
562           if (pfound->flag)
563             {
564               *(pfound->flag) = pfound->val;
565               return 0;
566             }
567           return pfound->val;
568         }
569
570       /* Can't find it as a long option.  If this is not getopt_long_only,
571          or the option starts with '--' or is not a valid short
572          option, then it's an error.
573          Otherwise interpret it as a short option.  */
574       if (!long_only || argv[optind][1] == '-'
575           || my_index (optstring, *nextchar) == NULL)
576         {
577           if (opterr)
578             {
579               if (argv[optind][1] == '-')
580                 /* --option */
581                 fprintf (stderr, "%s: unrecognized option `--%s'\n",
582                          argv[0], nextchar);
583               else
584                 /* +option or -option */
585                 fprintf (stderr, "%s: unrecognized option `%c%s'\n",
586                          argv[0], argv[optind][0], nextchar);
587             }
588           nextchar = (char *) "";
589           optind++;
590           return '?';
591         }
592     }
593
594   /* Look at and handle the next short option-character.  */
595
596   {
597     char c = *nextchar++;
598     char *temp = my_index (optstring, c);
599
600     /* Increment `optind' when we start to process its last character.  */
601     if (*nextchar == '\0')
602       ++optind;
603
604     if (temp == NULL || c == ':')
605       {
606         if (opterr)
607           {
608             /* 1003.2 specifies the format of this message.  */
609             fprintf (stderr, "%s: illegal option -- %c\n", argv[0], c);
610           }
611         optopt = c;
612         return '?';
613       }
614     if (temp[1] == ':')
615       {
616         if (temp[2] == ':')
617           {
618             /* This is an option that accepts an argument optionally.  */
619             if (*nextchar != '\0')
620               {
621                 optarg = nextchar;
622                 optind++;
623               }
624             else
625               optarg = NULL;
626             nextchar = NULL;
627           }
628         else
629           {
630             /* This is an option that requires an argument.  */
631             if (*nextchar != '\0')
632               {
633                 optarg = nextchar;
634                 /* If we end this ARGV-element by taking the rest as an arg,
635                    we must advance to the next element now.  */
636                 optind++;
637               }
638             else if (optind == argc)
639               {
640                 if (opterr)
641                   {
642                     /* 1003.2 specifies the format of this message.  */
643                     fprintf (stderr, "%s: option requires an argument -- %c\n",
644                              argv[0], c);
645                   }
646                 optopt = c;
647                 if (optstring[0] == ':')
648                   c = ':';
649                 else
650                   c = '?';
651               }
652             else
653               /* We already incremented `optind' once;
654                  increment it again when taking next ARGV-elt as argument.  */
655               optarg = argv[optind++];
656             nextchar = NULL;
657           }
658       }
659     return c;
660   }
661 }
662
663 int
664 getopt (argc, argv, optstring)
665      int argc;
666      char *const *argv;
667      const char *optstring;
668 {
669   return _getopt_internal (argc, argv, optstring,
670                            (const struct option *) 0,
671                            (int *) 0,
672                            0);
673 }
674
675 #endif  /* _LIBC or not __GNU_LIBRARY__.  */
676 \f
677 #ifdef TEST
678
679 /* Compile with -DTEST to make an executable for use in testing
680    the above definition of `getopt'.  */
681
682 int
683 main (argc, argv)
684      int argc;
685      char **argv;
686 {
687   int c;
688   int digit_optind = 0;
689
690   while (1)
691     {
692       int this_option_optind = optind ? optind : 1;
693
694       c = getopt (argc, argv, "abc:d:0123456789");
695       if (c == EOF)
696         break;
697
698       switch (c)
699         {
700         case '0':
701         case '1':
702         case '2':
703         case '3':
704         case '4':
705         case '5':
706         case '6':
707         case '7':
708         case '8':
709         case '9':
710           if (digit_optind != 0 && digit_optind != this_option_optind)
711             printf ("digits occur in two different argv-elements.\n");
712           digit_optind = this_option_optind;
713           printf ("option %c\n", c);
714           break;
715
716         case 'a':
717           printf ("option a\n");
718           break;
719
720         case 'b':
721           printf ("option b\n");
722           break;
723
724         case 'c':
725           printf ("option c with value `%s'\n", optarg);
726           break;
727
728         case '?':
729           break;
730
731         default:
732           printf ("?? getopt returned character code 0%o ??\n", c);
733         }
734     }
735
736   if (optind < argc)
737     {
738       printf ("non-option ARGV-elements: ");
739       while (optind < argc)
740         printf ("%s ", argv[optind++]);
741       printf ("\n");
742     }
743
744   exit (0);
745 }
746
747 #endif /* TEST */