Expand PMF_FN_* macros.
[netbsd-mini2440.git] / usr.bin / sed / getopt.c
blob8c0ba2e29ff5df9c165ee2482637b3d696493973
1 /* Getopt for GNU.
2 Copyright (C) 1987, 1989, 1990, 1991 Free Software Foundation, Inc.
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 2, or (at your option)
7 any later version.
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.
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */
18 /* AIX requires this to be the first thing in the file. */
19 #ifdef __GNUC__
20 #define alloca __builtin_alloca
21 #else /* not __GNUC__ */
22 #ifdef sparc
23 #include <alloca.h>
24 #else
25 #ifdef _AIX
26 #pragma alloca
27 #else
28 char *alloca ();
29 #endif
30 #endif /* sparc */
31 #endif /* not __GNUC__ */
33 #ifndef __STDC__
34 #define const
35 #endif
37 /* This version of `getopt' appears to the caller like standard Unix `getopt'
38 but it behaves differently for the user, since it allows the user
39 to intersperse the options with the other arguments.
41 As `getopt' works, it permutes the elements of `argv' so that,
42 when it is done, all the options precede everything else. Thus
43 all application programs are extended to handle flexible argument order.
45 Setting the environment variable _POSIX_OPTION_ORDER disables permutation.
46 Then the behavior is completely standard.
48 GNU application programs can use a third alternative mode in which
49 they can distinguish the relative order of options and other arguments. */
51 #include <stdio.h>
53 #if defined(STDC_HEADERS) || defined(__GNU_LIBRARY__)
54 #include <stdlib.h>
55 #else /* STDC_HEADERS or __GNU_LIBRARY__ */
56 char *getenv ();
57 char *malloc ();
58 #endif /* STDC_HEADERS or __GNU_LIBRARY__ */
60 #if defined(USG) || defined(STDC_HEADERS) || defined(__GNU_LIBRARY__)
61 #include <string.h>
62 #define bcopy(s, d, n) memcpy ((d), (s), (n))
63 #define index strchr
64 #else /* USG or STDC_HEADERS or __GNU_LIBRARY__ */
65 #ifdef VMS
66 #include <string.h>
67 #else /* VMS */
68 #include <strings.h>
69 #endif /* VMS */
70 /* Declaring bcopy causes errors on systems whose declarations are different.
71 If the declaration is omitted, everything works fine. */
72 #endif /* USG or STDC_HEADERS or __GNU_LIBRARY__ */
74 /* For communication from `getopt' to the caller.
75 When `getopt' finds an option that takes an argument,
76 the argument value is returned here.
77 Also, when `ordering' is RETURN_IN_ORDER,
78 each non-option ARGV-element is returned here. */
80 char *optarg = 0;
82 /* Index in ARGV of the next element to be scanned.
83 This is used for communication to and from the caller
84 and for communication between successive calls to `getopt'.
86 On entry to `getopt', zero means this is the first call; initialize.
88 When `getopt' returns EOF, this is the index of the first of the
89 non-option elements that the caller should itself scan.
91 Otherwise, `optind' communicates from one call to the next
92 how much of ARGV has been scanned so far. */
94 int optind = 0;
96 /* The next char to be scanned in the option-element
97 in which the last option character we returned was found.
98 This allows us to pick up the scan where we left off.
100 If this is zero, or a null string, it means resume the scan
101 by advancing to the next ARGV-element. */
103 static char *nextchar;
105 /* Callers store zero here to inhibit the error message
106 for unrecognized options. */
108 int opterr = 1;
110 /* Describe how to deal with options that follow non-option ARGV-elements.
112 If the caller did not specify anything,
113 the default is REQUIRE_ORDER if the environment variable
114 _POSIX_OPTION_ORDER is defined, PERMUTE otherwise.
116 REQUIRE_ORDER means don't recognize them as options;
117 stop option processing when the first non-option is seen.
118 This is what Unix does.
119 This mode of operation is selected by either setting the environment
120 variable _POSIX_OPTION_ORDER, or using `+' as the first character
121 of the list of option characters.
123 PERMUTE is the default. We permute the contents of ARGV as we scan,
124 so that eventually all the non-options are at the end. This allows options
125 to be given in any order, even with programs that were not written to
126 expect this.
128 RETURN_IN_ORDER is an option available to programs that were written
129 to expect options and other ARGV-elements in any order and that care about
130 the ordering of the two. We describe each non-option ARGV-element
131 as if it were the argument of an option with character code 1.
132 Using `-' as the first character of the list of option characters
133 selects this mode of operation.
135 The special argument `--' forces an end of option-scanning regardless
136 of the value of `ordering'. In the case of RETURN_IN_ORDER, only
137 `--' can cause `getopt' to return EOF with `optind' != ARGC. */
139 static enum
141 REQUIRE_ORDER, PERMUTE, RETURN_IN_ORDER
142 } ordering;
144 /* Describe the long-named options requested by the application.
145 _GETOPT_LONG_OPTIONS is a vector of `struct option' terminated by an
146 element containing a name which is zero.
147 The field `has_arg' is 1 if the option takes an argument,
148 2 if it takes an optional argument. */
150 struct option
152 char *name;
153 int has_arg;
154 int *flag;
155 int val;
158 const struct option *_getopt_long_options;
160 int _getopt_long_only = 0;
162 /* Index in _GETOPT_LONG_OPTIONS of the long-named option actually found.
163 Only valid when a long-named option was found. */
165 int option_index;
167 /* Handle permutation of arguments. */
169 /* Describe the part of ARGV that contains non-options that have
170 been skipped. `first_nonopt' is the index in ARGV of the first of them;
171 `last_nonopt' is the index after the last of them. */
173 static int first_nonopt;
174 static int last_nonopt;
176 /* Exchange two adjacent subsequences of ARGV.
177 One subsequence is elements [first_nonopt,last_nonopt)
178 which contains all the non-options that have been skipped so far.
179 The other is elements [last_nonopt,optind), which contains all
180 the options processed since those non-options were skipped.
182 `first_nonopt' and `last_nonopt' are relocated so that they describe
183 the new indices of the non-options in ARGV after they are moved. */
185 static void
186 exchange (argv)
187 char **argv;
189 int nonopts_size = (last_nonopt - first_nonopt) * sizeof (char *);
190 char **temp = (char **) alloca (nonopts_size);
192 /* Interchange the two blocks of data in ARGV. */
194 bcopy (&argv[first_nonopt], temp, nonopts_size);
195 bcopy (&argv[last_nonopt], &argv[first_nonopt],
196 (optind - last_nonopt) * sizeof (char *));
197 bcopy (temp, &argv[first_nonopt + optind - last_nonopt], nonopts_size);
199 /* Update records for the slots the non-options now occupy. */
201 first_nonopt += (optind - last_nonopt);
202 last_nonopt = optind;
205 /* Scan elements of ARGV (whose length is ARGC) for option characters
206 given in OPTSTRING.
208 If an element of ARGV starts with '-', and is not exactly "-" or "--",
209 then it is an option element. The characters of this element
210 (aside from the initial '-') are option characters. If `getopt'
211 is called repeatedly, it returns successively each of the option characters
212 from each of the option elements.
214 If `getopt' finds another option character, it returns that character,
215 updating `optind' and `nextchar' so that the next call to `getopt' can
216 resume the scan with the following option character or ARGV-element.
218 If there are no more option characters, `getopt' returns `EOF'.
219 Then `optind' is the index in ARGV of the first ARGV-element
220 that is not an option. (The ARGV-elements have been permuted
221 so that those that are not options now come last.)
223 OPTSTRING is a string containing the legitimate option characters.
224 If an option character is seen that is not listed in OPTSTRING,
225 return '?' after printing an error message. If you set `opterr' to
226 zero, the error message is suppressed but we still return '?'.
228 If a char in OPTSTRING is followed by a colon, that means it wants an arg,
229 so the following text in the same ARGV-element, or the text of the following
230 ARGV-element, is returned in `optarg'. Two colons mean an option that
231 wants an optional arg; if there is text in the current ARGV-element,
232 it is returned in `optarg', otherwise `optarg' is set to zero.
234 If OPTSTRING starts with `-' or `+', it requests different methods of
235 handling the non-option ARGV-elements.
236 See the comments about RETURN_IN_ORDER and REQUIRE_ORDER, above.
238 Long-named options begin with `+' instead of `-'.
239 Their names may be abbreviated as long as the abbreviation is unique
240 or is an exact match for some defined option. If they have an
241 argument, it follows the option name in the same ARGV-element, separated
242 from the option name by a `=', or else the in next ARGV-element.
243 When `getopt' finds a long-named option, it returns 0 if that option's
244 `flag' field is nonzero, the value of the option's `val' field
245 otherwise. */
248 getopt (argc, argv, optstring)
249 int argc;
250 char **argv;
251 const char *optstring;
253 optarg = 0;
255 /* Initialize the internal data when the first call is made.
256 Start processing options with ARGV-element 1 (since ARGV-element 0
257 is the program name); the sequence of previously skipped
258 non-option ARGV-elements is empty. */
260 if (optind == 0)
262 first_nonopt = last_nonopt = optind = 1;
264 nextchar = 0;
266 /* Determine how to handle the ordering of options and nonoptions. */
268 if (optstring[0] == '-')
270 ordering = RETURN_IN_ORDER;
271 ++optstring;
273 else if (optstring[0] == '+')
275 ordering = REQUIRE_ORDER;
276 ++optstring;
278 else if (getenv ("_POSIX_OPTION_ORDER") != 0)
279 ordering = REQUIRE_ORDER;
280 else
281 ordering = PERMUTE;
284 if (nextchar == 0 || *nextchar == 0)
286 if (ordering == PERMUTE)
288 /* If we have just processed some options following some non-options,
289 exchange them so that the options come first. */
291 if (first_nonopt != last_nonopt && last_nonopt != optind)
292 exchange (argv);
293 else if (last_nonopt != optind)
294 first_nonopt = optind;
296 /* Now skip any additional non-options
297 and extend the range of non-options previously skipped. */
299 while (optind < argc
300 && (argv[optind][0] != '-'
301 || argv[optind][1] == 0)
302 && (_getopt_long_options == 0
303 || argv[optind][0] != '+'
304 || argv[optind][1] == 0))
305 optind++;
306 last_nonopt = optind;
309 /* Special ARGV-element `--' means premature end of options.
310 Skip it like a null option,
311 then exchange with previous non-options as if it were an option,
312 then skip everything else like a non-option. */
314 if (optind != argc && !strcmp (argv[optind], "--"))
316 optind++;
318 if (first_nonopt != last_nonopt && last_nonopt != optind)
319 exchange (argv);
320 else if (first_nonopt == last_nonopt)
321 first_nonopt = optind;
322 last_nonopt = argc;
324 optind = argc;
327 /* If we have done all the ARGV-elements, stop the scan
328 and back over any non-options that we skipped and permuted. */
330 if (optind == argc)
332 /* Set the next-arg-index to point at the non-options
333 that we previously skipped, so the caller will digest them. */
334 if (first_nonopt != last_nonopt)
335 optind = first_nonopt;
336 return EOF;
339 /* If we have come to a non-option and did not permute it,
340 either stop the scan or describe it to the caller and pass it by. */
342 if ((argv[optind][0] != '-' || argv[optind][1] == 0)
343 && (_getopt_long_options == 0
344 || argv[optind][0] != '+' || argv[optind][1] == 0))
346 if (ordering == REQUIRE_ORDER)
347 return EOF;
348 optarg = argv[optind++];
349 return 1;
352 /* We have found another option-ARGV-element.
353 Start decoding its characters. */
355 nextchar = argv[optind] + 1;
358 if (_getopt_long_options != 0
359 && (argv[optind][0] == '+'
360 || (_getopt_long_only && argv[optind][0] == '-'))
363 const struct option *p;
364 char *s = nextchar;
365 int exact = 0;
366 int ambig = 0;
367 const struct option *pfound = 0;
368 int indfound;
370 while (*s && *s != '=')
371 s++;
373 /* Test all options for either exact match or abbreviated matches. */
374 for (p = _getopt_long_options, option_index = 0; p->name;
375 p++, option_index++)
376 if (!strncmp (p->name, nextchar, s - nextchar))
378 if (s - nextchar == strlen (p->name))
380 /* Exact match found. */
381 pfound = p;
382 indfound = option_index;
383 exact = 1;
384 break;
386 else if (pfound == 0)
388 /* First nonexact match found. */
389 pfound = p;
390 indfound = option_index;
392 else
393 /* Second nonexact match found. */
394 ambig = 1;
397 if (ambig && !exact)
399 fprintf (stderr, "%s: option `%s' is ambiguous\n",
400 argv[0], argv[optind]);
401 nextchar += strlen (nextchar);
402 optind++;
403 return '?';
406 if (pfound != 0)
408 option_index = indfound;
409 optind++;
410 if (*s)
412 if (pfound->has_arg > 0)
413 optarg = s + 1;
414 else
416 fprintf (stderr,
417 "%s: option `%c%s' doesn't allow an argument\n",
418 argv[0], argv[optind - 1][0], pfound->name);
419 nextchar += strlen (nextchar);
420 return '?';
423 else if (pfound->has_arg == 1)
425 if (optind < argc)
426 optarg = argv[optind++];
427 else
429 fprintf (stderr, "%s: option `%s' requires an argument\n",
430 argv[0], argv[optind - 1]);
431 nextchar += strlen (nextchar);
432 return '?';
435 nextchar += strlen (nextchar);
436 if (pfound->flag)
438 *(pfound->flag) = pfound->val;
439 return 0;
441 return pfound->val;
443 /* Can't find it as a long option. If this is getopt_long_only,
444 and the option starts with '-' and is a valid short
445 option, then interpret it as a short option. Otherwise it's
446 an error. */
447 if (_getopt_long_only == 0 || argv[optind][0] == '+' ||
448 index (optstring, *nextchar) == 0)
450 if (opterr != 0)
451 fprintf (stderr, "%s: unrecognized option `%c%s'\n",
452 argv[0], argv[optind][0], nextchar);
453 nextchar += strlen (nextchar);
454 optind++;
455 return '?';
459 /* Look at and handle the next option-character. */
462 char c = *nextchar++;
463 char *temp = index (optstring, c);
465 /* Increment `optind' when we start to process its last character. */
466 if (*nextchar == 0)
467 optind++;
469 if (temp == 0 || c == ':')
471 if (opterr != 0)
473 if (c < 040 || c >= 0177)
474 fprintf (stderr, "%s: unrecognized option, character code 0%o\n",
475 argv[0], c);
476 else
477 fprintf (stderr, "%s: unrecognized option `-%c'\n",
478 argv[0], c);
480 return '?';
482 if (temp[1] == ':')
484 if (temp[2] == ':')
486 /* This is an option that accepts an argument optionally. */
487 if (*nextchar != 0)
489 optarg = nextchar;
490 optind++;
492 else
493 optarg = 0;
494 nextchar = 0;
496 else
498 /* This is an option that requires an argument. */
499 if (*nextchar != 0)
501 optarg = nextchar;
502 /* If we end this ARGV-element by taking the rest as an arg,
503 we must advance to the next element now. */
504 optind++;
506 else if (optind == argc)
508 if (opterr != 0)
509 fprintf (stderr, "%s: option `-%c' requires an argument\n",
510 argv[0], c);
511 c = '?';
513 else
514 /* We already incremented `optind' once;
515 increment it again when taking next ARGV-elt as argument. */
516 optarg = argv[optind++];
517 nextchar = 0;
520 return c;
524 #ifdef TEST
526 /* Compile with -DTEST to make an executable for use in testing
527 the above definition of `getopt'. */
530 main (argc, argv)
531 int argc;
532 char **argv;
534 int c;
535 int digit_optind = 0;
537 while (1)
539 int this_option_optind = optind ? optind : 1;
541 c = getopt (argc, argv, "abc:d:0123456789");
542 if (c == EOF)
543 break;
545 switch (c)
547 case '0':
548 case '1':
549 case '2':
550 case '3':
551 case '4':
552 case '5':
553 case '6':
554 case '7':
555 case '8':
556 case '9':
557 if (digit_optind != 0 && digit_optind != this_option_optind)
558 printf ("digits occur in two different argv-elements.\n");
559 digit_optind = this_option_optind;
560 printf ("option %c\n", c);
561 break;
563 case 'a':
564 printf ("option a\n");
565 break;
567 case 'b':
568 printf ("option b\n");
569 break;
571 case 'c':
572 printf ("option c with value `%s'\n", optarg);
573 break;
575 case '?':
576 break;
578 default:
579 printf ("?? getopt returned character code 0%o ??\n", c);
583 if (optind < argc)
585 printf ("non-option ARGV-elements: ");
586 while (optind < argc)
587 printf ("%s ", argv[optind++]);
588 printf ("\n");
591 exit (0);
594 #endif /* TEST */